uniapp实现授权登录

<template>
    <view>
        <!-- #ifdef MP-WEIXIN -->
        <view v-if="isCanUse">
            <view>
                <view class='header'>
                    <image src='../../static/pen.png'></image>
                </view>
                <view class='content'>
                    <view>申请获取以下权限</view>
                    <text>获得你的公开信息(昵称,头像、地区等)</text>
                </view>
                <button class="bottom" type='primary' @click="getUserProfile">
                    登录授权
                </button>
            </view>
        </view>
        <view v-if="isCanUse2">
            <view>
                <view class='header'>
                    <image src='../../static/pen.png'></image>
                </view>

                <view class='content'>
                    <view>申请获取以下权限</view>
                    <text>获得你的手机号用于绑定登录</text>
                </view>
                <button class='bottom' type='primary' open-type="getPhoneNumber" @getphonenumber="PhoneNumber">
                    授权手机登录
                </button>
            </view>
        </view>
        <!-- #endif -->
    </view>
</template>
<script>
    import basesevers from '../../common/basesevers.js'
    export default {
        data() {
            return {
                code: "",
                SessionKey: '',
                OpenId: '',
                avatar: '',
                nick_name: "",
                avatarUrl: null,
                isCanUse: false, //默认为true
                isCanUse2: false //默认为true
            };
        },
        methods: {
            //第一授权获取用户信息===》按钮触发
            // 调用wx.getUserProfile接口
            getUserProfile() {
                var that = this
                // #ifdef MP-WEIXIN
                uni.getProvider({
                    service: 'oauth',
                    success: function(res) {
                        if (~res.provider.indexOf('weixin')) {
                            wx.login({
                                success: (res) => {
                                    that.code = res.code
                                    console.log('获取信息code', res.code);
                                }
                            })
                            uni.getUserProfile({
                                desc: '登录',
                                success: async (res) => {
                                    uni.setStorageSync('isCanUse', false);
                                    that.isCanUse = false
                                    that.isCanUse2 = true
                                    // 后端接口
                                    console.log('获取信息getUserProfile', res);
                                    that.avatar = res.userInfo.avatarUrl
                                    that.nick_name = res.userInfo.nickName
                                    // 这里应该读接口,暂时从前端读
                                    uni.setStorageSync('avatar', res.userInfo.avatarUrl);
                                    uni.setStorageSync('nick_name', res.userInfo.nickName);
                                },
                                fail: (res) => {
                                    console.log(res)
                                }
                            });

                        } else {
                            uni.showToast({
                                title: '请先安装微信或升级版本',
                                icon: "none"
                            });
                        }
                    }
                });
                //#endif
            },
            //登录
            login() {
                let _this = this;
                uni.showLoading({
                    title: '登录中...'
                });
            },

            PhoneNumber(e) {
                var _this = this
                var encry = e.detail.encryptedData;
                var iv = e.detail.iv;
                // 不允许授权
                if (e.detail.errMsg !== "getPhoneNumber:ok") {
                    console.log("没有授权")
                    _this.isCanUse = true;
                    _this.isCanUse2 = false;
                    return;
                }
                console.log('获取信息手机', e);
                uni.request({
                    url: basesevers.request2 + '/connect/token',
                    //url: 'http://192.192.192.183:7003/connect/token',
                    method: 'post',
                    dateType: "json",
                    header: {
                        'content-Type': 'application/x-www-form-urlencoded' //自定义请求头信息
                    },
                    data: {
                        grant_type: 'wechat_mini_code', //你的小程序的APPID
                        client_id: 'client.custom', //你的小程序秘钥secret,  
                        code: _this.code, //wx.login 登录成功后的code
                        username: encry,
                        iv: iv,
                        avatar: _this.avatar,
                        nick_name: _this.avatar
                    },
                    success: (cts) => {
                        if (cts.statusCode == 200) {
                            if (!("access_token" in cts.data)) {
                                console.log('获取失败'); //
                            } else {
                                uni.setStorageSync('access_token', cts.data.access_token);
                                console.log('获取成功'); //
                                // 请求头像开始
                                uni.request({
                                    url: basesevers.request2 + '/api/identity/my-profile',
                                    method: 'get',
                                    dateType: "json",
                                    header: {
                                        'content-Type': 'application/x-www-form-urlencoded', //自定义请求头信息
                                        "Authorization": 'Bearer ' + cts.data.access_token
                                    },
                                    data: {
                                        // grant_type: 'wechat_mini_code', //你的小程序的APPID
                                    },
                                    success: (cts2) => {
                                        if (cts.statusCode == 200) {
                                            console.log("获取后端返回数据", cts2)
                                            // uni.setStorageSync('sub', cts2.data.sub); //写入id
                                            // uni.setStorageSync('name', cts2.data.name); //写入name
                                            uni.reLaunch({ //信息更新成功后跳转到小程序首页
                                                url: '/pages/index/index'
                                            });
                                        } else {
                                            console.log("失败")
                                        }
                                    }
                                });
                            }
                        } else {
                            console.log("没有授权")
                            _this.isCanUse = true;
                            _this.isCanUse2 = false
                        }
                    }
                });
            },
        },

        onLoad() { //默认加载
            //   this.login();
            console.log(this.isCanUse)
            console.log(uni.getStorageSync('isCanUse'))
            if (uni.getStorageSync('access_token') != "") {
                uni.reLaunch({ //信息更新成功后跳转到小程序首页
                    url: '/pages/index/index'
                });
            } else {
                this.isCanUse = true
            }

        }
    }
</script>

<style>
    .header {
        margin: 90rpx 0 90rpx 50rpx;
        border-bottom: 1px solid #ccc;
        text-align: center;
        width: 650rpx;
        height: 300rpx;
        line-height: 450rpx;
    }

    .header image {
        width: 200rpx;
        height: 200rpx;
    }

    .content {
        margin-left: 50rpx;
        margin-bottom: 90rpx;
    }

    .content text {
        display: block;
        color: #9d9d9d;
        margin-top: 40rpx;
    }

    .bottom {
        border-radius: 80rpx;
        margin: 70rpx 50rpx;
        font-size: 35rpx;
    }
</style>

猜你喜欢

转载自blog.csdn.net/wcdunf/article/details/124867457