| 參數 | 是否必須 | 說明 | |
|---|---|---|---|
| appid | 是 | 應用唯一標識,在微信開放平臺提交應用審核通過后獲得 | |
| secret | 是 | 應用密鑰 AppSecret,在微信開放平臺提交應用審核通過后獲得 | |
| code | 是 | 填寫第一步獲取的 code 參數 | |
| grant_type | 是 | 填 authorization_code |
下面通過我們的PHP代碼實現:
?php
namespace App\Helpers;
use GuzzleHttp\Client;
use Illuminate\Support\Arr;
class WechatAppUtils
{
protected $client = null;
protected $config = [];
public function __construct()
{
$this->config = [
'wechat_app' => [
'appid' => env('WECHAT_APPID'), //審核通過的APPID
'secret' => env('WECHAT_SECRET'), //應用APP SECRET 詳情見上圖
],
'time_out' => 5,
];
$this->client = new Client([
'time_out' => $this->config['time_out'],
]);
}
/**
* 獲取微信用戶access_token
*
* @param [String] $code
* @return Array
*/
public function accessToken($code)
{
$accessTokenUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token';
$response = $this->client->request('GET', $accessTokenUrl, [
'query' => [
'grant_type' => 'authorization_code',
'code' => $code,
'appid' => Arr::get($this->config, 'wechat_app.appid'),
'secret' => Arr::get($this->config, 'wechat_app.secret'),
],
]);
$result = $response->getbody()->getContents();
return empty($result) ? null : json_decode($result, true);
}
/**
* 微信用戶信息
*
* @param [String] $accessToken
* @param [String] $openId
* @return Array
*/
public function userInfo($accessToken, $openId)
{
$userInfoUrl = 'https://api.weixin.qq.com/sns/userinfo';
$response = $this->client->request('GET', $userInfoUrl, [
'query' => [
'access_token' => $accessToken,
'openid' => $openId,
'lang' => 'zh_CN',
],
]);
$result = $response->getbody()->getContents();
return empty($result) ? null : json_decode($result, true);
}
}
上面的accessToken方法主要是實現用戶授權,效驗的code參數是客戶端傳遞過來的,當成功獲取收錢用戶的授權信息后,可以根據用戶的OPENID來調用userInfo方法查詢相關用戶的信息,包含了用戶的昵稱、頭像、性別等等。
具體客戶端開發文檔可以參考這篇:https://developers.weixin.qq.com/doc/oplatform/Mobile_App/WeChat_Login/Development_Guide.html。
上面的用到的Http Client是一個第三方拓展包,叫做GuzzleHttp,是一個PHP HTTP客戶端,可以輕松發送HTTP請求,并且可以輕松集成Web服務。
我們可以通過composer一鍵安裝:
composer require guzzlehttp/guzzle
(三)、完善用戶微信授權登錄
完成上述的封裝操作后,我們便開始講微信接入到我們自己的系統中與用戶進行關聯起來,下面是微信接入的一張時序圖。

如果用戶想使用微信登錄,首先會通過客戶端喚起微信,請求登錄第三方應用,然后微信會詢問用戶是否成功授權給XX應用,授權成功后,客戶端會得到一個授權碼:code,然后客戶端攜帶code請求我們的客戶端API,進行授權綁定,授權成功后,會得到授權用戶OPENID(應用下的唯一標識),反之拋出異常信息提示用戶。
建立OAuth表,用于儲存用戶的授權信息。
建立一張o_auths table 儲存用戶的授權信息,設計oauth_type字段使其成為一個多態模型,方便接入以后的微博、支付寶、QQ接入等等。
Schema::create('o_auths', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id')->index()->comment('用戶ID');
$table->morphs('o_auth');
$table->json('data')->nullable()->comment('授權信息');
$table->timestamps();
});
完善用戶授權綁定
建立好o_auths table,下面開始完善用戶授權綁定的邏輯:
function wechat(User $user, $code)
{
$utils = new WechatAppUtils;
//獲取微信token
$accessTokens = $utils->accessToken($code);
throw_if(!Arr::has($accessTokens, ['unionid', 'openid']), Exception::class, '授權失敗,請稍后再試!');
//建立oauth關聯
$oAuth = OAuth::firstOrNew(['oauth_type' => 'wechat', 'oauth_id' => $accessTokens['openid']]);
throw_if(isset($oAuth->id),Exception::class,'該微信已綁定,請直接登錄!');
$oAuth->user_id = $user->id;
$oAuth->data = Arr::only($accessTokens, ['openid', 'refresh_token']);
$oAuth->save();
return $oAuth;
}
首先會通過客戶端傳遞過來的Code獲取當前用戶授權,然后查詢該用戶是否已授權過,已授權過就提醒用戶直接去登錄,否則綁定授權信息,返回給客戶端。
完善微信登錄
完善好用戶授權后,登錄就顯得非常容易了,只需要簡單查詢授權記錄,存在則返回對應綁定的用戶,否則拋出異常信息提示用戶。
public function signIn($user, $code)
{
$utils = new WechatAppUtils;
//獲取微信token
$accessTokens = $utils->accessToken($code);
throw_if(!Arr::has($accessTokens, ['unionid', 'openid']), Exception::class, '授權失敗,請稍后再試!');
$oauth = $this->getUserOauth($user, 'wechat');
throw_if(is_null($oauth), UserException::class, '授權失敗,該賬戶未綁定!');
return $oauth;
}
public function getUserOauth(User $user, $oAuthType)
{
return OAuth::where(['oauth_type' => $oAuthType, 'user_id' => $user->id])->first();
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。