您好,登錄后才能下訂單哦!
這篇文章主要介紹了php進行微信公眾號開發的方法,具有一定借鑒價值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。
php如何進行微信公眾號開發
1、配置相關服務器
(1) 如下,把自己的服務器ip白名單配置上;
(2) 開始配置令牌,配置令牌時先需要把現成的代碼放到自己的服務器上面,代碼里面包含自己的設置的令牌號碼,這樣才可以配置成功。
注意:下面這個代碼在配置好后,即可從服務器上面刪除代碼或者把index.php改一個名字。
url必須是完整的url,比如 http://118.78.176.74/weixin/index.php
<?php /** * wechat php test * update time: 20141008 */ //define your token //下面的即是你設置的token令牌 define("TOKEN", "zj123456"); $wechatObj = new wechatCallbackapiTest(); $wechatObj->valid(); class wechatCallbackapiTest { public function valid() { $echoStr = $_GET["echostr"]; //valid signature , option if ($this->checkSignature()) { echo $echoStr; exit; } } public function responseMsg() { //get post data, May be due to the different environments $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //extract post data if (!empty($postStr)) { $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); $time = time(); $textTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <Content><![CDATA[%s]]></Content> <FuncFlag>0</FuncFlag> </xml>"; if (!empty($keyword)) { $msgType = "text"; $contentStr = "Welcome to wechat world!"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; } else { echo "Input something..."; } } else { echo ""; exit; } } private function checkSignature() { $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; $token = TOKEN; $tmpArr = array($token, $timestamp, $nonce); sort($tmpArr, SORT_STRING); $tmpStr = implode($tmpArr); $tmpStr = sha1($tmpStr); if ($tmpStr == $signature) { return true; } else { return false; } } }
2、配置ok后,接下來就可以實現相關的微信公眾號相關功能,比如說自動回復機器人。
代碼包含3部分,當然,自動回復機器人,下面的代碼有些用不到。
(1) 、index.php
<?php define("APPID","xxxxxxx"); define("APPSECRET","xxxxxx"); define("TOKEN","zj123456"); require("./wechat.inc.php"); $wechat = new WeChat(APPID,APPSECRET,TOKEN); $wechat->responseMsg(); ?>
(2)、wechat.inc.php
<?php class WeChat { private $_appid; private $_appsecret; private $_token; public function __construct($appid, $appsecret, $token) { $this->_appid = $appid; $this->_appsecret = $appsecret; $this->_token = $token; } /** *_request():發出請求 *@curl:訪問的URL *@https:安全訪問協議 *@method:請求的方式,默認為get *@data:post方式請求時上傳的數據 **/ private function _request($curl, $https = true, $method = 'get', $data = null, $headers = null) { $ch = curl_init(); //初始化 curl_setopt($ch, CURLOPT_URL, $curl); //設置訪問的URL // curl_setopt($ch, CURLOPT_HEADER, false); //設置不需要頭信息 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //只獲取頁面內容,但不輸出 if ($https) { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不做服務器認證 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //不做客戶端認證 } if ($method == 'post') { curl_setopt($ch, CURLOPT_POST, true); //設置請求是POST方式 curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //設置POST請求的數據 } $str = curl_exec($ch); //執行訪問,返回結果 curl_close($ch); //關閉curl,釋放資源 return $str; } /** *_getAccesstoken():獲取access token **/ private function _getAccesstoken() { $file = './accesstoken'; //用于保存access token if (file_exists($file)) { //判斷文件是否存在 $content = file_get_contents($file); //獲取文件內容 $content = json_decode($content); //json解碼 if (time() - filemtime($file) < $content->expires_in) //判斷文件是否過期 { return $content->access_token; } //返回access token } $content = $this->_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->_appid . "&secret=" . $this->_appsecret); //獲取access token的json對象 file_put_contents($file, $content); //保存json對象到指定文件 $content = json_decode($content); //進行json解碼 return $content->access_token; //返回access token } /** *_getTicket():獲取ticket,用于以后換取二維碼 *@expires_secords:二維碼有效期(秒) *@type :二維碼類型(臨時或永久) *@scene:場景編號 **/ public function _getTicket($expires_secords = 604800, $type = "temp", $scene = 1) { if ($type == "temp") { //臨時二維碼的處理 $data = '{"expire_seconds":' . $expires_secords . ', "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": ' . $scene . '}}}'; //臨時二維碼生成所需提交數據 return $this->_request("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $this->_getAccesstoken(), true, "post", $data, ''); //發出請求并獲得ticket } else { //永久二維碼的處理 $data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": ' . $scene . '}}}'; //永久二維碼生成所需提交數據 return $this->_request("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $this->_getAccesstoken(), true, "post", $data, ''); //發出請求并獲得ticket } } /** *_getQRCode():獲取二維碼 *@expires_secords:二維碼有效期(秒) *@type:二維碼類型 *@scene:場景編號 **/ public function _getQRCode($expires_secords, $type, $scene) { $content = json_decode($this->_getTicket($expires_secords, $type, $scene)); //發出請求并獲得ticket的json對象 $ticket = $content->ticket; //獲取ticket $image = $this->_request("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . urlencode($ticket) ); //發出請求獲得二維碼圖像 //$file = "./".$type.$scene.".jpg";// 可以將生成的二維碼保存到本地,便于使用 //file_put_contents($file, $image);//保存二維碼 return $image; } public function valid() //檢查安全性 { $echoStr = $_GET["echostr"]; //valid signature , option if ($this->checkSignature()) { echo $echoStr; exit; } } public function responseMsg() { //get post data, May be due to the different environments $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //獲得用戶發送信息 $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); switch ($postObj->MsgType) { case 'event': $this->_doEvent($postObj); break; case 'text': $this->_doText($postObj); break; case 'image': $this->_doImage($postObj); break; case 'voice': $this->_doVoice($postObj); break; case 'video': $this->_doVideo($postObj); break; case 'location': $this->_doLocation($postObj); break; default:exit; } } private function _doEvent($postObj) { //事件處理 switch ($postObj->Event) { case 'subscribe': //訂閱 $this->_doSubscribe($postObj); break; case 'unsubscribe': //取消訂閱 $this->_doUnsubscribe($postObj); break; default:; } } private function _doSubscribe($postObj) { $tpltext = '<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[%s]]></Content> </xml>'; $access_token = $this->_getAccesstoken(); $userInfo = $this->getUserinfo($access_token, $postObj->FromUserName); $str = sprintf($tpltext, $postObj->FromUserName, $postObj->ToUserName, time(), '歡迎您關注' . 'Geroge Zhang' . '的世界!'); //還可以保存用戶的信息到數據庫 echo $str; } private function _doUnsubscribe($postObj) { ; //把用戶的信息從數據庫中刪除 } private function _doText($postObj) { $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); $time = time(); $textTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <Content><![CDATA[%s]]></Content> <FuncFlag>0</FuncFlag> </xml>"; if (!empty($keyword)) { // $data_add = "question=" . $keyword; // $appcode = "2fd264cdc7914b308e51ab986f73fb86"; // $headers = array(); // array_push($headers, "Authorization:APPCODE " . $appcode); // $contentStr = $this->_request("http://jisuznwd.market.alicloudapi.com/iqa/query?question=" . $data_add, false, "GET", '', $headers); $data_add = urlencode($keyword); $contentStr = $this->_request("http://api.qingyunke.com/api.php?key=free&appid=0&msg=" . $data_add, false, "GET", '', ''); $contentStr = json_decode($contentStr, true); if ($contentStr['result'] == 0) { $contentStr = $contentStr['content']; } if ($keyword == "hello") { $contentStr = "你好"; } if ($keyword == "PHP") { $contentStr = "最流行的網頁編程語言!"; } if ($keyword == "JAVA") { $contentStr = "較流行的網頁編程語言!"; } $msgType = "text"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; } exit; } private function _doImage($postObj) { $tpltext = '<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[%s]]></Content> </xml>'; $str = sprintf($tpltext, $postObj->FromUserName, $postObj->ToUserName, time(), '您發送的圖片在' . $postObj->PicUrl . "。"); echo $str; } private function checkSignature() { $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; $token = TOKEN; $tmpArr = array($token, $timestamp, $nonce); sort($tmpArr, SORT_STRING); $tmpStr = implode($tmpArr); $tmpStr = sha1($tmpStr); if ($tmpStr == $signature) { return true; } else { return false; } } /** * 獲取用戶昵稱 * @param access_token 前面函數_getAccesstoken已經實現 * @param openid 即FromUserName這個參數 * url $urlid = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN'; * return userInfo */ public function getUserinfo($access_token, $openid) { $urlid = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN'; $userInfo = $this->_request($urlid); return $userInfo; } }
注意:想要獲取用戶信息必須是認證過了的訂閱號或者服務號!
綜上,把如上三個文件,放到你的配置的服務器上面,即可實現自動回復機器人功能。
感謝你能夠認真閱讀完這篇文章,希望小編分享php進行微信公眾號開發的方法內容對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,遇到問題就找億速云,詳細的解決方法等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。