# uni.login(OBJECT)

Log in

uni.login is a client API that unifies and encapsulates various common login methods of various platforms, including one-click login with App mobile number, three-party login (WeChat, Weibo, QQ, Apple, Google, Facebook), various MiniApp built-in login.

除了前端API,DCloud还提供了uni-id,这是一个云端一体的、完整的、账户开源框架。不仅包括客户端API,还包括前端页面、服务器代码、管理后台等所有与登录账户有关的服务,包括短信验证码、密码加密存储、忘记密码、头像更新等所有常见账户相关功能。

Platform Difference Description

App Web 微信小程序 支付宝小程序 百度小程序 抖音小程序、飞书小程序 QQ小程序 快手小程序 京东小程序
x

For most login methods, you need to apply for the activation of related services. For details, click the document below to view.

# Login methods supported by App platform

####The login methods supported by the MiniApp platform

# web平台支持的登录方式

Web平台常见的登录包括用户名密码、短信验证码、pc端微信扫描、微信公众号登录。这些没有封装在 uni.login API中,但都封装在了uni-id中。请另行参考uni-id

If you don’t use uni-id, when the WeChat embedded browser runs the H5 version, you can log in to WeChat through js sdk, you need to introduce a separate js, [see details](https://ask.dcloud.net.cn/article /35380)

# OBJECT parameter description

Parameter Name Type Required Description Platform Difference Description
provider String No Login service provider, obtained through uni.getProvider, if not set, the login list selection interface will pop up
scopes String/Array See platform difference description Authorization type, default auth_base. Support auth_base (silent authorization) / auth_user (active authorization) / auth_zhima (Sesame Credit) Alipay MiniApp
timeout Number No Timeout time, unit ms WeChat MiniApp, Baidu MiniApp, Jingdong MiniApp
univerifyStyle Object No one-key login page style App 3.0.0+
onlyAuthorize Boolean No WeChat Login only requests authorization authentication App 3.2.6+
success Function No Interface call success callback
fail Function No Callback function for interface call failure
complete Function No The callback function of the end of the interface call (it will be executed when the call succeeds or fails)

onlyAuthorize Description

When the WeChat login does not configure onlyAuthorize, the user login credential (code) is not returned when calling the uni.login interface, in exchange for login information (authResult); it needs to be configured in the project manifest.json appsecret, this parameter will be saved in apk/ipa after cloud packaging, there is a risk of parameter leakage; HBuilderX3.4.18+ no longer provides visual configuration of this parameter. For developers with low security requirements, you can add appsecret configuration via manifest.json -> source view -> app-plus -> distribute -> sdkConfigs -> oauth -> weixin ->.

success return parameter description

Parameter Name Description Platform Difference Description
authResult The login information provided by the login service provider, the results returned by different service providers are not exactly the same WeChat login configuration onlyAuthorize:true, this item is empty, App 3.2.6+
code 用户登录凭证。开发者需要在开发者服务器后台,使用 code 换取 openid 和 session_key 等信息 微信登录配置onlyAuthorize:true才会返回,App 3.2.6+、京东小程序
appleInfo 苹果登录返回的信息 App 3.4.3+
errMsg Description

example

uni.login({
  provider: 'weixin', //使用微信登录
  success: function (loginRes) {
    console.log(loginRes.authResult);
  }
});

# Precautions

  • 百度小程序平台需要在button组件的@login事件后再调用 uni.login ,详见,否则会返回“请登录”的错误信息,建议在@login事件中调用。
  • uni.login 已针对百度小程序兼容性升级转为 getLoginCode 调用,但某些情况下,百度小程序发布时兼容性诊断依然提示swan.login非兼容性改造,详见,可使用 uni.getLoginCode 替代 uni.login 解决。
  • The JD MiniApp IDE does not support this uni.login() for the time being, please check it with a real device; the IDE call can only return the simulated data with a code of 200.

# uni.getLoginCode(OBJECT)

Obtain the host App login credentials (Authorization Code)

Platform Difference Description

App H5 微信小程序 支付宝小程序 百度小程序 抖音小程序、飞书小程序 QQ小程序 快手小程序 京东小程序
x x x x x x x x

OBJECT parameter description

Parameter Name Type Required Description
timeout Number No Timeout (unit: ms)
success Function No Callback function for successful interface call
fail Function No Callback function for interface call failure
complete Function No The callback function for the end of the interface call (it will be executed when the call succeeds or fails)

success return parameter description

Parameter Name Type Platform Difference Description
code String User login credentials (valid for ten minutes), the developer needs to call the API in the background of the developer server, and exchange the code for session_key and other information. The user login credential code can only be used once.

# uni.checkSession

Check if the login status has expired

1.6.0 Added

Platform Difference Description

App H5 微信小程序 支付宝小程序 百度小程序 抖音小程序、飞书小程序 QQ小程序 快手小程序 快手小程序 京东小程序
x x x x
Attribute Type Required Description
success function No Callback function for successful interface call
fail function No Callback function for interface call failure
complete function No The callback function for the end of the interface call (it will be executed when the call succeeds or fails)

# uni.getUserInfo(OBJECT)

微信小程序端用户头像昵称获取规则已调整,参考 用户信息接口调整说明小程序用户头像昵称获取规则调整公告 The rules for obtaining nicknames and avatars on WeChat MiniApp have been adjusted . Rule Adjustment Announcement](https://developers.weixin.qq.com/community/develop/doc/00022c683e8a80b29bed2142b56c01 )

Get user information.

Platform Difference Description

App H5 微信小程序 支付宝小程序 百度小程序 抖音小程序、飞书小程序 QQ小程序 快手小程序 京东小程序
x

Notice:

  • On the WeChat MiniApp side, if the user calls this interface without authorization, the authorization pop-up window will not appear, and it will directly enter the fail callback (see "WeChat MiniApp announcement"). Calling this interface when the user is authorized can successfully obtain user information.
  • 京东小程序端,在用户未授权,调用该接口将直接报错。用户已经授权过,可使用该接口直接获取用户信息,不会弹二次授权框
  • 抖音小程序此接口将逐步废弃,请切换使用uni.getUserProfile详见

OBJECT parameter description

Parameter Name Type Required Description Platform Difference Description
provider String 登录服务提供商,通过 uni.getProvider 获取
withCredentials Boolean 是否带上登录态信息。 微信小程序、抖音小程序、飞书小程序、快手小程序
lang String No Specifies the language for returning user information, the default is en. For more values, please refer to the description below. WeChat MiniApp
timeout Number No Timeout time, unit ms. WeChat MiniApp
success Function No Interface call success callback
fail Function No Callback function for interface call failure
complete Function No The callback function of the end of the interface call (it will be executed when the call succeeds or fails)

lang value description

value description
zh_CN Simplified Chinese
zh_TW Traditional Chinese
en English

Note: When the MiniApp withCredentials is true or calling uni.getUserInfo in the App, it is required that uni.login has been called before and the login status has not expired. WeChat basic library version 2.10.4 has adjusted the interface related to user information. The userInfo obtained by using uni.getUserInfo is anonymous data. It is recommended to use uni.getUserProfile to obtain user information.

success return parameter description

Parameter Type Description Platform Difference Description
userInfo OBJECT user information object
rawData String 不包括敏感信息的原始数据字符串,用于计算签名。
signature String 使用 sha1( rawData + sessionkey ) 得到字符串,用于校验用户信息。 微信小程序、抖音小程序、飞书小程序、快手小程序、京东小程序
encryptedData String 包括敏感数据在内的完整用户信息的加密数据,详细见加密数据解密算法。 微信小程序、抖音小程序、飞书小程序、快手小程序
iv String 加密算法的初始向量,详细见加密数据解密算法。 微信小程序、抖音小程序、飞书小程序、快手小程序
errMsg String Description

userInfo parameter description

Parameter Type Description Platform Difference Description
nickName String User nickname
openId String The unique user ID of the service provider App
avatarUrl String Avatar
gender String User gender: 0-male, 1-female, 2-confidential Jingdong MiniApp

In addition to the above three necessary information, other information returned by different service providers will be different.

# Expansion instructions for App login

The App side also supports more login-related APIs, such as logout, see details

App-side login-related SDKs need to be configured in the manifest:

  1. Open manifest.json -> App module permission configuration, check OAuth (login authentication).
  2. Open manifest.json -> App SDK configuration, and check the login authentication. There are blue links in the description, which include links to apply for SDKs on WeChat, QQ, Weibo and other platforms.
  3. After applying for SDK information from WeChat, QQ, Weibo and other platforms, fill it back into the manifest.
  4. These configurations need to be packaged to take effect. The real machine operation is still the setting of the HBuilder base, and custom base package can be used. For offline packaging, please refer to the offline packaging documentation to configure it in the native project.
  5. After configuration and packaging, you can get a list of configuration results through uni.getProvider. Note that what is returned here is manifest configuration, and it has nothing to do with whether WeChat, QQ, or Weibo are installed on the mobile phone.

If QQ and Weibo are not installed on the mobile phone, the wap page login of these platforms will be activated when calling, and their client login will be activated if the corresponding client has been installed.

example

uni.login({
  provider: 'weixin',
  success: function (loginRes) {
    console.log(loginRes.authResult);
    // Get user information
    uni.getUserInfo({
      provider: 'weixin',
      success: function (infoRes) {
        console.log('用户昵称为:' + infoRes.userInfo.nickName);
      }
    });
  }
});

# Instructions for integrating other login SDKs such as Alipay and Taobao on the App side

  1. Find plugins in the plugin market
  • [Alipay Login](https://ext.dcloud.net.cn/search?q=%E6%94%AF%E4%BB%98%E5%AE%9D%E7%99%BB%E9%99 %86)
  • Taobao Login
  • sharesdk
  1. Embed the web-view component and use the web login mode to integrate these three-party logins
  2. Develop native plug-ins to integrate three-party SDKs, see details

# uni.getUserProfile(OBJECT)

Wechat MiniApp Basic Library 2.27.1 and above, wx.getUserProfile interface has been withdrawn, for details, please refer to "Announcement on the Adjustment of the Rules for Obtaining MiniApp User Avatar Nicknames".

Get user information. An authorization window will pop up for each request, and userInfo will be returned after the user agrees.

Platform Difference Description

App H5 微信小程序 支付宝小程序 百度小程序 抖音小程序、飞书小程序 QQ小程序 快手小程序 京东小程序
x x √(基础库2.10.4) x x √(基础库2.30.0) x x x

注意:

  • If the business needs to obtain user avatar nicknames, you can use "Avatar Nickname Filling Ability" (Basic Library 2.21 .2 version starts to support, covering iOS and Android WeChat version 8.0.16 and above).
  • This API only supports the WeChat MiniApp(basic library version 2.10.4-2.27.0), and the WeChat MiniApp adjusted the relevant interface (see "MiniApp Login, User Information Related Interface Adjustment Instructions"). Every time uni.getUserProfile is triggered, an authorization window will pop up, and user information can be successfully obtained after user authorization. The API does not currently support asynchronous operations in events, otherwise an error will be triggered: {errMsg: "getUserProfile:fail can only be invoked by user TAP gesture."}

抖音从基础库 2.30.0 开始支持本方法,低版本需做兼容处理。详见

OBJECT parameter description

Parameter Name Type Required Description
desc String Yes Describe the purpose of obtaining the user's personal information, no more than 30 characters
lang String No Specifies the language for returning user information, the default is en. For more values, please refer to the description below.
success Function No Callback for successful interface call
fail Function No Callback function for interface call failure
complete Function No The callback function for the end of the interface call (it will be executed when the call succeeds or fails)

lang value description

value description
zh_CN Simplified Chinese
zh_TW Traditional Chinese
en English

Note: You can use if(uni.getUserProfile) to determine whether uni.getUserProfile is available.

success return parameter description

Parameter Type Description
userInfo OBJECT user information object
rawData String The raw data string excluding sensitive information, used to calculate the signature.
signature String Use sha1( rawData + sessionkey ) to get a string for verifying user information.
encryptedData String Encrypted data of complete user information including sensitive data. For details, see Encrypted Data Decryption Algorithm.
iv String Initial vector of encryption algorithm, see Encrypted Data Decryption Algorithm for details.
cloudID String The cloud ID corresponding to the sensitive data will only be returned if the MiniApp developed by the cloud is activated, and the open data can be obtained directly through cloud calling. For details, see Directly obtaining open data through cloud calling
errMsg String Description

userInfo parameter description

Parameter Type Description
nickName String User nickname
avatarUrl String Avatar
gender Number User gender
country String User's country
province String The user's province
city String User's city
language String Display the language used by country, province, city

Legal values for gender

value description
0 Unknown
1 Male
2 Female

legal values for language

value description
en English
zh_CN Simplified Chinese
zh_TW Traditional Chinese

# uni.preLogin(OBJECT)

pre-login. It is used for one-click login with App phone number.

Platform Difference Description

App H5 微信小程序 支付宝小程序 百度小程序 抖音小程序、飞书小程序 QQ小程序 快手小程序 京东小程序
3.0.0+ x x x x x x x x

OBJECT parameter description

Parameter Name Type Required Description
provider String No Login service provider, obtained through uni.getProvider, currently only supports one-key login
success Function No Callback for successful interface call
fail Function No Callback function for interface call failure
complete Function No The callback function for the end of the interface call (it will be executed when the call succeeds or fails)

# uni.closeAuthView()

Close the one-key login page.

According to the requirements of China Mobile, China Unicom, China Telecom and other operators, one-click login must have an interface. Use this API to close the page.

Platform Difference Description

App H5 微信小程序 支付宝小程序 百度小程序 抖音小程序、飞书小程序 QQ小程序 快手小程序 京东小程序
3.0.0+ x x x x x x x x

# uni.getCheckBoxState(OBJECT)

Get the checkbox status of one-key login clause.

Platform Difference Description

App H5 微信小程序 支付宝小程序 百度小程序 抖音小程序、飞书小程序 QQ小程序 快手小程序 京东小程序
3.2.3+ x x x x x x x x

OBJECT parameter description

Parameter Name Type Required Description
success Function No Callback for successful interface call
fail Function No Callback function for interface call failure
complete Function No The callback function for the end of the interface call (it will be executed when the call succeeds or fails)

success return parameter description

Parameter Type Description
state Boolean One-click login terms checkbox state
errMsg String Description

# uni.getUniverifyManager(OBJECT)

Get the globally unique one-click login manager univerifyManager

Platform Difference Description

App H5 微信小程序 支付宝小程序 百度小程序 抖音小程序、飞书小程序 QQ小程序 快手小程序 京东小程序
√ (3.2.13+) x x x x x x x x

univerifyManager method description

Method Name Type Description
login Function One-key login
preLogin Function One-key login pre-login
close Function Close one-click landing page
getCheckBoxState Function Get the checkbox state of one-click login terms
onButtonsClick Function Subscribe to one-click login custom button click event
offButtonsClick Function Unsubscribe one-click login custom button click event

Usage example

// No need to pass provider when using
const univerifyManager = uni.getUniverifyManager()

// pre-login
// parameters are the same as uni.preLogin
univerifyManager.preLogin()

// Call the one-click login pop-up box
// Only need to pass parameter univerifyStyle
univerifyManager.login({
  univerifyStyle: {
    "fullScreen": true,
    "buttons": {
        "iconWidth": "45px",
        "list": [
            {
                "provider": "apple",
                "iconPath": "/static/apple.png"
            },
            {
                "provider": "weixin",
                "iconPath": "/static/wechat.png"
            }
        ]
    }
  },
  success (res) {
    console.log('login success', res)
  }
})

const callback = (res) => {
  // Get the check status of the one-click login pop-up protocol
  // The parameters are the same as uni.getCheckBoxState
  univerifyManager.getCheckBoxState({
    success(res) {
      console.log("getCheckBoxState res: ", res);
      if (res.state) {
        // Close the one-click login popup
        // The parameters are the same as uni.closeAuthView
        univerifyManager.close()
      }
    }
  })
}

// Subscribe to the custom button click event
univerifyManager.onButtonsClick(callback)
// unsubscribe custom button click event
univerifyManager.offButtonsClick(callback)