uniapp 微信小程序登录

521 阅读1分钟

step1|✨ Promise返回格式互相转换

/**Vue 2 转 Vue 3, 在 main.js 中写入以下代码即可
* 目的是使得Promise符合我们平时的使用习惯
* 详情 https://uniapp.dcloud.net.cn/api/#vue-2-%E5%92%8C-vue-3-%E7%9A%84-api-promise-%E5%8C%96
*/
function isPromise(obj) {
  return (
    !!obj &&
    (typeof obj === "object" || typeof obj === "function") &&
    typeof obj.then === "function"
  );
}

uni.addInterceptor({
  returnValue(res) {
    if (!isPromise(res)) {
      return res;
    }
    return new Promise((resolve, reject) => {
      res.then((res) => {
        if (res[0]) {
          reject(res[0]);
        } else {
          resolve(res[1]);
        }
      });
    });
  },
});

step2|✨ 封装微信登录函数

export async function authLogin() {
  // 获得code
  const { code } = await uni.login({
    provider: 'weixin'
  });
  let { cancel } = await uni.showModal({
    title: '登录',
    content: '为了更好的体验,请登录后继续使用',
  });
  if (cancel) return;
  /**获得头像和用户昵称
  * - 注意事项
  *  2022年11月8日24时,wx.getUserInfo()获取用户头像和昵称被微信回收,
  现在通过 wx.getUserInfo 接口获取用户头像将统一返回默认[灰色头像],昵称将统一返回 “微信用户”。      
  */
  const { userInfo } = await uni.getUserProfile({
    desc: '用于完善个人资料'
  });
  
  /** 此处根据项目需求,自行请求相关接口并保存相关数据。通用流程是
  * - 1、调用登录接口,参数(获得code, 获得头像和用户昵称),成功 => 保存token到store存储
  * - 2、调用获取用户信息,成功 => 保存userInfo到store存储
  */
  await store.dispatch('user/login', { code, userInfo });
}

小程序用户头像昵称获取规则调整公告 developers.weixin.qq.com/community/d…