本教程采用的微信开发基于新浪云搭建环境。
登陆后,点击创建应用。
创建版本,输入安全密码
自此已经成功创建 http://1.maizi.applinzi.com
这个应用。
登录微信公众平台,基本配置-服务器配置,填写token,请求地址和和消息模式,在此选择明文模式。
并在ip白名单中填写服务器ip地址
交互分为两种方式:get请求和消息发送。
微信发出GET请求通常包括4个常见字段。
参数 | 描述 |
---|---|
signature | 加密签名,包括token、timestamp和nonce |
timestamp | 时间戳 |
nonce | 随机数 |
echostr | 随机字符串 |
而微信发送消息,请求除了带上token、timestamp和nonce,还会带上一个xml数据包。
<xml>
<ToUserName><![CDATA[账号]]></ToUserName>
<FromUserName><![CDATA[用户名]]></FromUserName>
<CreateTime>时间</CreateTime>
<MsgType><![CDATA[数据类型]]></MsgType>
<Content><![CDATA[%内容]></Content>
<MsgId>消息id</MsgId>
</xml>
交互流程
echottr
字段变量。有则校验,没有则进入消息业务处理流程。
根据上述思想,可以以php实现如下代码。
<?php
/*
hello wechat
*/
header('Content-type:text');
define("TOKEN", "weixin"); //定义token
$wechatObj = new wechatCallbackapiTest();
if (isset($_GET['echostr'])) {
$wechatObj->valid();
}else{
$wechatObj->responseMsg();
}
// 定义类库
class wechatCallbackapiTest
{
public function valid()
{
$echoStr = $_GET["echostr"];
if($this->checkSignature()){
echo $echoStr;
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;
}
}
public function responseMsg()
{
$postStr = $GLOBALS["HTTP_RAW_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($keyword == "?" || $keyword == "?")
{
$msgType = "text";
$content = date("Y-m-d H:i:s",time());
$result = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $content);
echo $result;
}
}else{
echo "";
exit;
}
}
}
?>
接口调试:https://mp.weixin.qq.com/debug
可在此进行各种模拟事件操作。