微信开放平台的开发

来源:互联网转载 | 更新日期:2023-09-14 07:40:51

概念

微信公众平台-第三方平台(简称第三方平台)开放给所有通过开发者资质认证后的开发者使用。在得到公众号或小程序运营者(简称运营者)授权后,第三方平台开发者可以通过调用微信开放平台的接口能力,为公众号或小程序的运营者提供账号申请、小程序创建、技术开发、行业方案、活动营销、插件能力等全方位服务。同一个账号的运营者可以选择多家适合自己的第三方为其提供产品能力或委托运营。

写此篇博客的缘由

由于腾讯文档的极其简陋,导致很多开发者(我)多走了许多弯路。所以我立下誓言如果我这边开发完成,我一定搞篇博客,给后来者指条路,因为腾讯实在太坑了,废话就不啰嗦了,直接开讲。

第一步:创建第三方平台

1).在微信开放平台-管理中心-第三方平台中创建第三方平台账号。创建第三方平台

2).选择“平台型服务商类型”创建第三方平台。填写第三方平台的基本信息. 填写基本信息

3).设置相关权限信息,具体权限集信息可参考:第三方平台权限说明
4).填写开发资料的信息说明, 可参考:第三方平台申请资料说明

第二步:调试开发

      接收第三方验证票据(component_verity_ticket

在第三方平台创建审核通过后,微信服务器会向其“授权事件接收URL”每隔10分钟定时推送component_verify_ticket。第三方平台方在收到ticket推送后也需进行解密,接收到后必须直接返回字符串success。

/*** 用于接受微信传来的ticket** @return string*/public function authCallback(){$xml_msg=file_get_contents('php://input');$msg=array("timeStamp" => empty($_GET['timestamp']) ? "" : trim($_GET['timestamp']) ,"nonce" => empty($_GET['nonce']) ? "" : trim($_GET['nonce']) ,"msg_sign" => empty($_GET['msg_signature']) ? "" : trim($_GET['msg_signature']));//第三方平台的配置信息$wx_settins=['app_id' => env('WECHAT_OPEN_PLATFORM_APPID', ''),'secret' => env('WECHAT_OPEN_PLATFORM_SECRET', ''),'token' => env('WECHAT_OPEN_PLATFORM_TOKEN', ''),'aes_key' => env('WECHAT_OPEN_PLATFORM_AES_KEY', ''),];$result = $this->component_decode($xml_msg,$msg,$wx_settins);$ticket = WechatTicket::where('ticket', $result)->get();if(!count($ticket)){$Data=['appid'=>open_platform_app_id,'ticket'=>$result,'created_at'=>date('Y-m-d H:i:s')];WechatTicket::insert($Data);}return 'success';}

注意1:component_verity_ticket建议每次接受都进行写入缓存/数据库/文件

注意2:微信发送的请求中总共有5个参数,具体如下:

时间戳 timestamp,随机数nonce , encrypt_type(加密类型,为aes)和msg_signature(消息体签名,用于验证消息体的正确性)以及xml内容 

XML内容

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

注意3:对上述XML内容解密

解密/加密方式都是aes,

需要在创建第三方平台时填写开发资料时填写的:消息验证token,消息加解密key,appid

和微信请求来的参数:msg_signature(签名),timestamp(时间戳),nonce(随机数),postDataStr(post来的数据字符串),进行校验和解密成明文内容。然后提取出ComponentVerifyTicket进行写入缓存/数据库/文件(后续所有的操作都需要用到)

       获取令牌(component_access_token

第三方平台component_access_token是第三方平台的下文中接口的调用凭据,也叫做令牌(component_access_token)。每个令牌是存在有效期(2小时)的,且令牌的调用不是无限制的,请第三方平台做好令牌的管理,在令牌快过期时(比如1小时30分)再进行刷新.

/*** 获取component_access_token** @return bool|string*/public function getComponentAccessToken(){$componentAccessToken=Redis::get('component_access_token');if(!$componentAccessToken){// 获取最新的ticket$ticket = WechatTicket::where('appid', $this->open_platform['open_platform']['app_id'])->orderBy('created_at', 'DESC')->limit(1)->select(['ticket'])->first();$this->componentVerifyTicket = $ticket->ticket;$url = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";$postData = array("component_appid" =>open_platform_app_id,"component_appsecret" => open_platform_secret,"component_verify_ticket" => $this->componentVerifyTicket);$componentAccessTokenReq = $this->http($url, $postData, 'POST');$componentAccessTokenArr = json_decode($componentAccessTokenReq, true);$componentAccessToken = $componentAccessTokenArr['component_access_token'];Redis::setex('component_access_token', 5400, $componentAccessToken); //有效时间2个小时,缓存一定要小于两个小时}return $componentAccessToken;}
  • 判断token未过期直接返回(不要频繁的请求token,微信有请求次数限制)
  • 用最新的ticket
  • 拼装请求数据
  • 发送Https请求并获取结果
  • 解析结果并缓存token
  •        获取预授权码(pre_auth_code

    该API用于获取预授权码。预授权码用于公众号或小程序授权时的第三方平台方安全验证

    /*** 获取预授权码** @param string $componentAccessToken* @return bool|string*/public function getPreAuthCode(string $componentAccessToken){$url = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=" . $componentAccessToken;$postData = array("component_appid" => $open_platform_app_id, //第三方平台的APPID);return OpenWechat::newInstance()->http($url, $postData, 'POST');//发送post请求}

    重定向到授权页,引入用户进入授权页

    第三方平台方可以在自己的网站:中放置“微信公众号授权”的入口,引导公众号进入授权页。授权页网址为

    https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=xxxx&pre_auth_code=xxxxx&redirect_uri=xxxx

    该网址中第三方平台方需要提供第三方平台方appid、预授权码和回调URI(授权成功后直接跳转的页面),

    步骤:

    • 在第三方平台指定的域名下做一个简单的页面作为授权页的入口
    • 获取pre_auth_code
    • 替换重定向的url的参数

       

    /*** 公众号授权** @param Request $request* @return string*/public function openOauth(Request $request){// 1、获取component_access_token$componentAccessToken= OpenWechat::getComponentAccessToken();if($request->has('auth_code')){// 存在auth_code 说明前两个接口已请求过// 4、使用授权码换取公众号或小程序的接口调用凭据和授权信息$authorization = $this->getAuthToken($componentAccessToken,$request->input('auth_code'));$authorization_info = json_decode($authorization,true);$whereData=['authorizer_appid'=>$authorization_info['authorization_info']['authorizer_appid']];$updataData=['authorizer_access_token'=>$authorization_info['authorization_info']['authorizer_access_token'],'authorizer_refresh_token'=>$authorization_info['authorization_info']['authorizer_refresh_token']];WechatAccount::updateOrCreate($whereData,$updataData);}else{// 2、获取预授权码$preAuthCodeReq = $this->getPreAuthCode($componentAccessToken);$preAuthCodeArr = json_decode($preAuthCodeReq,true);$preAuthCode = $preAuthCodeArr['pre_auth_code'];// 3、引导进入授权页面$url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=". $this->open_platform['open_platform']['app_id'] ."&pre_auth_code=". $preAuthCode ."&redirect_uri=".$request->fullUrl();return view('wechat.auth', ['url' => $url,]);}return 'success';}

    注意:接收授权方授权请求并一定要保存授权方信息

    在第四步后重定向到授权页后,在授权页上会有一个二维码,微信公众号管理员(开发者的权限不行)通过的使用本人微信扫描二维码对第三方平台进行授权,在公众号管理员扫描二维码后,第三方平台后台给定的回调地址(redirect_uri),将会收到一条请求,请求中包含了授权方的authorization_code和authorization_code的有效期 ;

  • 使用authorization_code换取授权方的authorizer_access_token和authorizer_refresh_token。
  • ​ /*** 获取公众号信息包括token refresh_token** @param string $componentAccessToken* @param string $authCode* @return bool|string*/private function getAuthToken(string $componentAccessToken, string $authCode){$url = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=" . $componentAccessToken;$postData = array('component_appid' => , //第三方app_id"authorization_code" => $authCode); // return $this->http($url, $postData, 'POST');return OpenWechat::newInstance()->http($url, $postData, 'POST');}​

    步骤:

    • 获取第三方平台的token
    • 获取授权方授权信息
    • 获取授权方账号信息进行保存

    获取/刷新接口调用令牌

    在公众号/小程序接口调用令牌(authorizer_access_token)失效时,可以使用刷新令牌(authorizer_refresh_token)获取新的接口调用令牌。

    注意: authorizer_access_token 有效期为 2 小时,开发者需要缓存 authorizer_access_token,避免获取/刷新接口调用令牌的 API 调用触发每日限额

    /*** 更新authorizer_access_token** @return bool|string*/public function UpdateAuthorizerAccessToken($authorizer_appid){$component_access_token=$this->getComponentAccessToken();$old_authorizer_refresh_token= WechatAccount::where("authorizer_appid",$authorizer_appid)->first(['authorizer_refresh_token']);$url="https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=$component_access_token";$postData = array("component_appid" => $this->open_platform['open_platform']['app_id'],"authorizer_appid" => $authorizer_appid,"authorizer_refresh_token" => $old_authorizer_refresh_token->authorizer_refresh_token);$authorizer_refresh_token=$this->http($url, $postData, 'POST');$new_authorizer_refresh_token=json_decode($authorizer_refresh_token, true);$whereData=['authorizer_appid'=>$authorizer_appid];$updataData=['authorizer_access_token'=>$new_authorizer_refresh_token['authorizer_access_token'],'authorizer_refresh_token'=>$new_authorizer_refresh_token['authorizer_refresh_token']];WechatAccount::updateOrCreate($whereData,$updataData);}

    公用的http请求方法

    /*** post 请求** @param string $url* @param array $data* @param string $method* @return bool|string*/public function http(string $url, array $data, string $method){$data = json_encode($data);$curl = curl_init(); // 启动一个CURL会话curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Refererif ($method == 'POST') {curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求if ($data != '') {curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包}}curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回$tmpInfo = curl_exec($curl); // 执行操作curl_close($curl); // 关闭CURL会话return $tmpInfo; // 返回数据}

    第三步:代公众号调用接口

     当微信公众号授权给第三方开发平台后,第三方开发平台执行某些操作时,如查询用户信息、发送模板消息等等,这就需要使用authorizer_access_token。这个token从获得开始,2小时内有效,如果需要继续使用授权,就需要在有效期内主动刷新token。但是当某些原因导致刷新token失败时,仍然可以使用authorizer_refresh_token(自获得起30天内有效)重新获得authorizer_access_token。这里的authorizer_access_token就可以代替普通的access_token去调你授权的接口了。

     

    上一篇:这21个自动化部署工具,你都知道吗?

    下一篇:数据库试题及答案 两套

    相关文章

    Copyright © 网站出售-网站交易平台 版权信息

    网站备案号:黔ICP备2023004141号