1. 程式人生 > >微信公眾號三方平臺開發【component_verify_ticket篇】

微信公眾號三方平臺開發【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;
}

後面接收微信服務推送的訊息都需要解密,該方法都可以解密。