微信小程式之訊息推送配置Token驗證失敗-已解決
阿新 • • 發佈:2018-11-28
微信小程式配置訊息推送的時候一般都會出現Token驗證失敗的問題,這個錯誤是因為,你的介面頁面還沒有反饋正確的資訊給微信介面,網友們也給出了一些解決方法,但有些能夠配置成功,有些則不然。下面給出網友提供的2種比較容易配置成功的php介面驗證程式碼。
把程式碼放到可訪問的地址
程式碼示例一(我的驗證可以成功):
<?php //1. 將timestamp , nonce , token 按照字典排序 $timestamp = $_GET['timestamp']; $nonce = $_GET['nonce']; $token = "你自定義的Token值"; $signature = $_GET['signature']; $array = array($timestamp,$nonce,$token); sort($array); //2.將排序後的三個引數拼接後用sha1加密 $tmpstr = implode('',$array); $tmpstr = sha1($tmpstr); //3. 將加密後的字串與 signature 進行對比, 判斷該請求是否來自微信 if($tmpstr == $signature) { echo $_GET['echostr']; exit; }
示例二
<?php /** * wechat php test */ //define your token define("TOKEN", "自定義token"); $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); $tmpStr = implode( $tmpArr ); $tmpStr = sha1( $tmpStr ); if( $tmpStr == $signature ){ return true; }else{ return false; } } } ?>