微信小程序配置消息推送的时候一般都会出现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;
}
}
}
?>
以上两种实例代码选择一种直接上传到你的服务器上,在消息配置中的url(服务器地址写上php文件的服务器地址),填入对应的自定义Token(令牌),消息加密密钥随机生成即可,加密方式我的填了兼容模式,数据格式随个人喜好吧(
我的填了JSON)。然后直接点击提交即可。如果出现下图说明验证通过了: