微信開發者接入 代碼的流程為
1 驗證消息簽名, 判斷是否接口接入
2 實例exRequest消息,構造函數可確保取出ToUserName參數
3 實例化WechatConfig類,傳入參數ToUserName,通過ToUserName獲取 appid secret,encryptType等參數
4 提取微信消息exRequest->extractMsg($encryptType, $config, false);
5 判斷消息類型,對應類型處理器接管
消息處理器接管后 實現消息保存,聊天場景定位,消息回復等業務
~~~
<?php
namespace app\exwechat\controller;
use youwen\exwechat\exLog;
use youwen\exwechat\exWechat;
use youwen\exwechat\exRequest;
/**
* 微信交互控制器
* @author baiyouwen <youwen21@yeah.net>
*/
class index
{
// 微信消息對象
private $exRequest;
// 數組消息體 - 微信消息對象的局部信息
private $_msg;
/**
* 微信消息入口
*
* @author baiyouwen
*/
public function index()
{
exLog::log($_GET, 'get');
exLog::log(file_get_contents("php://input"), 'post');
// 微信驗證控制器
$exwechat = new exWechat();
// 接口配置 和 簽名驗證
$ret = $exwechat->authentication();
if(is_bool($ret)){
if(!$ret){
exit('簽名驗證失敗');
}
}else{ //接口配置 開發者模式接入
exit($ret);
}
// 微信消息單例 和 驗證消息簽名
$this->exRequest = exRequest::instance();
$ToUserName = $this->exRequest->getToUserName();
// 根據ToUserName獲取 appid, token等對應信息
$conf = new WechatConfig($ToUserName);
$config = [];
$config['appid'] = $conf->appid;
$config['token'] = $conf->token;
$config['encodingAesKey'] = $conf->encodingAesKey;
// $encryptType = $conf->encryptType;
$encryptType = 2;
// 提取微信消息
$this->exRequest->extractMsg($encryptType, $config, false);
if($this->exRequest->errorCode){
exit($this->exRequest->errorMsg);
}
// 獲取用戶發來的消息 - 數組格式
$this->_msg = $this->exRequest->getMsg();
// 微信消息分類處理
$this->_msgTypeHandle();
}
/**
* 微信消息分類處理
* 消息分類控制器接管后續操作
* @author baiyouwen
*/
public function _msgTypeHandle()
{
switch ($this->_msg['MsgType']) {
// 點擊菜單與關注
case 'event':
$cls = new HandleEvent($this->_msg);
$ret = $cls->handle();
break;
// 文本消息
case 'text':
$cls = new HandleText($this->_msg);
$ret = $cls->handle();
break;
// 圖片消息
case 'image':
$cls = new HandleDefault();
$ret = $cls->handle('你發了個圖片,我告訴你圖片不要隨便發。尤其不要發臉部照片,不安全。');
break;
// 地理位置
case 'location':
$cls = new HandleLocation($this->_msg);
$ret = $cls->handle();
break;
// 音頻消息
case 'voice':
// 視頻消息
case 'video':
// 鏈接
case 'link':
default:
$cls = new HandleDefault($this->_msg);
$ret = $cls->handle();
}
}
}
~~~