[php] 微信开放平台授权和全网发布

一.

 授权流程

 1. 接收component_verify_ticket:

 [1]微信服务器每隔10分钟会向第三方的消息接收地址推送一次component_verify_ticket,拿到后需要在本地做好存储;

 [2]微信第三方平台的消息是加密的(下图),需要进行解密才能获取需要的信息;

 [3]接收并解密消息,代码如下:

[php] view plain copy

 

  1. /** 
  2.      * 授权事件接收URL 
  3.      */  
  4.     public function msg() {  
  5.         import("@.ORG.ArrayTool");  
  6.         import("@.ORG.Weixincrypt.WXBizMsgCrypt");  
  7.         $timestamp = empty($_GET ['timestamp']) ? '' : trim($_GET ['timestamp']);  
  8.         $nonce = empty($_GET ['nonce']) ? '' : trim($_GET ['nonce']);  
  9.         $msgSign = empty($_GET ['msg_signature']) ? '' : trim($_GET ['msg_signature']);  
  10.         $signature = empty($_GET ['signature']) ? '' : trim($_GET ['signature']);  
  11.         $encryptType = empty($_GET ['encrypt_type']) ? '' : trim($_GET ['encrypt_type']);  
  12.         $encryptMsg = file_get_contents('php://input');  
  13.         $wxData = C("platform_setting");  
  14.         $encodingAesKey = $wxData['encodingAesKey'];  
  15.         $token = $wxData['token'];  
  16.         $appId = $wxData['appId'];  
  17.         $Wxcrypt = new WXBizMsgCrypt($token, $encodingAesKey, $appId);  
  18.         $postArr = ArrayTool::xml2array($encryptMsg);  
  19.         $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";  
  20.         $fromXml = sprintf($format, $postArr['Encrypt']);  
  21.         //第三方收到公众号平台发送的消息  
  22.         $msg = '';  
  23.         $errCode = $Wxcrypt->decryptMsg($msgSign, $timestamp, $nonce, $fromXml, $msg); // 解密  
  24.         if ($errCode == 0) {  
  25.             $param = ArrayTool::xml2array($msg);  
  26.             switch ($param['InfoType']) {  
  27.                 case 'component_verify_ticket' :    // 授权凭证  
  28.                     $componentVerifyTicket = $param['ComponentVerifyTicket'];  
  29.                     S('component_verify_ticket_' . $appId, $componentVerifyTicket);  
  30.                     break;  
  31.                 case 'unauthorized' :               // 取消授权  
  32.                     break;  
  33.                 case 'authorized' :                 // 授权  
  34.                     break;  
  35.                 case 'updateauthorized' :           // 更新授权  
  36.                     break;  
  37.             }  
  38.         }  
  39.         exit("success");  
  40.     }  

 2.获取component_access_token:

 [1]每个令牌是存在有效期(2小时)的,且令牌的调用不是无限制的,请第三方平台做好令牌的管理,在令牌快过期时(比如1小时50分)再进行刷新。所以要对component_access_token做好本地缓存,代码如下:

[php] view plain copy

 

  1. $wxData = C("setting");  
  2.         //1. 取得component_verify_ticket  
  3.         $vt = S('component_verify_ticket_' . $wxData['appId']);  
  4.         $at = S('component_access_token_' . $wxData['appId']);  
  5.   
  6.         //2. 获取第三方平台component_access_token  
  7.         if (empty($at) && !empty($vt)) {  
  8.             $url2 = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";  
  9.             $post = array();  
  10.             $post['component_appid'] = $wxData['appId'];  
  11.             $post['component_appsecret'] = $wxData['appSecret'];  
  12.             $post['component_verify_ticket'] = $vt;  
  13.             $return2 = $this->curlPost($url2, $post);  
  14.             if (isset($return2['component_access_token'])) {  
  15.                 $at = $return2['component_access_token'];  
  16.                 S('component_access_token_' . $wxData['appId'], $at, 6600); //缓存1小时50分钟 = 6600秒  
  17.             } else {  
  18.                 return false;  
  19.             }  
  20.         }  

 3.获取pre_auth_code(注意这是预授权码,不是授权码):

 

[php] view plain copy

 

  1. $wxData = C('platform_setting');  
  2.         $appId = $wxData['appId'];  
  3.         $HT = new HttpTool();  
  4.         $at = $HT->getComponentAccessToken();  
  5.         if ($at) {  
  6.             //3.获取预授权码pre_auth_code  
  7.             $url3 = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token={$at}";  
  8.             $post = array();  
  9.             $post['component_appid'] = $appId;  
  10.             $return3 = $HT->curlPost($url3, $post);  
  11.             if (isset($return3['pre_auth_code'])) {  
  12.                 $preauthcode = $return3['pre_auth_code'];  
  13.                 $redirectUrl = C('site_url') . U("User/App/setauth", array('uid' => $uid));  
  14.                 $weixinUrl = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid={$appId}&pre_auth_code={$preauthcode}&redirect_uri={$redirectUrl}";  
  15.                 redirect($weixinUrl);  
  16.                 exit;  
  17.             }  
  18.         }  
  19.         $this->error("亲, 授权失败了!");  

 4.使用授权码换取公众号的接口调用凭据和授权信息:

 

