申请第三方平台(https://open.weixin.qq.com/)过程中,需要在开发资料中填写 授权事件接收URL 。
授权事件接收URL主要用于微信服务器发送给第三方平台自身的通知或事件推送(如取消授权通知,component_verify_ticket 推送等)。其中主要的就是获取component_verify_ticket,在调用其他API接口时都需要用到这一参数,同时这一参数是会过期的,每10分钟会发送一次,每1小时更新一次,因此需要在服务器端处理时进行保存(数据库或缓存中)。
微信有提供wxBizMsgCrypt.php加解密核心代码,用于解密消息与事件接收URL收到的微信服务器消息,下载地址为:https://res.wx.qq.com/op_res/-serEQ6xSDVIjfoOHcX78T1JAYX-pM_fghzfiNYoD8uHVd3fOeC0PC_pvlg4-kmP。(来源:https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/Message_Encryption/Message_encryption_and_decryption.html)
PHP源码
/**
* [授权事件接收URL description]
* @return [type] [description]
*/
public function wechat_authorize_recieve(){
$access_token = C('WechatThirdParty.access_token');
$encodingAesKey = C('WechatThirdParty.EncodingAESKey');
$appid = C('WechatThirdParty.appid');
//解密信息
$pc = new \Org\Com\WXBizMsgCrypt\WXBizMsgCrypt($access_token,$encodingAesKey,$appid);
$pc->WXBizMsgCrypt($access_token,$encodingAesKey,$appid);
$nonce = I('get.nonce');
$timeStamp = I('get.timestamp');
$msg_sign = I('get.msg_signature');
$from_xml = $GLOBALS["HTTP_RAW_POST_DATA"];
$msg = '';
$errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
sae_debug('[授权事件接收URL]:'.$msg);
//给微信官方回复信息
if ($errCode == 0) {
echo 'success';
} else {
print($errCode . "\n");
}
$xml_tree = new DOMDocument();
$xml_tree->loadXML($msg);
$InfoType = $xml_tree->getElementsByTagName('InfoType')->item(0)->nodeValue;
if($InfoType != 'component_verify_ticket'){
die();
}
$array_e = $xml_tree->getElementsByTagName('ComponentVerifyTicket');
$ComponentVerifyTicket = $array_e->item(0)->nodeValue;
$data = array();
if($errCode == 0) {
$data['value'] = $ComponentVerifyTicket;
}
sae_debug('[授权事件接收URL]ComponentVerifyTicket:'.json_encode($ComponentVerifyTicket));
//更新表中component_verify_ticket
$Configure = M('Configure');
$where = array();
//0在表中表示平台配置
$where['company_id'] = 0;
$where['name'] = 'component_verify_ticket';
$Configure->where($where)->save($data);
}
注意事项
1.代码使用的是ThinkPHP架构,部分语句需要进行适配;
2.注意函数名称和函数所属类,决定了url的具体地址;
3. sae_debug 用于在新浪云sae中打印调试日志,可以删去;
4. component_verify_ticket 保存在了数据库的 Configure 表中;
5.使用到的 access_token 、 encodingAesKey 和 appid 三个变量分别为预置在ThinkPHP框架中的第三方平台的 消息校验Token 、 消息加解密Key 和 第三方平台的APPID,前两者在开发配置中同样需要填写(第一幅图中所示),只要在腾讯后台和代码中保持一致即可,APPID可以在平台查看。
6.实例化的 WXBizMsgCrypt 使用了微信官方提供的库,下载地址为:https://download.csdn.net/download/Ximerr/15651996(如果积分不够可以一键三连后站内信)