Laravel 集成微信用戶登陸&&綁定

最近主要在忙活微信與支付寶平臺的對接與開發,本篇就基於後端層面來說述一下微信的登陸與綁定實現。php

(1、)申請微信開放平臺

最首先的話就是須要去微信開發中心https://open.weixin.qq.com,建立一個帳號,而後建立本身的移動或網站應用。html

image

建立完成後,就會須要騰訊的審覈,整個過程在1-3天,基本上1天左右就能完成,審覈經過以下圖所示。json

image

(2、) 封裝微信相關接口

微信移動應用開發文檔:https://developers.weixin.qq....後端

審覈經過後,就須要來封裝微信受權、可信息獲取的接口。api

封裝微信受權 && 用戶信息獲取

微信受權接口:https://api.weixin.qq.com/sns...微信

須要填寫的參數以下:微信開發

參數 是否必須 說明
appid 應用惟一標識,在微信開放平臺提交應用審覈經過後得到
secret 應用密鑰 AppSecret,在微信開放平臺提交應用審覈經過後得到
code 填寫第一步獲取的 code 參數
grant_type 填 authorization_code

下面經過咱們的PHP代碼實現:app

<?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方法查詢相關用戶的信息,包含了用戶的暱稱、頭像、性別等等。composer

具體客戶端開發文檔能夠參考這篇:https://developers.weixin.qq....ide

上面的用到的Http Client是一個第三方拓展包,叫作GuzzleHttp,是一個PHP HTTP客戶端,能夠輕鬆發送HTTP請求,而且能夠輕鬆集成Web服務。

咱們能夠經過composer一鍵安裝:

composer require guzzlehttp/guzzle

(三)、完善用戶微信受權登陸

完成上述的封裝操做後,咱們便開始講微信接入到咱們本身的系統中與用戶進行關聯起來,下面是微信接入的一張時序圖。

image

若是用戶想使用微信登陸,首先會經過客戶端喚起微信,請求登陸第三方應用,而後微信會詢問用戶是否成功受權給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();
}
相關文章
相關標籤/搜索