uniapp 微信获取手机号登录

485 阅读1分钟

用户点击微信登录,跳转到下方页面

<template>
    <view class="minipro-wxlogin-container yx-flex-col-center-center yx-pos-center">
        <image style="width: 140rpx;height: 140rpx;margin-bottom: 80rpx;" src="/static/paipan-logo.png" />
        <button 
            class="yx-flex-row-center-center yx-rounded-50" 
            style="color: #fff;background-color: var(--yxPrimaryColor);width: 710rpx;height: 100rpx;" 
           type="default" open-type="getPhoneNumber"  @getphonenumber="yxGetPhoneLogin"
        >
            <image class="yx-mr-20" style="width: 50rpx;height: 50rpx;" src="/static/weixin-login.png" />
            <text>手机号快捷登录</text>
        </button>
    </view>
</template>

<script>
export default {
    name: 'minipro-wxlogin'
}
</script>
<script setup>
import { onLoad } from '@dcloudio/uni-app';

import { miniproAuth, miniproLogin, getUserCenterInfo, } from '@/api/modules/userApi.js';
import { yxLoginAfterStep } from './util.js';

let auth_key = '';

// step1: 进入该页面,立即小程序授权登录
onLoad(async () => {
    const { code } = await uni.login({
        provider: 'weixin'
    });
    try{
        let res = await miniproAuth({code});
        // 到这一步代表用户已经绑定手机号
        yxLoginAfterStep({
            socket_token: res.socket_token,
            session_id: res.session_id
        })
    }catch(e) {
        // 到这一步代表用户未绑定手机号,保存auth_key,后续用户绑定手机号时传递给接口
        auth_key = e.data.auth_key;
    }
});

// step2: 小程序中获取手机号并登录
const yxGetPhoneLogin = async (phoneInfo) => {
    const { code } = await uni.login({
         provider: 'weixin'
    });
    
    let res = await miniproLogin({
        "auth_key": auth_key, //小程序授权后,未绑定手机号时返回的auth_key
        "code": code, // 注意:这里的code要再调用一次uni.login获取,并非获取手机号的code
        "encryptedData": phoneInfo.detail.encryptedData, //授权手机号的encryptedData
        "iv": phoneInfo.detail.iv //授权手机号的iv
    });

    yxLoginAfterStep({
        socket_token: res.socket_token,
        session_id: res.session_id
    })
}
</script>

<style lang="scss">

</style>

函数yxLoginAfterStep()做的事:保存token到store,并调用获取用户接口,再将用户信息存到store