1. 程式人生 > 其它 >uniapp app端一鍵微信登入和小程式端一鍵微信登入

uniapp app端一鍵微信登入和小程式端一鍵微信登入

        <view class="wx">
            <view class="subtitle">微信快捷登入</view>
            <!-- #ifdef MP-WEIXIN -->
            <text class="iconfont icon-weixin" @tap="wxLogin"></text>
            <text>微信端</text>
            <!-- #endif -->
            <!-- #ifdef  H5 || APP-PLUS -->
            <text class
="iconfont icon-weixin" @tap="appLogin"></text> <text>app端</text> <!-- #endif --> </view>

//小程式登入 begin登入
// 邏輯:登入 > 拿到code > 後端通過code獲取sessionKey、openid(unionid)等

        wxLogin(e) {
            let _this = this;
          uni.login({
                    provider: 
'weixin', success: function(res) { console.log(res); if (res.code) { let code = res.code; //將使用者登入code傳遞到後臺置換使用者SessionKey、OpenId等資訊 //...寫用code置換SessionKey、OpenId的介面
// _this.$http.post("/api/user/login", {code:code}) // .then(res => { // let openId= res.openId; // _this.wxSubmit(openId) // }) // .catch(err => { // _this.$ant.toast('登入失敗') // }); } else { uni.showToast({ title: '登入失敗!', duration: 2000 }); console.log('登入失敗!' + res.errMsg) } }, });         }

// app登入邏輯 app端能直接拿到openId

appLogin() {
                var that = this;
                uni.getProvider({
                    service: 'oauth',
                    success: function(res) {
                        console.log(res.provider);
                        //支援微信、qq和微博等
                        if (~res.provider.indexOf('weixin')) {
                            uni.login({
                                provider: 'weixin',
                                success: function(loginRes) {
                                    console.log("App微信獲取使用者資訊成功", loginRes);
                                    // 獲取使用者資訊
                                    uni.getUserInfo({
                                        provider: 'weixin',
                                        success: function(infoRes) {
                                            console.log('-------獲取微信使用者所有-----');
                                            console.log(infoRes.userInfo.openId);
                                            console.log(JSON.stringify(infoRes.userInfo));
                                                // 提交資訊
                                                that.wxSubmit(infoRes.userInfo.openId)
                                                
                                        }
                                    });
                                    // that.getApploginData(loginRes) //請求登入介面方法
                                },
                                fail: function(res) {
                                    console.log("App微信獲取使用者資訊失敗", res);
                                }
                            })
                        }
                    }
                });
            },

記錄時間2021-07-13,親測有效,有用的話,麻煩給點個贊。