uniapp實現公眾號H5、小程序和App微信授權登錄功能

本文介紹在使用uniapp開發的H5、小程序和App中使用微信授權登錄的方法。
由于微信的公眾號、小程序和App是相對獨立的體系,同一個用戶在這些不同的端中授權所返回的openid是不一樣的,這個時候就必須在微信開放平臺注冊賬號,并把對應的公眾號、小程序和移動應用綁定上去,在授權的時候就能返回一個unionid了,這樣就可以在后臺識別到是同一個用戶了。
前期要準備的工作:
1、申請公眾號、小程序和微信開放平臺,并拿到對應平臺的appid和secret;
2、H5網頁授權還要在公眾號后臺設置網頁授權域名;
3、小程序的接口域名必須啟用https,且要設置request、download合法域名等;
4、App必須在微信開放平臺申請應用并綁定。
上述工作準備好后,就可以開干了!
一、H5網頁授權
1、授權按鈕

// official.vue
<u-button class="button" type="success" @click="getWeChatCode">立即授權</u-button>

2、js代碼

// official.vue
onLoad(options) {
    if (options.scope) {
        this.scope = options.scope
    }
    if (this.$wechat && this.$wechat.isWechat()) {
        uni.setStorageSync('scope', this.scope)
    let code = this.getUrlCode('code')
        if (code) {
        this.checkWeChatCode(code)
    } else {
        if (this.scope == 'snsapi_base') {
        this.getWeChatCode()
        }
        }
    }
},
methods: {
    getUrlCode(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')) || null
    },
    getWeChatCode() {
    if (this.$wechat && this.$wechat.isWechat()) {
        let appid = '公眾號appid'
        let local = encodeURIComponent(window.location.href)
        let scope = uni.getStorageSync('scope')
        window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${local}&response_type=code&scope=${scope}&state=1#wechat_redirect`
    } else {
        uni.showModal({
        content: '請在微信中打開',
        showCancel: false
        })
    }
    },
    checkWeChatCode(code) {
    if (code) {
        let scope = uni.getStorageSync('scope')
        this.$http.post('/wechat/login', {
        code,
        scope,
        type: 1
    }).then(res => {
        if (res.code == 1) {
        if (scope == 'snsapi_userinfo') {
            this.login(res.data.userinfo)
            uni.navigateBack()
            }
        } else {
        uni.showModal({
            content: res.msg,
            showCancel: false
        })
        }
        }).catch(err => {
        uni.showModal({
        content: err.msg,
        showCancel: false
        })
        })
    }
}

注意,
1、公眾號授權scope有兩種方式:snsapi_base和snsapi_userinfo,前者靜默授權不會有授權彈窗,后者必須用戶點擊授權彈窗按鈕授權才行;
2、網頁授權是需要跳轉到微信服務器上,然后攜帶code再跳回來,所以在跳回來后還需要用到的變量比如scope必須用緩存保存起來,否則會讀取不到;
3、跳轉回來的頁面就是發起授權的頁面,所以在頁面的onload方法中要判斷url是否攜帶有code,避免重復跳轉授權的死循環(會提示code已被使用);
4、授權后拿code去后臺通過微信請求換取用戶信息。
二、小程序授權
1、授權按鈕,必須是button,且設置

// mp.vue
<u-button type="success" @click="getUserProfile()">微信授權登錄</u-button>

2、js代碼

getUserProfile() {
    uni.getUserProfile({
    desc: '使用微信登錄',
    lang: 'zh_CN',
    success: (a) => {
        uni.login({
        provider: 'weixin',
            success: (b) => {
            this.loading = true
            let userInfo = a.userInfo
            userInfo.code = b.code
            userInfo.type = 2
            this.$http.post('/wechat/login', userInfo).then(c => {
            this.loading = false
            this.login(c.data.userinfo)
            uni.navigateBack()
            }).catch(err => {
            this.loading = false
            uni.showModal({
                content: err.msg,
                showCancel: false
                })
            })
            },
            fail: (err) => {
            console.error(err)
            }
        })
        },
        fail: (err) => {
            console.error(err)
        }
    })
}

說明:
1、授權后會得到code和userInfo,里面有昵稱、頭像、性別、地域等字段,沒有openid;
2、把code和userInfo傳回后臺,再通過code換取用戶的openid和unionid。
三、App授權
1、授權按鈕

// app.vue
<u-button class="button" type="success" @click="onAppAuth">確定授權</u-button>

2、js代碼

// app.vue
onAppAuth() {
    uni.getProvider({
    service: 'oauth',
    success: (a) => {
        if (~a.provider.indexOf('weixin')) {
        uni.login({
            provider: 'weixin',
            onlyAuthorize: true,    // 注意此參數
            success: (b) => {
            if (b.code) {
                this.$http.post('/wechat/login', {
                code: b.code,
                type: 3
                }).then(c => {
                this.loading = false
                this.login(c.data.userinfo)
                uni.navigateBack()
                }).catch(err => {
                this.loading = false
                uni.showModal({
                    content: '授權登錄失敗',
                    showCancel: false
                })
                })
            } else {
                uni.getUserInfo({
                success: (c) => {
                    this.loading = true
                    let userInfo = c.userInfo
                    userInfo.type = 3
                    this.$http.post('/wechat/login', userInfo).then(d => {
                    this.loading = false
                    this.login(d.data.userinfo)
                    uni.navigateBack()
                    }).catch(err => {
                    this.loading = false
                    uni.showModal({
                        content: '授權登錄失敗',
                        showCancel: false
                    })
                    })
                },
                fail: (err) => {
                    console.error(err)
                }
                })
            }
            },
            fail: (err) => {
            console.error(err)
            }
        })
        }
    },
    fail: (err) => {
        console.error(err)
    }
    })
}

注意:微信在App中授權有兩種方式,
1、第一種是uni.login里面的onlyAuthorize為false,此時直接調用uni.getUserInfo方法即可直接在前端獲取到用戶信息。但此方式有個問題,即必須把App的secret配置在manifest.json文件當中,并且會被打包進apk/ipa中,存在泄漏的風險!所以不推薦此種方式;
2、第二種是onlyAuthorize設置為true,則uni.login只返回code,跟小程序一樣傳到后臺去換取用戶信息。

// 后臺代碼
public function login()
{
    $params = $this->request->param();
    switch ($params['type']) {
        case '1':   // 公眾號
            $wechat = Config::get('wechat.h5');
            $access_token = Http::sendRequest('https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$wechat['appid'].'&secret='.$secret['secret'].'&code='.$params['code'].'&grant_type=authorization_code');
            $msg = json_decode($access_token['msg'], true);
            if ($params['scope'] == 'snsapi_userinfo') {
                $userinfo = Http::sendRequest('https://api.weixin.qq.com/sns/userinfo?access_token='.$msg['access_token'].'&openid='.$msg['openid'].'&lang=zh_CN');
                $info = json_decode($userinfo['msg'], true);
                $wechat_member = $this->memberModel->field(['user_id','headimgurl'])->where(['openid'=>$info['openid']])->find();
                $member = [
                    'type'       => $params['type'],
                    'unionid'    => $info['unionid'],
                    'openid'     => $info['openid'],
                    'nickname'   => $info['nickname'],
                    'sex'        => $info['sex'],
                    'language'   => $info['language'],
                    'country'    => $info['country'],
                    'province'   => $info['province'],
                    'city'       => $info['city'],
                    'headimgurl' => $info['headimgurl']
                ];
                // 判斷是否需要注冊或更新數據
                if ($wechat_member) {
                    // 如果該用戶已經存在,則只更新數據
                } else {
                    // 否則的話先用unionid判斷有無其他微信記錄,再進行更新或注冊
                }
            } else {
                $data['openid'] = $info['openid'];
                $this->success('獲取成功',$data);
            }
            break;
        case '2':   // 小程序
            $app = Factory::miniProgram(Config::get('wechat.mini'));
            $info = $app->auth->session($params['code']);
            $wechat_member = $this->memberModel->field(['user_id','headimgurl'])->where(['openid'=>$info['openid']])->find();
            $member = [
                'type'       => $params['type'],
                'unionid'    => $info['unionid'],
                'openid'     => $info['openid'],
                'nickname'   => $params['nickName'],
                'sex'        => $params['gender'],
                'language'   => $params['language'],
                'country'    => $params['country'],
                'province'   => $params['province'],
                'city'       => $params['city'],
                'headimgurl' => $params['avatarUrl']
            ];
            // 判斷是否需要注冊或更新數據
            if ($wechat_member) {
                // 如果該用戶已經存在,則只更新數據
            } else {
                // 否則的話先用unionid判斷有無其他微信記錄,再進行更新或注冊
            }
            break;
        case '3':   // app
            if (isset($params['code'])) {
                $app = Config::get('wechat.app');
                $access_token = Http::sendRequest('https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$app['app_id'].'&secret='.$app['secret'].'&code='.$params['code'].'&grant_type=authorization_code');
                $msg = json_decode($access_token['msg'], true);
                $wechat_member = $this->memberModel->field(['user_id','headimgurl'])->where(['openid'=>$msg['openid']])->find();
                $member = [
                    'type'       => $params['type'],
                    'unionid'    => $msg['unionid'],
                    'openid'     => $msg['openid'],
                    'nickname'   => isset($msg['nickName']) ? $msg['nickName'] : '微信用戶',
                    'sex'        => isset($msg['gender']) ? $msg['gender'] : '0',
                    'language'   => isset($msg['language']) ? $msg['language'] : '',
                    'country'    => isset($msg['country']) ? $msg['country'] : '',
                    'province'   => isset($msg['province']) ? $msg['province'] : '',
                    'city'       => isset($msg['city']) ? $msg['city'] : '',
                    'headimgurl' => isset($msg['avatarUrl']) ? $msg['avatarUrl'] : ''
                ];
            } else {
                $wechat_member = $this->memberModel->field(['user_id','headimgurl'])->where(['openid'=>$params['openId']])->find();
                $member = [
                    'type'       => $params['type'],
                    'unionid'    => $params['unionId'],
                    'openid'     => $params['openId'],
                    'nickname'   => $params['nickName'],
                    'sex'        => $params['gender'],
                    'language'   => isset($params['language']) ? $params['language'] : '', // app微信wx.getUserInfo授權未返回此字段
                    'country'    => $params['country'],
                    'province'   => $params['province'],
                    'city'       => $params['city'],
                    'headimgurl' => $params['avatarUrl']
                ];
            }
            // 判斷是否需要注冊或更新數據
            if ($wechat_member) {
                // 如果該用戶已經存在,則只更新數據
            } else {
                // 否則的話先用unionid判斷有無其他微信記錄,再進行更新或注冊
            }
            break;
    }
}

至此,微信公眾號H5、小程序和App授權登錄全部流程結束。
轉載自王維的博客: https://asyou.github.io/content/43.html

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。