[php] view plain copy

 

  1. //1. 使用授权码换取公众号的接口调用凭据和授权信息  
  2.         import("@.ORG.HttpTool");  
  3.         $HT = new HttpTool();  
  4.         $wxData = C('platform_setting');  
  5.         $caccessToken = $HT->getComponentAccessToken();  
  6.         $url1 = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token={$caccessToken}";  
  7.   
  8.         $post = array();  
  9.         $post['component_appid'] = $wxData['appId'];  
  10.         $post['authorization_code'] = $authcode;  
  11.         $return = $HT->curlPost($url1, $post);  
  12.         if (isset($return['authorization_info'])) {  
  13.             $authinfo = $return['authorization_info'];  
  14.             $authid = $authinfo['authorizer_appid'];  
  15.             $accessToken = $authinfo['authorizer_access_token'];  
  16.             $refreshToken = $authinfo['authorizer_refresh_token'];  
  17.             //$funcInfo = $authinfo['func_info'];  
  18.             //2. 获取授权方的公众号帐号基本信息  
  19.             $url2 = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token={$caccessToken}";  
  20.             $post = array();  
  21.             $post['component_appid'] = $wxData['appId'];  
  22.             $post['authorizer_appid'] = $authid;  
  23.             $return2 = $HT->curlPost($url2, $post);  
  24.             if (isset($return2['authorizer_info'])) {  
  25.                 $wxinfo = $return2['authorizer_info'];  
  26.                 $fcinfo = $return2['authorization_info'];  
  27.                 $Wxuser = M("Wxuser");  
  28.   
  29.                 //是否已经存在  
  30.                 $extFilter = array();  
  31.                 $wxuser['uid'] = $uid;  
  32.                 $extFilter['auth_appid'] = $fcinfo['authorizer_appid'];  
  33.                 $isExt = $Wxuser->where($extFilter)->find();  
  34.   
  35.                 $wxuser = array();  
  36.                 $wxuser['uid'] = $uid;  
  37.                 $wxuser['token'] = $this->getToken();  
  38.                 $wxuser['wxid'] = $wxinfo['user_name'];     //原始ID  
  39.                 $wxuser['wxname'] = $wxinfo['nick_name'];   //昵称  
  40.                 $wxuser['weixin_type'] = $wxinfo['service_type_info']['id'];  //微信类型 授权方公众号类型,0代表订阅号,1代表由历史老帐号升级后的订阅号,2代表服务号  
  41.                 $wxuser['weixin'] = $wxinfo['alias'];       //微信号  
  42.                 $wxuser['headerpic'] = $wxinfo['head_img']; //头像  
  43.                 $wxuser['bind_type'] = 1;  
  44.                 $wxuser['auth_appid'] = $fcinfo['authorizer_appid'];  
  45.                 $wxuser['auth_access_token'] = $accessToken;  
  46.                 $wxuser['auth_refresh_token'] = $refreshToken;  
  47.                 $wxuser['auth_functions'] = json_encode($fcinfo['func_info']);  
  48.                 $wxuser['auth_business_info'] = json_encode($wxinfo['business_info']);  
  49.                 $wxuser['create_time'] = time();  
  50.                 if ($isExt) {  
  51.                     $sign = $Wxuser->where($extFilter)->save($wxuser);  
  52.                 } else {  
  53.                     $sign = $Wxuser->add($wxuser);  
  54.                     if ($sign) {  
  55.                         //添加功能模块  
  56.                         $this->addfc($wxuser['token']);     
  57.                         //记录公众号数量  
  58.                         M('Users')->where(array('id' => $uid))->setInc('wechat_card_num');  
  59.                     }  
  60.                 }  
  61.                 if ($sign) {  
  62.                     redirect(C("site_url") . U('User/Index/index'));  
  63.                 }  
  64.             }  
  65.         }  
  66.         $this->error("亲,获取授权信息失败!", U('User/Index/index'));  

 

二. 全网发布

代码如下:

 

[php] view plain copy

 

  1. /** 
  2.      * 公众号消息与事件接收URL 
  3.      */  
  4.     public function index() {  
  5.         $timestamp = empty($_GET['timestamp']) ? '' : trim($_GET['timestamp']);  
  6.         $nonce = empty($_GET['nonce']) ? '' : trim($_GET ['nonce']);  
  7.         $msgSign = empty($_GET['msg_signature']) ? '' : trim($_GET['msg_signature']);  
  8.         $signature = empty($_GET['signature']) ? '' : trim($_GET['signature']);  
  9.         $encryptType = empty($_GET['encrypt_type']) ? '' : trim($_GET['encrypt_type']);  
  10.         $openid = trim($_GET['openid']);  
  11.           
  12.         import("@.ORG.ArrayUtil");  
  13.         import("@.ORG.Weixincrypt.WXBizMsgCrypt");  
  14.         $input = file_get_contents('php://input');  
  15.         $paramArr = ArrayUtil::xml2array($input);  
  16.         //$this->logPrint($paramArr);  
  17.         //$this->logPrint($_GET);  
  18.   
  19.         //解密  
  20.         $wxData = C("platform_setting");  
  21.         $encodingAesKey = $wxData['encodingAesKey'];  
  22.         $token = $wxData['token'];  
  23.         $appId = $wxData['appId'];  
  24.         $Wxcrypt = new WXBizMsgCrypt($token, $encodingAesKey, $appId);  
  25.         $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";  
  26.         $fromXml = sprintf($format, $paramArr['Encrypt']);  
  27.         $errCode = $Wxcrypt->decryptMsg($msgSign, $timestamp, $nonce, $fromXml, $toXml); // 解密  
  28.         $this->logPrint($toXml);  
  29.         if ($errCode == 0) {  
  30.             $param = ArrayUtil::xml2array($toXml);  
  31.             $keyword = isset($param['Content']) ? trim($param['Content']) : '';  
  32.             // 案例1 - 发送事件  
  33.             if (isset($param['Event']) && $paramArr['ToUserName'] == 'gh_3c884a361561') {  
  34.                 $contentStr = $param ['Event'] . 'from_callback';  
  35.             }  
  36.             // 案例2 - 返回普通文本  
  37.             elseif ($keyword == "TESTCOMPONENT_MSG_TYPE_TEXT") {  
  38.                 $contentStr = "TESTCOMPONENT_MSG_TYPE_TEXT_callback";  
  39.             }  
  40.             // 案例3 - 返回Api文本信息  
  41.             elseif (strpos($keyword, "QUERY_AUTH_CODE:") !== false) {  
  42.                 import("@.ORG.HttpTool");  
  43.                 $authcode = str_replace("QUERY_AUTH_CODE:", "", $keyword);  
  44.                 $contentStr = $authcode . "_from_api";  
  45.                 $HT = new HttpTool();  
  46.                 $authDetail = $HT->getAccessTokenByAuthCode($authcode);  
  47.                 $accessToken = $authDetail['authorizer_access_token'];  
  48.                 $HT->sendFansText($accessToken, $param['FromUserName'], $contentStr);  
  49.                 //$tokenInfo = WechatOpenApiLogic::getAuthorizerAccessTokenByAuthCode($ticket);  
  50.                 //$param ['authorizerAccessToken'] = $tokenInfo ['authorization_info'] ['authorizer_access_token'];  
  51.                 //self::sendServiceMsg($param['FromUserName'], $param['ToUserName'], 1, $contentStr); // 客服消息接口  
  52.                 return 1;  
  53.             }  
  54.   
  55.             $result = '';  
  56.             if (!empty($contentStr)) {  
  57.                 $xmlTpl = "<xml>  
  58.             <ToUserName><![CDATA[%s]]></ToUserName>  
  59.             <FromUserName><![CDATA[%s]]></FromUserName>  
  60.             <CreateTime>%s</CreateTime>  
  61.             <MsgType><![CDATA[text]]></MsgType>  
  62.             <Content><![CDATA[%s]]></Content>  
  63.             </xml>";  
  64.                 $result = sprintf($xmlTpl, $param['FromUserName'], $param['ToUserName'], time(), $contentStr);  
  65.                 if (isset($_GET['encrypt_type']) && $_GET['encrypt_type'] == 'aes') { // 密文传输  
  66.                     $wxData = C("platform_setting");  
  67.                     $msgCryptObj = new WXBizMsgCrypt($wxData['token'], $wxData['encodingAesKey'], $wxData['appId']);  
  68.                     $encryptMsg = '';  
  69.                     $msgCryptObj->encryptMsg($result, $_GET['timestamp'], $_GET['nonce'], $encryptMsg);  
  70.                     $result = $encryptMsg;  
  71.                 }  
  72.             }  
  73.             echo $result;  
  74.         }  
  75.     }  

转载于:https://my.oschina.net/u/3391479/blog/1580205

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值