1. 首先到“微信公众平台”,申请公众号,类别选择“订阅号”。
2. 申请成功后到新浪云申请一个SAE,我是用微博账号直接申请的
3. 在“控制台”->“应用管理”->“创建新应用”->“设定二次域名”->选择开发语言:PHP5.3空应用
4. 下载wx_sample.php,修改如下(亲测可用):
<?php
/**
* wechat php test
*/
//define your token
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
if (isset($_GET['echostr'])) { //后加的
$wechatObj->valid();
}else{
$wechatObj->responseMsg();
}
class wechatCallbackapiTest
{
public function valid()
{
$echoStr = $_GET["echostr"];
//valid signature , option
if($this->checkSignature()){
header('content-type:text'); //后加的
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;
}
}
}
?>
5. 用Git部署代码:”控制台“->”代码管理“-按照“Git代码部署说明”执行。现在你在SAE上已经有了一个云应用了,它之后将负责与微信服务器的通信。
6. 回到微信公众平台->“开发”->"基本配置":设置URL,就是http://xxx.sinaapp.com/wx_sample.php (xxx是你SAE中的二级域名);设置Token,就是php代码中写的”weixin“;设置EncodingAESKey,随机生成;消息加解密方式:我选择的是兼容模式;然后提交。
7. 此时应该显示”提交成功“
8. 在微信中搜索你的公众号并添加,随意发送消息,公众号会回复:”Welcom to wechat world!"