uni-app 微信小程序授權登錄


1.appID配置

在manifest.json中輸入申請的微信小程序id

 

 

 2.獲取用戶信息

可以使用uni.getUserProfile請求用戶授權獲取用戶信息, 也可以使用uni.getUserInfo獲取

 

 

 授權成功后獲取到的用戶信息在userInfo中:

 

 

 

uni.getUserProfile({
                    desc: '123',
                    lang: 'zh_CN',
                    success: res => {    
                                   console.log(res)
                                }
                            })        

3.調用登錄api

使用uni.login方法,provider參數輸入'weixin',成功的返回值中如果errMsg="login:ok" 代表成功,

微信小程序端會返回一個code字符串

 

 

 4.使用獲取到的code請求微信登錄接口,獲取 openid 和 session_key

 

 

 

請求微信官方文檔中的jscode2Session接口:

GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

替換為自己的參數,appId和Secret為申請微信小程序時獲取的AppID和appSecret,js_code為剛才uni.login獲取到的code,最后一個參數為固定值‘authorization_code’

調用成功后,會獲取到該用戶的openId,唯一標識微信用戶

 

 

 

5.綁定用戶 實現登錄

獲取到微信用戶的唯一id后,就可以綁定至自己系統中的用戶,我的做法是在用戶表中加入weixinId字段,跳轉至自己的用戶綁定界面,如果用戶選擇綁定微信,則更新該行用戶數據的weixinId。下次用戶使用微信登錄時,如果通過openId能夠查詢到一條用戶數據,說明已經綁定,則登錄該用戶

完整代碼:

uni.getUserProfile({
                    desc: '123',
                    lang: 'zh_CN',
                    success: res => {
                        //拉取用戶成功,調用登錄
                        uni.login({
                            provider: 'weixin',
                            success: res => {
                                //console.log(res);
                                if (res.errMsg == "login:ok") {
                                    this.code = res.code;
                                    //請求后端接口換取 openid 和 session_key,這里放到后端去請求code2Session接口,將返回的openid和sessionkey再返回給前端                     

                        uni.request({
                        url: 'WebService/xxxxxxxx/GetWxOpenId',
                        data: {
                          code: this.code
                          }
                        }).then((res)=>{

                        //獲取到 openid 和 session_k后,自己的邏輯

                          console.log(res.openId);
                          console.log(res.session_key);

                        //DoSomeThing.................

                        })

                                } else {

 uni.showModal({ title: '登錄失敗', content: '系統異常,請聯系管理員' }); } } }) }, fail: faleres => { console.log(faleres); uni.hideLoading(); } })

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM