# 小程序登录

Authing 通过 SDK 为开发者提供了一种快速在小程序中获取用户信息并完成登录的方法。通过 Authing 的 SDK 可以方便地获取微信提供的用户身份标识,快速建立以手机号码为基础的账号体系。

如下所示:

# 准备工作

  1. Authing 开发者账号
  2. 申请微信小程序
  3. 在 Authing 后台填入你的小程序信息

# 申请微信小程序

  1. 前先前往微信开放平台 (opens new window)注册一个微信小程序开发账号
  • 如果你需要获取用户手机号,需要通过微信认证。
  • core.authing.cn 加入微信的 request 合法域名:

  1. Authing 控制台 (opens new window)开启微信小程序社会化登录。
  • 获取微信小程序 AppId 和 AppSecret

  • 填入小程序 AppId 和 AppSecret,点击保存即可。

# 安装 Authing SDK

从小程序基础库版本 2.2.1 或以上、及开发者工具 1.02.1808300 或以上开始,小程序支持使用 npm 安装第三方包,详情请见: npm 支持 | 微信开放文档 (opens new window)

# 安装 npm 包

使用 npm:

npm install authing-wxapp-sdk

使用 yarn:

yarn add authing-wxapp-sdk

# 在小程序开发者工具中构建 npm

点击开发者工具中的菜单栏:工具 --> 构建 npm:

勾选 使用 npm 模块 选项:

# 初始化 Authing SDK

AuthenticationClient 初始化需要传入用户池 ID (userPoolId):

你可以在此了解如何获取 UserPoolId (opens new window),如果你对用户池的概念不是很了解,可以在此了解 Authing 系统的核心概念 (opens new window)

const { AuthenticationClient } = require("authing-wxapp-sdk")

const authing = new AuthenticationClient({
  userPoolId: "YOUR_USERPOOL_ID",
})

# 使用方法

在用户完成登录之后,SDK 会将用户的 token 写入到微信的 Storage 中,后续请求会自动携带 token 访问。

const { code } = await wx.login()
// 无需用户授权
const user = await authing.loginByCode(code); // 成功登录,将 token 写入微信 Storage

// 登录之后可以进行此操作
await authing.updateProfile(
  nickname: 'Bob'
)

后续用户再次打开小程序,如果小程序的 Storage 中保存有用户的 token,访问 authing 的请求将会自动带上该 token。

// 该请求可以成功,因为该用户出于登录状态。
await authing.updateProfile(
  nickname: 'Mick'
)

详细请见 Authing 小程序 SDK:

SDK for 微信小程序