基于 PHP 的微信公众平台开发
一、服务器配置
申请微信公众平台,进入管理界面。开发 -> 基本配置,在服务器配置面板中点击修改配置,URL是你的服务器地址(http://myserver/index.php),Token随便设置一个字符串(hello2017),EncodingAESKey随机生成,消息加密方式选择“明文模式”。
二、测试
在web服务器访问目录下创建index.php文件,内容如下:
<?php
define("TOKEN", "YoonPer"); //TOKEN值
$wechatObj = new wechat();
$wechatObj->valid();
class wechat {
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;
}
}
}
?>
点击提交,验证成功的话回到配置界面,点击“开启”。如果提示“token验证失败”,可以在echo $echoStr;
语句前加入ob_clean()
。因为在输出$echoStr
之前可能会有一些缓存内容,需要先清除,否则影响微信公众平台的识别。
三、通信
微信公众平台与后台服务器采用xml格式通信:
粉丝发给公众号消息格式
<xml>
<ToUserName><![CDATA[公众号]]></ToUserName>
<FromUserName><![CDATA[粉丝号]]></FromUserName>
<CreateTime>1460537339</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[欢迎开启公众号开发者模式]]></Content>
<MsgId>6272960105994287618</MsgId>
</xml>
公众号发给粉丝消息格式
<xml>
<ToUserName><![CDATA[粉丝号]]></ToUserName>
<FromUserName><![CDATA[公众号]]></FromUserName>
<CreateTime>1460541339</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[test]]></Content>
</xml>
例子:
<?php
// index.php [ 微信公众平台接口 ]
$wechatObj = new wechat();
$wechatObj->responseMsg();
class wechat {
public function responseMsg() {
//---------- 接 收 数 据 ---------- //
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //获取POST数据
//用SimpleXML解析POST过来的XML数据
$postObj = simplexml_load_string($postStr,'SimpleXMLElement',LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName; //获取发送方帐号(OpenID)
$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>";
$msgType = "text"; //消息类型
$contentStr = 'hello'; //返回消息内容
//格式化消息模板
$resultStr = sprintf($textTpl,$fromUsername,$toUsername,$time,$msgType,$contentStr);
echo $resultStr; //输出结果
}
}
?>
本作品采用《CC 协议》,转载必须注明作者和本文链接
返回为空啊 - -