#  Fastadmin微信小程序授权登录插件+手机号码获取

## 2021.06.23更新（此更新明文传输数据时候对头像昵称的限制去掉了，因为部分用户存在头像昵称异常的情况导致不能使用小程序，）：
## 2021.06.15更新（此更新仅在markdown补充，不改动插件代码，自行复制下面代码添加即可 ）-由于授权登录可能存在解密失败的情况，特新加明文传输API，接口代码如下：


```
protected $noNeedLogin = ['code', 'login', 'codev2', 'loginv2'];

   /**
     * 登录第一步，获取openid 跟 session_key
     */
    public function codev2()
    {
        $code = $this->request->param('code');
        if (!$code) {
            $this->error('code不能为空');
        }
        self::getOpenidv2($code);
    }


    /**
     * @param $code 用来交换获取openid 跟 session_key
     */
    public function getOpenidv2($code)
    {
        $url = sprintf($this->loginUrl, $this->appid, $this->secret, $code);
        $result = Http::get($url);
        $wxResult = json_decode($result, true);
        if (empty($wxResult)) {
            $this->error('获取sessin_key及openID时异常');
        }
        if (isset($wxResult['errcode']) && $wxResult['errcode'] != 0) {
            $this->error($wxResult['errmsg']);
        }
        $item = [
            'openid' => $wxResult['openid'],
            'session_key' => $wxResult['session_key']
        ];
        $ck = \app\admin\model\User::where(['openid' => $wxResult['openid']])->find();
        if (!$ck) {
            $user = new \app\admin\model\User;
            $user->openid = $wxResult['openid'];
            $user->status = 'normal';
            $user->save();
            $this->auth->direct($user->id);
            $this->success('登录成功', $this->auth->getUserinfo());
        } else {
            $this->auth->direct($ck['id']);
            $this->success('登录成功', $this->auth->getUserinfo());
        }
    }


    /**
     * 用户登录
     */
    public function loginv2()
    {
        $nickName = $this->request->post('nickName');
        $avatarUrl = $this->request->post('avatarUrl');
        $gender = $this->request->post('gender');
        $openid = $this->request->post('openid');
        /**TODO 这个限制不能再用了    if (empty($nickName) || empty($avatarUrl) || empty($gender) || empty($openid)) {
            $this->error('缺少参数');
        }*/
        $userinfo = \app\admin\model\User::where(['openid' => $openid])->find();
        if ($userinfo) {
            $userinfo->nickname = $nickName;
            $userinfo->avatar = $avatarUrl;
            $userinfo->gender = $gender;
            $userinfo->save();
            $this->auth->direct($userinfo['id']);
        } else {
            $user = new \app\admin\model\User();
            $user->data([
                'nickname' => $nickName,
                'avatar' => $avatarUrl,
                'gender' => $gender,
                'status' => 'normal',
                'openid' => $openid
            ]);
            $user->save();
            $this->auth->direct($user->id);
        }
        $this->success('登录成功', $this->auth->getUserinfo());
    }

```




#### 介绍
> 旨在方便自己日后做这方面的开发，直接安装就好，省事.本项目是基于2021年4月13日微信小程序授权登录做的整改进行开发的插件

#### 软件架构

> 毫无架构可言


#### 使用说明

1.  Install_Package目录 是打包过的插件安装包，可以直接用于安装
2.  接口文档在下方已经贴出
3.  前端测试demo:在application/api/minapp_v2 里面，使用时只需要修改minapp_v2/utils/api.js 里面的 http地址即可
4.  使用前还记得要把插件管理里面的配置项的小程appid跟密钥配置好

