微信第三方平台开发小程序发起授权,PHP微信第三方平台授权案例laravel
一、地址:
Route::get('wx/authorize', 'WxAuthorizeController@WxAuthorize')->name('wx-authorize');//发起授权
二、方法
/** * @return \Illuminate\Auth\Access\Response|void * 授权跳转地址到二维码 */ public function WxAuthorize() { $code = $this->wx->preAuthCode(); if( $code ) { $url = $this->wx->QRCodeUrl( $code ); return redirect($url); }else { return redirect()->back()->with('msg','调取微信平台失败'); } } /** * @param $code * @return string * 生成二微码 */ public function QRCodeUrl( $code ) { return 'https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid='.第三方appid.'&pre_auth_code='.$code.'&redirect_uri='.返回地址; } /** * @return string * 预授权code * $ID 用户id */ public function preAuthCode() { $url = 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token='.$this->component_access_token; $post['component_appid'] = $this->appid; $data = wxPostCurl( $url, $post ); if( $data ) { $data = json_decode($data,true); if( array_has( $data,'pre_auth_code') ) { //你可以写在缓存 $pre_auth_code = $data['pre_auth_code']; }else { $pre_auth_code = ''; } }else { $pre_auth_code = ''; } return $pre_auth_code; } //component_access_token请求方法 /** * @return string * 获取全局token */ public function getAccesstoken() { if( Cache::has('component_access_token') ) { $access_token = Cache::get('component_access_token'); }else { $url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token'; $post['component_appid'] = '';//appid $post['component_appsecret'] = '';//secret; $post['component_verify_ticket'] = '';//Cache::get('ticket'); //ticket是微信发送给你的参考http://www.xiaoshu168.com/PHP/247.html $data = wxPostCurl( $url,'component_access_token') ) { Cache::put('component_access_token',$data['component_access_token'],$data['expires_in']/60); $access_token = $data['component_access_token']; }else { $access_token = ''; } }else { $access_token = ''; } } return $access_token; }
三、请求方法
/*** * @param $url * @param $dataObj * @return mixed * 微信接口 curl post请求 */ function wxPostCurl( $url , $dataObj ) { //初使化init方法 $ch = curl_init(); //指定URL curl_setopt($ch, CURLOPT_URL, $url); //设定请求后返回结果 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //声明使用POST方式来进行发送 curl_setopt($ch, CURLOPT_POST, 1); //发送什么数据呢 curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($dataObj,JSON_UnesCAPED_UNICODE)); //忽略证书 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //忽略header头信息 curl_setopt($ch, CURLOPT_HEADER, 0); //设置超时时间 curl_setopt($ch, CURLOPT_TIMEOUT, 10); //发送请求 $output = curl_exec($ch); //关闭curl curl_close($ch); //返回数据 return $output; }
四、授权回调
Route::any('wx/authorize/back', 'WxAuthorizeController@WxAuthorizeBack');//授权回调
/** * @param Request $request * 授权回调 */ public function WxAuthorizeBack( Request $request ) { $code = $request->input('auth_code'); //这就是你要处理的业务了 }