Skip to content
This repository has been archived by the owner on Feb 26, 2023. It is now read-only.

Authing/authing-wxapp-sdk

Repository files navigation

This repository no longer maintained, please move to authing-js-sdk

npm version download standardjs License Node

English | 简体中文

Authing Miniapp SDK(authing-wxapp-sdk) is suitable for use in wechat Miniapp environmen,baseed authing-js-sdk,adapted wechat Miniapp environment。You can use authing-js-sdk AuthenticationClient all methods,such as obtaining and modifying user data, adding user-defined fields, etc。For example: Obtain the user's mobile phone number through wechat authorizationLog in with wechat authorizationLog in with the mobile number authorized by wechat, etc。

Configuring Miniapp login in Authing

To use the authoring Miniapp SDK in Miniapp,you need to apply for a small program on theWeixin Official Accounts Platform,and at the same time Authing Console fill in the configuration of the Miniapp.

Configure Miniapp login
  1. Go to Weixin Official Accounts Platform first, register a wechat Miniapp development account.
  • If you need to obtain the user's mobile phone number, you need to pass wechat authentication.

  • Add core.authing Cn to request legal domain name:

  1. Go to Authing 控制台 open wechat Miniapp social login.
  • Get appId and appSecret of wechat Miniapp

  • Fill in the Miniapp appId and appSecret, and click save.

Install

Starting from the basic library version 2.2.1 or above and the developer tool 1.02.1808300 or above, the applet supports the installation of third-party packages using NPM. For details, please refer to: npm support.

Install NPM package

Use NPM:

npm install authing-wxapp-sdk

Use Yarn:

yarn add authing-wxapp-sdk

Building NPM in Miniapp developer tools

Click the menu bar in the developer tool:Tool --> building npm:

Check the use NPM module Option:

Initialize

Init AuthenticationClient need passing AppId:

You can view your application list in applications on the console.

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

const authing = new AuthenticationClient({
  appId: "YOUR_APP_ID",
});

The complete parameter list is as follows:

  • appId: Authing APP ID(required);
  • accessToken: Initialize the SDK through the user's token (optional, you can cache the user's token in the front-end localstorage to realize the purpose of remembering login).
  • timeout: Request timeout, unit: ms, default: 10000 (10 seconds).
  • onError: Error handling function, you can use it to catch all exceptions requested by the authoring client globally. The function is defined as:
(code: number, message: string, data: any) => void

Refer to for complete error codes doc

  • host: Authing server。If you are using the public cloud version, please ignore the parameter. This parameter is required if you are using the version of privatized deployment. The format is as follows:: https://authing-api.mydomain.com,finally, without /.

Usage

After the user logs in, the SDK will write the user's token into the storage of wechat, and subsequent requests will automatically carry the token for access.

const { code } = await wx.login();
// No user authorization required
const user = await authing.loginByCode(code); // 成功登录,将 token 写入微信 Storage

// You can do this after logging in
await authing.updateProfile((nickname: "Bob"));

Subsequently, the user opens the applet again. If the token of the user is saved in the storage of the applet, the request to access authing will automatically carry the token.

// The request can succeed because the user is logged in.
await authing.updateProfile((nickname: "Mick"));

API Reference

You can use authing-js-sdk AuthenticationClient all methods,the calling method is completely consistent with Authing JS SDK.

loginByCode

Log in with wechat authorization。

  • If the user logs in the applet for the first time, and the user has not logged in using the wechat application bound to the same subject as the applet, a new account will be created.
  • If the user logs in the applet for the first time, but the user has logged in using the wechat application of the same subject bound to the applet, the corresponding wechat account will be returned.

Parameter

  • code: Call wx.login() get the code,no user authorization is required. Required。
  • options: Optional。
  • options.iv: open-type is getUserInfo Weixin Button Component returned iviv and encryptedData are required,The Authing server will attempt to encrypt user data from 'iv' and 'encrypteddata'. Manual authorization is required for the first time. Optional.
  • options.encryptedData: open-type is getUserInfo Weixin Button Component returned encryptedDataiv and encryptedData are required. The server will attempt to encrypt user data from 'iv' and 'encrypted data'. Manual authorization is required for the first time. Optional.
  • options.rawData: open-type is getUserInfo Weixin Button Component returned rawData. Choose between 'iv' + 'encrypteddata'. If 'rawdata' is passed, the authing server will directly use the data as the user's profile. Manual authorization is required for the first time. Optional.

