最近主要在忙活微信与支付宝平台的对接与开发,本篇就基于后端层面来说述一下微信的登陆与绑定实现。php
最首先的话就是须要去微信开发中心https://open.weixin.qq.com,建立一个帐号,而后建立本身的移动或网站应用。html
建立完成后,就会须要腾讯的审核,整个过程在1-3天,基本上1天左右就能完成,审核经过以下图所示。json
微信移动应用开发文档: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
完成上述的封装操做后,咱们便开始讲微信接入到咱们本身的系统中与用户进行关联起来,下面是微信接入的一张时序图。
若是用户想使用微信登陆,首先会经过客户端唤起微信,请求登陆第三方应用,而后微信会询问用户是否成功受权给XX应用,受权成功后,客户端会获得一个受权码:code,而后客户端携带code请求咱们的客户端API,进行受权绑定,受权成功后,会获得受权用户OPENID(应用下的惟一标识),反之抛出异常信息提示用户。
创建一张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(); }