前言

uniapp混合开发实现授权登录功能,代码兼容微信H5、支付宝H5、微信小程序、支付宝小程序


一、微信H5授权登录实现

// 在入口页面检测URL中是否包含code参数
onLoad() {
  const urlParams = new URLSearchParams(window.location.search)
  if (urlParams.has('code')) {
    this.wechatH5Login(urlParams.get('code'))
    // 清除URL中的code参数
    window.history.replaceState({}, document.title, window.location.pathname)
  }
}

// 微信H5跳转授权
wechatH5Auth() {
  const appid = '你的微信公众号appid'
  const redirectUri = encodeURIComponent(window.location.href.split('?')[0])
  const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
  window.location.href = authUrl
}

// 微信H5登录逻辑
async wechatH5Login(code) {
  try {
    const res = await uni.request({
      url: '你的后端接口地址',
      method: 'POST',
      data: { code, type: 'wechat_h5' }
    })
    // 登录成功后跳转
    window.location.href = '/pages/home/index'
  } catch (error) {
    console.error('微信H5登录失败', error)
  }
}
 

二、支付宝H5授权登录实现

// 支付宝H5授权跳转
alipayH5Auth() {
  const appId = '你的支付宝应用ID'
  const redirectUri = encodeURIComponent(window.location.href.split('?')[0])
  const authUrl = `https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=${appId}&scope=auth_user&redirect_uri=${redirectUri}&state=init`
  window.location.href = authUrl
}

// 支付宝H5登录处理
onLoad() {
  const urlParams = new URLSearchParams(window.location.search)
  if (urlParams.has('auth_code')) {
    this.alipayH5Login(urlParams.get('auth_code'))
    // 清除URL参数
    window.history.replaceState({}, document.title, window.location.pathname)
  }
}

async alipayH5Login(authCode) {
  try {
    const res = await uni.request({
      url: '你的后端接口地址',
      method: 'POST',
      data: { authCode, type: 'alipay_h5' }
    })
    window.location.href = '/pages/home/index'
  } catch (error) {
    console.error('支付宝H5登录失败', error)
  }
}
 

三、微信小程序授权登录实现

// 获取微信小程序code
getWxMiniProgramCode() {
  return new Promise((resolve, reject) => {
    uni.login({
      provider: 'weixin',
      success: res => resolve(res.code),
      fail: err => reject(err)
    })
  })
}

// 微信小程序获取手机号
async getWxMiniPhoneNumber(e) {
  try {
    const { code, encryptedData, iv } = e.detail
    if (!code) {
      const loginCode = await this.getWxMiniProgramCode()
      const res = await uni.request({
        url: '你的后端接口地址',
        method: 'POST',
        data: {
          code: loginCode,
          encryptedData,
          iv,
          type: 'wechat_mini'
        }
      })
      uni.redirectTo({ url: '/pages/home/index' })
    }
  } catch (error) {
    console.error('微信小程序登录失败', error)
  }
}
 

四、支付宝小程序授权登录实现

// 支付宝小程序授权
alipayMiniAuth() {
  return new Promise((resolve, reject) => {
    my.getAuthCode({
      scopes: 'auth_user',
      success: res => resolve(res.authCode),
      fail: err => reject(err)
    })
  })
}

// 支付宝小程序登录
async alipayMiniLogin() {
  try {
    const authCode = await this.alipayMiniAuth()
    const res = await uni.request({
      url: '你的后端接口地址',
      method: 'POST',
      data: { authCode, type: 'alipay_mini' }
    })
    uni.redirectTo({ url: '/pages/home/index' })
  } catch (error) {
    console.error('支付宝小程序登录失败', error)
  }
}
 

五、统一登录入口处理

// 根据平台执行不同登录方式
handleLogin() {
  // #ifdef H5
  if (navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1) {
    this.wechatH5Auth()
  } else if (navigator.userAgent.toLowerCase().indexOf('alipay') !== -1) {
    this.alipayH5Auth()
  }
  // #endif

  // #ifdef MP-WEIXIN
  this.getWxMiniPhoneNumber()
  // #endif

  // #ifdef MP-ALIPAY
  this.alipayMiniLogin()
  // #endif
}
 

总结

各平台需要在manifest.json中配置相应的appid 微信H5需要确保公众号的网页授权域名已配置 支付宝H5需要配置授权回调域名 微信小程序需要获取手机号权限 支付宝小程序需要添加用户信息授权功能

后端接口需要区分不同平台类型处理授权码 前端跳转时H5平台必须使用window.location.href跳转 小程序平台使用uni的导航方法跳转

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