接入微信公众平台开发,开发者需要按照如下步骤完成:
1、填写服务器配置
2、验证服务器地址的有效性
1、填写服务器配置

将需要填写的东西填好后就可提交。注意token和php代码中的token要保持一致,不一定是weixin可自行设定。
2、验证服务器地址的有效性
<?php
/**
* wechat php test
*/
//define your token
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();
class wechatCallbackapiTest
{
public function valid()
{
$echostr = $_GET["echostr"];//随机字符串
//判断是否来自微信端
if($this->checkSignature()){
echo $echostr;
exit;
}else{
$this->responseMsg();
}
}
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('msg.txt',$postStr,FILE_APPEND);//生成文件
//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"];//微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
$timestamp = $_GET["timestamp"];//时间戳
$nonce = $_GET["nonce"]; //随机数
//1)将token、timestamp、nonce三个参数进行字典序排序
//2)将三个参数字符串拼接成一个字符串进行sha1加密
//3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
$token = TOKEN;
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
}
?>将php文件放入到服务器上后,关注自己的微信测试号,发送消息后它会自动回复消息。
847

被折叠的 条评论
为什么被折叠?