![输入图片说明](https://images.gitee.com/uploads/images/2021/0416/112431_447b3d59_968332.png "屏幕截图.png")
#### 参与贡献

1.  Fork 本仓库
2.  新建 Feat_xxx 分支
3.  提交代码
4.  新建 Pull Request


![输入图片说明](https://images.gitee.com/uploads/images/2021/0416/191030_13c98f4a_968332.png "屏幕截图.png")
![输入图片说明](https://images.gitee.com/uploads/images/2021/0416/191428_64408157_968332.png "屏幕截图.png")



## 下面是API文档

##### API一简要描述

- code换取openid接口

##### 请求URL
- `/api/Auth_login_with_wechat/code`

##### 请求方式
- GET/POST

##### 参数

|参数名|必选|类型|说明|
|:----    |:---|:----- |-----   |
|code |是  |int |wx.login 获取的code   |

##### 返回示例

``` 
{
    "code": 1,
    "msg": "成功",
    "time": "1618534098",
    "data": {
        "openid": "o5rIS5MzaMjZBz3DMzUtsosMZApU",
        "session_key": "z5kYsGmcb7MaRcS0a1AGPQ=="
    }
}

{
    "code": 0,
    "msg": "code been used, hints: [ req_id: YDHBA5yFe-i1q0RA ]",
    "time": "1618534253",
    "data": null
}
```

##### 返回参数说明

|参数名|类型|说明|
|:-----  |:-----|-----                           |
|code |int   |状态码，1：成功；0：失败  |
|msg |string   |提示语  |
|openid |string   |openid  用于后面的登录传值 |
|session_key |string   |session_key 用于后面的登录传值 |






##### API二简要描述

- 登录接口

##### 请求URL
- `/api/Auth_login_with_wechat/login`

##### 请求方式
- POST

##### 参数

|参数名|必选|类型|说明|
|:----    |:---|:----- |-----   |
|encryptedData |是  |string |加密串   |
|iv |是  |string |偏移量   |
|sessionKey |是  |string |sessionKey   |
|openid |是  |string |openid   |

##### 返回示例

``` 
{
    "code": 1,
    "msg": "登录成功",
    "time": "1618535634",
    "data": {
        "id": 2,
        "username": "",
        "nickname": "Blustant'C 吴伟祥 可乐爸爸",
        "mobile": "",
        "avatar": "https://thirdwx.qlogo.cn/mmopen/vi_32/Hlq7zKcsbIXveqiaEuRI6SHbk1zSBADsf6SVMWI9VxRxmpz4R917QHfcFTlsLFC8IVhZ418LVlv3DX4VjzyKibZg/132",
        "score": 0,
        "token": "47b64df8-d5ee-43e7-9168-889ea48c11fb",
        "user_id": 2,
        "createtime": 1618535634,
        "expiretime": 1621127634,
        "expires_in": 2592000
    }
}
```

##### 返回参数说明

|参数名|类型|说明|
|:-----  |:-----|-----                           |
|code |int   |状态码，1：成功；0：失败  |
|msg |string   |提示语  |
|token |string   |用于接口请求使用  |





##### API三简要描述

- 获取手机号接口

##### 前端示例代码
```html
<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">获取手机号</button>


getPhoneNumber:function(e){
    console.log(e.detail.errMsg)
    console.log(e.detail.iv)
    console.log(e.detail.encryptedData)
},
```



##### 请求URL
- ` /api/Auth_login_with_wechat/getPhone`

##### 请求方式
- POST

##### 参数

|参数名|必选|类型|说明|
|:----    |:---|:----- |-----   |
|iv |是  |string |偏移量   |
|encryptedData |是  |string | 加密串    |
|sessionKey |是  |string | sessionKey    |

##### 返回示例

``` 
{
    "code": 1,
    "msg": "获取成功",
    "time": "1613125219",
    "data": {
        "phoneNumber": "18712377078",
        "purePhoneNumber": "18712377078",
        "countryCode": "86",
        "watermark": {
            "timestamp": 1613124456,
            "appid": "wxc17d20f5b4595397"
        }
    }
}
```

##### 返回参数说明

|参数名|类型|说明|
|:-----  |:-----|-----                           |
|code |int   |1  成功  0 失败 -获取手机号失败就只能手动填写手机号 |
|data-phoneNumber |string   |手机号  |






> 解密后的数据格式，并没有openid跟unionID

```angular2html
{
    "nickName":"Blustant'C 吴伟祥 可乐爸爸",
    "gender":1,
    "language":"zh_CN",
    "city":"Hefei",
    "province":"Anhui",
    "country":"China",
    "avatarUrl":"https://thirdwx.qlogo.cn/mmopen/vi_32/Hlq7zKcsbIXveqiaEuRI6SHbk1zSBADsf6SVMWI9VxRxmpz4R917QHfcFTlsLFC8IVhZ418LVlv3DX4VjzyKibZg/132",
    "watermark":{
        "timestamp":1618498216,
        "appid":"wx9d9766d500e04dcd"
    }
}
```


## 获取手机号遇到报错appid没有权限：

![输入图片说明](https://images.gitee.com/uploads/images/2021/0421/164220_ea476bdc_968332.png "屏幕截图.png")

- 解决方案：微信小程序后台首页的微信认证通过了就有权限了 
![输入图片说明](https://images.gitee.com/uploads/images/2021/0421/164320_52f3b8e1_968332.png "屏幕截图.png")

