一、环境准备
1.服务器
2.微信公众号
3. 会php,thinkphp和服务器的基本操作
二、我的环境
1. 阿里云学生服务器
2. php5.4(TP3.1的情况下不建议用PHP7,各种BUG)
3. thinkphp 3.1
4. 工具:Xshell6 ,WinScp,Beyond Compare
thinkphp目录结构:
云翼计划
thinkphp3.1教程
基于thinphp3.1开发微信公众号教程
微信公众号开发文档
三、开启微信公众号开发者模式
登录微信公众号->开发>基本配置,我的配置如下
- 注意:
- 如果开发者密码(APPSercret)第一次开启,生成的密码需要自己妥善保存,以后将不会再显示
- 并且要在IP白名单中添加自己的ip或者域名,这样才能调用access_token
三、服务端对应代码
public function index() {//输入imooc.php的时候默认加载这里
//获得参数
$nonce = $_GET['nonce'];
$token = 'imooc';//就是在公众号填写的Token
$timestamp = $_GET['timestamp'];
$echostr = $_GET['echostr']; //只有第一次验证才会传这个参数
$signature = $_GET['signature'];
//形成数组
$array = array($nonce, $timestamp, $token);
sort($array);
//拼接成字符串,sha1加密,与signature进行校验
$str = sha1(implode($array));
if ($str == $signature && $echostr) {
//第一次接入weixin api接口的时候
echo $echostr;
exit;
} else {
$this->reponseMsg();//第二次以及以后的情况都自动调用下面的处理函数
}
}
四、关注事件响应函数(reponseMsg)
public function reponseMsg() {
//1.获取到微信推送过来的post数据(xml格式)
// $postArr=$GLOBALS['HTTP_RAW_POST_DATA'];//php7不能使用
$postArr = file_get_contents("php://input"); //这是php7专 用格式!!!
//2.处理消息类型,并设置回复类型和内容
$postObj = simplexml_load_string($postArr);
if (strtolower($postObj->MsgType) == 'event') {
//-------------------订阅事件
//如果是关注subscribe事件
if (strtolower($postObj->Event )== 'subscribe') {
$content = "欢迎关注骁哥的公众号,本公众号正在后台开发中,敬请期待....\n目前的功能有:\n1.天气预报(输入'城市+天气',eg:珠海天气)";
}
$indexModel = new indexModel();
$indexModel->reponseText($postObj, $content);
}
以上函数均放在Imooc/Lib/Action/indexAction.class.php中
五、响应函数reponseText
放在Imooc/Lib/Model/indexModel.class.php中
class indexModel {
public function reponseText($postObj, $content) {
$template = " <xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml> ";//返回的格式
$toUser = $postObj->FromUserName; //订阅公众号的对象就是要发送的对象
$fromUser = $postObj->ToUserName;
$time = time();
$msgType = 'text';
$info = sprintf($template, $toUser, $fromUser, $time, $msgType, $content);
echo $info;
}
}
六、 测试结果
关注后:
BUG解决方案:
1.关于thinkphp3.1在php7下显示空白的解决方案
thinkphp3.1在php7下显示空白