微信公众号三方平台开发【component_verify_ticket篇】

在第三方平台创建审核通过之后后,微信服务器会每隔10分钟定时向“授权事件接收URL”推送component_verify_ticket,第三方平台方收到component_verify_ticket推送后需对其进行解密操作,且在接收到之后必须直接返回字符串success(这个推送过来的component_verify_ticket很重要,这在第三方平台后续功能实现上都需要用到)。

微信服务器将信息用XML数据格式,以POST方式推送到我们的服务器,官方有提供相应的数据示例以及字段说明。

POST数据示例

<xml>
<AppId></AppId>
<CreateTime>1413192605</CreateTime>
<InfoType></InfoType>
<ComponentVerifyTicket></ComponentVerifyTicket>
</xml>

字段说明

字段名称 字段描述
AppId 第三方平台appid
CreateTime 时间戳
InfoType component_verify_ticket
ComponentVerifyTicket Ticket内容

这一步也是折腾我最久的地方,主要问题就是推送过来的信息是加密的我们需要先将信息解密,解密出component_verify_ticket后将该ticket保存起来。

不过这部分官方有提供相应语言的解密DEMO,下面附上我自己这块的完整代码,里面用到了数据库操作以及微信公众号取消授权的操作:
public function ticket(){
require_once(dirname(FILE).'/wxBizMsgCrypt.php');//该文件在官方demo里面,下载后引入进来就可以了
$encodingAesKey = '';//创建平台时填写的公众号消息加解密Key
$token = '';//创建平台时填写的公众号消息校验Token
$appId = '';//公众号第三方平台AppID
$timeStamp = empty ( $_GET ['timestamp']) ? "" : trim ( $_GET ['timestamp'] );
$nonce = empty ( $_GET ['nonce'] ) ?"" : trim ( $_GET ['nonce'] );
$msg_sign = empty ( $_GET['msg_signature'] ) ? "" : trim ( $_GET ['msg_signature'] );
$encryptMsg = file_get_contents ('php://input' );
$pc = new \WXBizMsgCrypt ( $token,$encodingAesKey, $appId );
// 第三方收到公众号平台发送的消息
$msg = '';
$errCode = $pc->decryptMsg ($msg_sign, $timeStamp, $nonce, $encryptMsg, $msg );
if ($errCode == 0) {
$data = $this->_xmlToArr ( $msg);
if (isset ( $data['ComponentVerifyTicket'] )) {
$config['componentverifyticket'] = $data ['ComponentVerifyTicket'];
$config['create_time'] =date("Y-m-d H:i:s");
$where['id']= '1';
M('Public')->where($where)->setField($config);
} elseif ($data ['InfoType'] =='unauthorized') {
// 在公众号后台取消授权后,同步把系统里的公众号删除掉,并更新相关用户缓存
$map ['appid'] = $data['AuthorizerAppid'];
$map2 ['id'] = M ('WechatPublic' )->where ( $map )->getField ( 'id' );
if ($map2 ['id']) {
M ( 'WechatPublic')->where ( $map2 )->delete();
}
}
echo 'success';
} else {
echo '解密失败'.$errCode;
}
}
public function _xmlToArr($xml) {
$res = @simplexml_load_string ( $xml,NULL, LIBXML_NOCDATA );
$res = json_decode ( json_encode ( $res), true );
return $res;
}

后面接收微信服务推送的消息都需要解密,该方法都可以解密。

猜你喜欢

转载自blog.csdn.net/joelingwei/article/details/72876730