PHP实现微信公众账号开发
程序员文章站
2023-12-27 19:10:33
...
1、首先需要一个可以外网访问的接口url。
我这里是申请的新浪免费云服务器,http://xxxxx.applinzi.com/wx.php,具体自己可以去新浪云中心申请地址为:http://www.sinacloud.com
2、去微信公众账号申请个人的公众账号,地址为:https://mp.weixin.qq.com,然后进入到左侧菜单开发里面选择基本配置。
3、点击修改配置,填写必要的信息,认证如下图:
需要在wx.php里面写入认证代码,具体代码下文会提供。
4、等待认证成功后,启用配置
附详细代码:
1 valid(); 6 7 class wechatCallbackapiTest { 8 public function valid() 9 { 10
//这里是认证过程
$echoStr = $_GET["echostr"]; 11 if($this->checkSignature() && $echoStr) { 12 echo $echoStr; 13 exit; 14 } else { 15 $this->responseMsg();//当认证成功后执行下面的代码 16 } 17 } 18 19 private function responseMsg() { 20 21 $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; 22 if (!empty($postStr)) { 23 libxml_disable_entity_loader(true); 24 $textTpl = "25 "; 32 $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); 33 //第一次关注的时候 34 if (strtolower($postObj->MsgType) == 'event') { 35 if (strtolower($postObj->Event) == 'subscribe') { 36 $toUsername = $postObj->ToUserName; 37 $fromUsername = $postObj->FromUserName; 38 $time = time(); 39 $msgType = "text"; 40 $contentStr = ">"; 41 $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); 42 echo $resultStr; 43 } 44 //关键字文本回复 45 } else if ( strtolower($postObj->MsgType) == 'text' ) { 46 if ( $postObj->Content == 'imooc' ) { 47 $toUsername = $postObj->ToUserName; 48 $fromUsername = $postObj->FromUserName; 49 $time = time(); 50 $msgType = "text"; 51 $contentStr = "imooc is very good"; 52 $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); 53 echo $resultStr; 54 exit; 55 } else if ( $postObj->Content == '美丽说' ) { 56 $array = array( 57 array( 58 'title' => 'meilishuo', 59 'description'=> 'meilishuo is very good', 60 'picurl' => 'http://d05.res.meilishuo.net/img/_o/67/24/65bc4ebfe22d0c2eca1702c9736c_117_43.ch.png', 61 'url' => 'http://www.meilishuo.com' 62 ) 63 ); 64 $imageTpl = "26 27 %s 2829 30 0 3165 "; 81 $toUsername = $postObj->ToUserName; 82 $fromUsername = $postObj->FromUserName; 83 $time = time(); 84 $msgType = "news"; 85 $resultStr = sprintf($imageTpl, $fromUsername, $toUsername, $time, $msgType); 86 echo $resultStr; 87 exit; 88 } 89 } 90 91 } else { 92 echo ""; 93 exit; 94 } 95 96 } 97 98 private function checkSignature() { 99 if (!defined("TOKEN")) {100 throw new Exception('TOKEN is not defined!');101 }102 103 $signature = $_GET["signature"];104 $timestamp = $_GET["timestamp"];105 $nonce = $_GET["nonce"]; 106 $token = TOKEN;107 $tmpArr = array($token, $timestamp, $nonce);108 sort($tmpArr, SORT_STRING);109 $tmpStr = implode( $tmpArr );110 $tmpStr = sha1( $tmpStr );111 return ($tmpStr == $signature) ? true : false;112 }113 }66 67 %s 6869 ".count($array)." 70"; 71 foreach ($array as $key => $value) { 72 $imageTpl .= 73 " - 74
"; 79 } 80 $imageTpl .= "75 76 77 78