相信很多人会跟我一样,token验证之后,发送消息给订阅号,没有消息返回。
以下,说一下我辛苦调试得到的解决办法:
首先,token验证:
自己写的token一直验证失败,找了好久,没有发现bug。实在没办法,就用了官方的示例代码。并且通过示例代码调试,发现了一个让我吐血的bug(也不算bug):
token验证貌似要求字符编码格式!!!!
官方的示例代码,直接上传到服务器,token直接过!
把官方示例代码改为utf-8格式,再上传覆盖,token失败!失败!失败!
后来,把自己写的修改为ansi格式还是token失败!醉了醉了!那只好用官方示例代码。在此,说下,token是一次握手验证,验证过一次就不用了。
下面,言归正传,貌似偏题了...orz
token验证之后,直接用官方示例代码,赶紧测试自己的订阅号,结果....发出去的消息就跟泼出去的水一样,什么鬼都没有返回...orz
又各种找bug,各种群问,各种搜索....历经本博主九九八十一的努力,终于找出了问题所在(这里是指我自己开发的,并不包括全部,如果你有不同的bug,欢迎交流):
1、最容易被忽视的一个bug,官方给的示例代码,压根就没调用写好的那个responsemsg()函数!
2、把之前的token代码注释,也就是$wechatobj->valid();这行代码。因为toke验证那段代码会有一个echo $echostr,会把responsemsg()函数里的echo $resultstr;(56行)xml格式混乱,输回给微信服务器就无法识别了(貌似只能识别xml格式,还有json格式)。(token验证是一次握手验证,验证开发者之后,就可以不用了,赶紧让它消失在我们整洁的代码orz...)
3、最恶心的一个bug,还是字符编码问题!orz...xml要求utf-8编码,所以,把示例代码改回utf-8编码!这个bug找的让我崩溃!!!
下面是我修改后的代码,能正常运行,无bug,需要的可以参考一下
<?php
/**
* wechat php test
*/
//define your token
define("token", "codcodog");
$wechatobj = new wechatcallbackapitest();
//$wechatobj->valid();
$wechatobj->responsemsg();
class wechatcallbackapitest
{
public function valid()
{
$echostr = $_get["echostr"];
//valid signature , option
if($this->checksignature()){
header('content-type:text');
echo $echostr;
exit;
}
}
public function responsemsg()
{
//get post data, may be due to the different environments
$poststr = $globals["http_raw_post_data"];
//$poststr = file_get_contents("php://input");
file_put_contents("log.txt",$poststr,file_append );
//extract post data
if (!empty($poststr)){
/* libxml_disable_entity_loader is to prevent xml external entity injection,
the best way is to check the validity of xml by yourself */
libxml_disable_entity_loader(true);
$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></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()
{
// you must define token by yourself
if (!defined("token")) {
throw new exception('token is not defined!');
}
$signature = $_get["signature"];
$timestamp = $_get["timestamp"];
$nonce = $_get["nonce"];
$token = token;
$tmparr = array($token, $timestamp, $nonce);
// use sort_string rule
sort($tmparr, sort_string);
$tmpstr = implode( $tmparr );
$tmpstr = sha( $tmpstr );
if( $tmpstr == $signature ){
return true;
}else{
return false;
}
}
}
?>
以上所述是小编给大家分享的php微信订阅号开发之token验证后自动发送消息给订阅号但是没有消息返回的解决方案,希望大家喜欢。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!