作者:Lanboream | 来源:互联网 | 2023-05-17 10:41
第一步:接收component_verify_ticket:1、微信服务器每隔10分钟会向第三方的消息接收地址推送一次component_verify_ticket,拿到后需要在本地做
第一步:接收component_verify_ticket:
1、微信服务器每隔10分钟会向第三方的消息接收地址推送一次component_verify_ticket,拿到后需要在本地做好存储;
2、微信第三方平台的消息是加密的(下图),需要进行解密才能获取需要的信息;
3、接收并解密消息,代码如下:
- $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 ( OPEN_MSG_VERIFY_TOKEN, OPEN_ENCRYPT_KEY, OPEN_APPID );
- $postArr = ArrayUtil::xml2array ( $encryptMsg );
- $format = "";
- $from_xml = sprintf ( $format, $postArr ['Encrypt'] );
-
- $msg = '';
- $errCode = $pc->decryptMsg ( $msg_sign, $timeStamp, $nonce, $from_xml, $msg );
- if ($errCode == 0) {
- $param = ArrayUtil::xml2array ( $msg );
- switch ($param ['InfoType']) {
- case 'component_verify_ticket' :
- $component_verify_ticket = $param ['ComponentVerifyTicket'];
- $ret ['component_verify_ticket'] = $component_verify_ticket;
- file_put_contents ( OPEN_COMPONENT_VERIFY_TICKET_PATH, $component_verify_ticket );
- break;
- case 'unauthorized' :
- $status = 2;
- break;
- case 'authorized' :
- $status = 1;
- break;
- case 'updateauthorized' :
- break;
- }
- }
第二步:获取component_access_token:
每个令牌是存在有效期(2小时)的,且令牌的调用不是无限制的,请第三方平台做好令牌的管理,在令牌快过期时(比如1小时50分)再进行刷新。所以要对component_access_token做好本地缓存,代码如下:
- $nowTime = time ();
- $getCache = false;
- if (is_file ( OPEN_COMPONENT_ACCESS_TOKEN_PATH )) {
- $cacheJson = file_get_contents ( OPEN_COMPONENT_ACCESS_TOKEN_PATH );
- if (json_decode ( $cacheJson )) {
- $cacheArr = json_decode ( $cacheJson, true );
- if (! empty ( $cacheArr ['component_access_token'] ) && $cacheArr ['expires_in'] > $nowTime + 120) {
- $ret ['errCode'] = 0;
- $ret ['component_access_token'] = $cacheArr ['component_access_token'];
- $getCache = true;
- }
- }
- }
-
- if (! $getCache) {
- $url = WeixinApiLang::$url ['component_token'];
- $ticket = file_get_contents ( OPEN_COMPONENT_VERIFY_TICKET_PATH );
- $data = '{
- "component_appid":"' . OPEN_APPID . '",
- "component_appsecret":"' . OPEN_APPSECRET . '",
- "component_verify_ticket":"' . $ticket . '"
- }';
- $ret = self::requestWeixinAPI ( $url, $data );
-
- if (isset ( $ret ['component_access_token'] )) {
- $cacheArr = array ();
- $cacheArr ['component_access_token'] = $ret ['component_access_token'];
- $ret ['expires_in'] += $nowTime;
- $cacheArr ['expires_in'] = $ret ['expires_in'];
- file_put_contents ( OPEN_COMPONENT_ACCESS_TOKEN_PATH, json_encode ( $cacheArr ) );
- }
- }
第三步:获取pre_auth_code(注意这是预授权码,不是授权码):
- $url = 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=' . $accessToken;
- $data = '{
- "component_appid":"' . OPEN_APPID . '"
- }';
- $ret = self::requestWeixinAPI ( $url, $data );
第四步:使用授权码换取公众号的接口调用凭据和授权信息:
授权码authorization_code是用户“确认授权”后,微信回调时返回的。代码如下:
- $url = 'https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=' . $accessToken;
- $data = '{
- "component_appid":"' . OPEN_APPID . '",
- "authorization_code": "' . $authorization_code . '"
- }';
- $ret = self::requestWeixinAPI ( $url, $data );
到此,授权流程就走完了。。。
接着看看全网发布的测试用例怎么做:
1、模拟粉丝触发专用测试公众号的事件,并推送事件消息到专用测试公众号,第三方平台方开发者需要提取推送XML信息中的event值,并在5秒内立即返回按照下述要求组装的文本消息给粉丝;
2、模拟粉丝发送文本消息给专用测试公众号,第三方平台方需根据文本消息的内容进行相应的响应;
3、模拟粉丝发送文本消息给专用测试公众号,第三方平台方需在5秒内返回空串表明暂时不回复,然后再立即使用客服消息接口发送消息回复粉丝。
代码如下:
- $xmlTpl = "
-
-
- %s
-
-
- ";
- $keyword = isset ( $param ['Content'] ) ? trim ( $param ['Content'] ) : '';
- if(isset($param ['Event']) && $param ['ToUserName'] == 'gh_3c884a361561'){
- $contentStr = $param ['Event'] . 'from_callback';
- }elseif ($keyword == "TESTCOMPONENT_MSG_TYPE_TEXT") {
- $contentStr = "TESTCOMPONENT_MSG_TYPE_TEXT_callback";
- } elseif (strpos ( $keyword, "QUERY_AUTH_CODE:" ) !== false) {
- $ticket = str_replace ( "QUERY_AUTH_CODE:", "", $keyword );
- $contentStr = $ticket . "_from_api";
- $tokenInfo = WechatOpenApiLogic::getAuthorizerAccessTokenByAuthCode ( $ticket );
- $param ['authorizerAccessToken'] = $tokenInfo ['authorization_info'] ['authorizer_access_token'];
- self::sendServiceMsg ( $param ['FromUserName'], $param ['ToUserName'], 1, $contentStr );
- return 1;
- }
- $result = '';
- if (! empty ( $contentStr )) {
- $result = sprintf ( $xmlTpl, $param ['FromUserName'], $param ['ToUserName'], time (), $contentStr );
- if (isset ( $_GET ['encrypt_type'] ) && $_GET ['encrypt_type'] == 'aes') {
- $msgCryptObj = new WXBizMsgCrypt ( OPEN_MSG_VERIFY_TOKEN, OPEN_ENCRYPT_KEY, OPEN_APPID );
- $encryptMsg = '';
- $msgCryptObj->encryptMsg ( $result, $_GET ['timestamp'], $_GET ['nonce'], $encryptMsg );
- $result = $encryptMsg;
- }
- }
全网发布常会遇到的问题如下:
以PHP为例。
1、组件ticket正确接收。分析解密后的XML格式消息内容,如果存在ComponentVerifyTicket字段,将这个值保存到数据库,程序结束直接输出字符串success。
//$msg为解密后的XML格式消息内容
$obj = simplexml_load_string($msg, 'SimpleXMLElement', LIBXML_NOCDATA);
if (isset($obj->ComponentVerifyTicket)) {
saveTicket(strval($obj->ComponentVerifyTicket)); //保存ticket
die('success');
}
2、Api文本消息
首先得判断公众平台模拟发送的用户消息(解密后)Content字段是否以QUERY_AUTH_CODE开头,代码略。
$arr = explode(':',$packet['content']);
$code = $arr[1];
$compOnentVerifyTicket= readTicket(); //读取已保存的ticket
//获取第三方平台
$data = array('component_appid'=>$componentAppId,'component_appsecret'=>$componentAppSecret,'component_verify_ticket'=>$componentVerifyTicket);
$json = @json_encode($data);
$result = http_post("https://api.weixin.qq.com/cgi-bin/component/api_component_token",$json);
msg("Component Token Result:" . var_export($result,true));
$compOnentAccessToken= $result['component_access_token'];
//使用授权码换取公众号的接口调用凭据和授权信息
$data = array('component_appid'=>$componentAppId,'authorization_code'=>$code);
$json = @json_encode($data);
$result = http_post("https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=$componentAccessToken", $json);
msg("Query Auth Result:" . var_export($result,true));
$accessToken = $result['authorization_info']['authorizer_access_token'];
saveAccessToken($accessToken); //保存access_token
$text = $code.'_from_api';
3、消息和事件(需要特别说明一点,开放平台上的文档有点坑,题主截图中显示的后面三个失败的点,须使用客服消息接口发送消息,而非按照《全网发布接入检测说明》中说的回复XML内容)
//$text = 'LOCATIONfrom_callback';
//$text = 'TESTCOMPONENT_MSG_TYPE_TEXT_callback';
$data = array('touser'=>$packet['from'],'msgtype'=>'text','text'=>array('content'=>$text));
$json = @json_encode($data);
$accessToken = readAccessToken(); //读取已保存的access_token
$result = http_post("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$acce