最近主要在忙活微信与支付宝平台的对接与开发,本篇就基于后端层面来讲述一下微信的登录与绑定实现。
(一)、申请微信开放平台
最首先的话就是需要去微信开发中心https://open.weixin.qq.com,创建一个账号,然后创建自己的移动或网站应用。

创建完成后,就会需要腾讯的审核,整个过程在1-3天,基本上1天左右就能完成,审核通过如下图所示。

(二) 、封装微信相关接口
微信移动应用开发文档:https://developers.weixin.qq.com/doc/oplatform/Mobile_App/WeChat_Login/Authorized_API_call_UnionID.html
审核通过后,就需要来封装微信授权、可信息获取的接口。
封装微信授权 && 用户信息获取
微信授权接口:https://api.weixin.qq.com/sns/oauth2
需要填写的参数如下:
| 参数 | 是否必须 | 说明 | |
|---|---|---|---|
| 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);
}
}
内容版权声明:除非注明,否则皆为本站原创文章。
