环境准备
有一台外网可以访问的云服务器
微信公众号端的配置
如下图所示的配置,请填写,其中
- URL: 填写你服务器的地址,即使http://your_address/weixin/index.php
- 令牌:随便填一个即可
在/var/www/html 下建weixin目录,并将以下代码保存到index.php中,然后拷贝到/var/www/html/路径。注意文中的xxxxxx环境你自己的token
<?php
/**
* wechat php test
*/
//define your token
define("TOKEN", "xxxxxx");
$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;
}
}
}
?>
以上完成之后点击提交。
编写测试代码
记得安装 pip3 install werobot
示例代码
import werobot
robot = werobot.WeRoBot(token='xxxxxx')
@robot.handler
def hello(msg):
return 'Hello World!'
robot.config['HOST'] = '0.0.0.0'
robot.config['PORT'] = 80
robot.run()
注意,代码中的token后的xxxxx要和"微信公众号端的配置"中的一致
效果展示:
参考文档
WeRoBot开发文档
(backup)
前面是基于python + WeRoBot开发的公众号自动回复,其实如果单纯是聊天,可以点击自动回复
菜单栏中开启自动回复,然后接入图灵机器人即可。
接入图灵机器人的效果展示:
(您也可以关注此公众进行测试)
更多推荐
微信公众号开发(python+werobot)-自动回复
发布评论