您的位置:首页 > 移动开发 > 微信开发

微信开发(怎样接入微信公众平台,自动回复)

2018-04-07 16:02 429 查看
微信开发,首先要接入微信服务器。接入微信服务器首先要填写服务器地址



其次是验证消息是否来自微信服务器,依据接口文档实现业务逻辑(实现自动回复)

开发者提交信息后,微信服务器将发送GET请求到填写的服务器地址URL上,GET请求携带参数如下表所示:

signature微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
timestamp时间戳
nonce随机数
echostr随机字符串
示例代码:定义一个wechatCallbackapiTest类,(包括校验signature的方法,自动回复的方法,判断是否介入成功的方法)开发者通过检验signature对请求进行校验。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。(其中最核心的代码是: $echoStr = $_GET["echostr"]; echo $echoStr;直接决定是否接入成功)当接入成功后调用responseMsg()方法实现自动回复//define your token
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->run();

class wechatCallbackapiTest
{
public function run()
{
if($this->checkSignature() == false){
die('非法请求');
}

// $echoStr = $_GET["echostr"];
if(isset($_GET["echostr"])){
echo $echoStr;
exit;
}else{
$this->responseMsg();
}

//valid signature , option

}

public function responseMsg()
{
//get post data, May be due to the different environments
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
file_put_contents('demo.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 = "欢迎来到php!";
$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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: