第一步:拥有自己的公众号以及服务器(及域名)。
第二步:申请测试账号,一定记住开发者密码(AppSecret),不然就只能重置了。
第三步:进入微信公共平台,点击开发
->基本配置
->服务器配置
->修改规则
填入以下信息
URL
:就是你的服务器的URL(要能响应TOKEN验证,还要能在外网访问到这个服务器)
TOKEN
:这个算是自己设置的一个验证码,要自己在代码里面设置的(并且当微信服务器器把GET请求发到你的服务器的时候,能返回这个值)
注:微信服务器的GET请求会带四个参数signature,token,timestamp,echostr
;POST请求会带三个参数除了刚才的echostr
- 获得参数 signature nonce token timestamp echostr
- 形成数组,然后按字典序排序
- 拼接成字符串,sha1加密 ,然后与signature进行校验
实例代码:
<?php
/**
* wechat php test
*/
//define your token;TOKEN一定和你自己的对应起来
define("TOKEN", "weixin");
$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)){
/* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
the best way is to check the validity of xml by yourself */
libxml_disable_entity_loader(true);
$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()
{
// you must define TOKEN by yourself
if (!defined("TOKEN")) {
throw new Exception('TOKEN is not defined!');
}
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$token = TOKEN;
$tmpArr = array($token, $timestamp, $nonce);
// use SORT_STRING rule
sort($tmpArr, SORT_STRING);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
}
?>
EncodingAeskey
:直接点击随机生成就好了。
提交之后,会提醒你配置成功。