Example

  1. Silent authorization

The nickname and avatar in the profile of the first registered user will be empty because the user's Avatar and nickname are not obtained.

const { code } = await wx.login();
const data = await authing.loginByCode(code);
  1. User manually authorized to obtain nickname Avatar

Authorization is only required for the first time. Users can use Wx GetUserInfo get the nickname of the avatar directly

  • Request user manual authorization for the first time
<button open-type="getUserInfo" bindgetuserinfo="getUserInfo">
  Get avatar nickname
</button>
getUserInfo: async function (e) {
  const { code } = await wx.login()
  const { rawData } = e.detail
  const user = await authing.loginByCode(code, { rawData })

  // or passing iv encryptedData
  // const { iv, encryptedData } = e.detail
  // const user = await authing.loginByCode(code, { iv, encryptedData })

  console.log(user)
}
  • After that, you can use the wx.getUserInfo auto get
const { rawData } = await wx.getUserInfo();
const user = await authing.loginByCode(code, { rawData });
// 或者传 iv encryptedData
// const { iv, encryptedData } = e.detail
// const user = await authing.loginByCode(code, { iv, encryptedData })

loginByPhone

Log in through wechat mobile number authorization. Each call requires manual authorization by the user.

  • If the mobile phone number is registered for the first time, it will bind the mobile phone number with the wechat account (it will be created if it does not exist).
  • If the mobile phone number has been registered before, the account corresponding to the mobile phone number will be returned, and the mobile phone number will be bound with the current wechat account.

Parameter

Example

<button open-type="getPhoneNumber" bindgetphonenumber="getPhone">
  get phone code
</button>
getPhone: async function(e) {
  const { code } = await wx.login()
  const { iv, encryptedData } = e.detail
  const data = await authing.loginByPhone(code, iv, encryptedData)
  console.log(data)
}

getPhone

Get the mobile phone number of the current user (you will not use this mobile phone number to register or bind an account).

Parameter

Example

<button open-type="getPhoneNumber" bindgetphonenumber="getPhone">
  获取手机号
</button>
getPhone: async function(e) {
  const { code } = await wx.login()
  const { iv, encryptedData } = e.detail
  const data = await authing.getPhone(code, iv, encryptedData)
  console.log(data)
}

Example of returned data:

{
  "countryCode": "86",
  "phoneNumber": "176xxxx6754",
  "purePhoneNumber": "176xxxx6754",
  "openid": "o1p9H4wAgb9uTqpxG5Z1g0pIr3FE",
  "unionid": "o0pqE6Fbr5M-exSu_PeL_sjwN44U"
}

updateAvatar

Update user avatar, this method will automatically call wx.chooseimage to get the image and upload it to the CDN of authoring, only one line of code is required.

Example

const { photo } = await authing.updateAvatar();
console.log(photo);

Best practices

We recommend that when the user uses the applet for the first time, use 'loginbycode' to obtain the authing account corresponding to the applet account. If the account has been bound with a mobile phone number before, there is no need to request the user to authorize the mobile phone number again. If the account is not bound with a mobile phone number, call the 'loginbyphone' method to request the user to authorize a mobile phone number.

After the user logs in, authing wxApp SDK will write the token to the storage of the applet. You can call authing.checkloginstatus() judge whether the user's token is valid, and log in again when the token is invalid.

Error handling

You can use try catch to handle errors:

try {
  const user = await authing.loginByEmail("test@example.com", "passw0rd");
} catch (error) {
  console.log(error.code); // 2004
  console.log(error.message); // User does not exist
}

See for complete error codes: doc

You can also specify onerror to catch all authing request exceptions, such as using wx.showmodal and other wechat components display error prompts.

const authing = new AuthenticationClient({
  userPoolId,
  onError: (code, message) => {
    wx.showModal({
      content: message,
      showCancel: false,
    });
  },
});

Contribution

  • Fork it
  • Create your feature branch (git checkout -b my-new-feature)
  • Commit your changes (git commit -am 'Add some feature')
  • Push to the branch (git push origin my-new-feature)
  • Create new Pull Request