微信开放平台开发-授权、全网发布(PHP)
这两天做了微信开发平台的开发,梳理下。。。
浙江百牛信息技术bainiu.ltd整理发布于博客园
先看看授权的流程:
第一步:接收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 ); // xml对象解析
- $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
- $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做好本地缓存,代码如下:
第三步:获取pre_auth_code(注意这是预授权码,不是授权码):
- $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 ) );
- }
- }
第四步:使用授权码换取公众号的接口调用凭据和授权信息:
- $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 = "<xml>
- <ToUserName><![CDATA[%s]]></ToUserName>
- <FromUserName><![CDATA[%s]]></FromUserName>
- <CreateTime>%s</CreateTime>
- <MsgType><![CDATA[text]]></MsgType>
- <Content><![CDATA[%s]]></Content>
- </xml>";
- $keyword = isset ( $param ['Content'] ) ? trim ( $param ['Content'] ) : '';
- if(isset($param ['Event']) && $param ['ToUserName'] == 'gh_3c884a361561'){ // 案例1
- $contentStr = $param ['Event'] . 'from_callback';
- }elseif ($keyword == "TESTCOMPONENT_MSG_TYPE_TEXT") { // 案例2
- $contentStr = "TESTCOMPONENT_MSG_TYPE_TEXT_callback";
- } elseif (strpos ( $keyword, "QUERY_AUTH_CODE:" ) !== false) { // 案例3
- $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;
- }
- }
写的不是很详细,有疑问留言。。。