wx.weixinMiniProgramLogin(Object object)

调用 JSAPI 唤起微信小程序登录,获取临时登录凭证 (code),通过凭证进而换取用户标识信息等。另外,登录成功后,可以调用微信 JSAPI 以使用微信开放能力,如云开发等。

前置准备

  • 微信移动应用能力初始化
  • 引入微信能力拓展 SDK
  • 配置唤起的微信小程序版本。
    • app.miniapp.json 中,添加 “authorizeMiniprogramType” 参数,可指定跳转小程序版本 (0:正式版,1:开发版,2:体验版)。
  • 配置小程序官方授权页
    • app.json 中,添加 “useAuthorizePage” 参数,并设为 “true”。配置后,小程序将在编译时插入小程序官方授权页 (官方授权页不占用代码包体积)。
  • 在微信开发者工具中,选择“小程序模式”,点击预览,使用微信扫码。

参数

Object object

属性类型默认值必填说明
redirectPathstring指定授权完小程序跳转的页面
successfunction接口调用成功的回调函数
failfunction接口调用失败的回调函数
completefunction接口调用结束的回调函数

object.success 回调函数

参数
Object res
属性类型说明
codestring用户登录凭证(有效期五分钟)。开发者可以在开发者服务器调用 code2Verifyinfoopen in new window,使用 code 换取用户标识信息等

object.fail 回调函数

参数
Object res
属性类型说明
errCodenumber错误码
errMsgstring错误提示

res.errCode

errCode说明
-1system error
10001005多端应用未接入身份管理
10001008多端应用未绑定开发小程序
10001016多端应用模块绑定开发小程序错误
-700000前端错误,errMsg 将给出详细提示

常见前端错误

errMsg指引
sendOpenReq:fail launch wechat fail需配置移动应用账号,具体查看微信移动应用能力初始化

示例代码

wx.weixinMiniProgramLogin({
  redirectPath: 'pages/home/index',
  success (res) {
    if (res.code) {
      // 发起网络请求
      wx.request({
        url: 'https://example.com/onLogin',
        data: {
          code: res.code
        }
      })

      // login 成功后,可以直接使用云开发功能
      wx.cloud.callFunction({
        name: 'myCloudFunction'
      })

    } else {
      console.log('登录失败!' + res.errMsg)
    }
  }
})