# Launch Wechat Mini Program from App

"Mobile Application Mini Program Login" refers to the use of WeChat's open capabilities in mobile applications to evoke WeChat Mini Program "Mini Login" and obtain user WeChat authorization to log in. This method can get the user's mobile phone number.

This login method provides GitHub Demo: https://github.com/authing/AuthingIOSDemo (opens new window)

Example Demo:

You can scan the QR code of the mini program below to experience the "small login":

If you want to privatize and deploy your own small program, you can contact us. Mobile phone number: [176-0250-2507] (tel: 176-0250-2507).

# Ready to work

  1. Authing developer account
  2. Apply for WeChat mobile application (opens new window)
  3. Small login associated with mobile apps
  4. Fill in your mini program information in the Authing backend (requires the developer of privatization deployment)

# Mobile App Association Login

In WeChat Open Platform (opens new window) "Management Center-Mobile Application-Application Details-Associated Mini Program Information", you can initiate an association mini-program for the approved mobile application Program operation. The AppID of the small login is wxa0435021fd7a3af2.

# Configure the applet information in the Authing console (optional, required for privatization deployment)

On the Authing console User Pool -> Third Party Login -> Social Login page, find the "Mobile Application Mini Program Login" in "Mobile Social Login":

Fill in the AppID and AppSecret of your applet:

# Custom configuration items

Authing has always been committed to bringing developers a highly customized development experience. Therefore, we provide the following custom configuration items. Developers can balance security and convenience according to their business needs.

Developers can log in from the Authing console (opens new window) Basic Configuration -> Basic Settings -> App opens the applet Define the custom configuration at the configuration item.

# Do you need a user pool secret in exchange for user information

The default is true. If enabled, you must bring the user pool secret when using the ticket in exchange for user information. This means that you cannot directly exchange user information in the App, and must be done on the server side.

# ticket valid time

The default is 120 seconds.

# Access process (take Swift as an example)

# Initiate a request to launch a mini program in the App

Developers need to call WechatOpenSDK (see WeChat official document (opens new window) for the specific access process to call up the mini program:

-Mini program userName is gh_a781a791e29e -path is /routers/explore -The path query parameters are: -userPoolId: your user pool ID -getPhone: Whether it is necessary to get the user's mobile phone number, 1 means it is required, not fill in or other means it is not required -fromApp: 1, this parameter is required. -useSelfWxapp: 0. This parameter is required.

Take the swift language as an example:

let userPoolId = "5e4cdd055df3df65dc58b97d"
let req = WXLaunchMiniProgramReq()
req.userName = "gh_a781a791e29e"
req.path = "/routes/explore?userPoolId=\(userPoolId)&getPhone=1&fromApp=1&useSelfWxapp=0"
req.miniProgramType = WXMiniProgramType.test
WXApi.send(req)

# Receive data returned by the applet

The small login will return a string of URL Query String to the App, and the developer can convert it into a dictionary:

-code: business status code, 200 means success. -message: prompt message. -ticket: attached when authorization is successful. Developers can use this to get user information

func onResp(_ resp: BaseResp) {
    print("onResp: type=\(resp.type)")
    if resp.isKind(of: WXLaunchMiniProgramResp.self) {
        if resp.errCode == 0 && resp.type == 0{//Authorization is successful
            let response = resp as! WXLaunchMiniProgramResp
            let extMsg = response.extMsg!
            // WeChat login successful notification
            debugPrint(extMsg)
            let arr = extMsg.components(separatedBy:"&")
            var data = [String:Any]()
            for row in arr {
                let pairs = row.components(separatedBy:"=")
                data[pairs[0]] = pairs[1]
            }
            let code = data["code"]
            let message = data["message"]
            let ticket = data["ticket"]
            debugPrint(code, message, ticket)
        }
    }
}

# Get user information

If the user agrees to the authorization, the developer can use the ticket in exchange for user information, and the ticket is valid for two minutes by default. By default, for security reasons, the ticket exchange for user information requires a user pool key, which means that user information cannot be exchanged directly in the App. We also provide developers with the right to choose. Developers can modify this option on the user pool basic configuration page (see above).

POST
https://core.authing.cn/oauth/app2wxapp/auth/:userPoolId

ticket in exchange for user information

Path Paramter
userPoolId
REQUIRED
string

User pool ID

Headers
content-type
REQUIRED
string

application/json

Body Paramter
secret
OPTIONAL
string

User pool key

tickett
REQUIRED
string

The ticket returned by the applet to the App

200: OK

_id is the user ID.

{
  emailVerified: false,
  username:'Liao Changjiang',
  nickname:'Liao Changjiang',
  company:'',
  photo:'https://usercontents.authing.cn/avatar-5e57540f84622ae263294a42-1582781455906',
  loginsCount: 2,
  registerMethod:'oauth:app2wxapp',
  blocked: false,
  isDeleted: false,
  oauth:'{"nickName":"Liao Changjiang","gender":1,"language":"zh_CN","city":"Haidian","province":"Beijing","country":"China" , "avatarUrl": "https://wx.qlogo.cn/mmopen/vi_32/8INxh2bxDMiaU05jLqvWBszALu2u8Qw4iaxV58v4fERaDWV8yunE7icNiahJdxkOCNfGosqXcQ2SyScAcdyibv8uWWQ/132", "phone": "17670416754", "openid": "o1p9H4wAgb9uTqpxG5Z1g0pIr3FE", "unionid": "o0pqE6Fbr5M-exSu_PeL_sjwN44U" }',
  metadata:'""',
  _id: "5e57540f84622ae263294a42",
  unionid:'o0pqE6Fbr5M-exSu_PeL_sjwN44U',
  openid:'o1p9H4wAgb9uTqpxG5Z1g0pIr3FE',
  lastIP:'::ffff:192.168.0.106',
  lastLogin: "2020-02-27T05:33:20.796Z",
  signedUp: "2020-02-27T05:30:55.875Z",
  token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7InVuaW9uaWQiOiJvMHBxRTZGYnI1TS1leFN1X1BlTF9zandONDRVIiwiaWQiOiI1ZTU3NTQwZjg0NjIyYWUyNjMyOTRhNDIiLCJjbGllbnRJZCI6IjVlNGNkZDA1NWRmM2RmNjVkYzU4Yjk3ZCJ9LCJpYXQiOjE1ODI3ODE2MDAsImV4cCI6MTU4NDA3NzYwMH0.pd7HJu5Ft8uytxIy4VgHdQiaAKuo96P_LcABFwM7OPI',
  tokenExpiredAt: "2020-03-13T05:33:20.000Z",
  phone: '176xxxx6754'
}

swift code example:

import Alamofire

struct Body: Encodable {
    let ticket: String
}
let body = Body(ticket: ticket)
let url = "https://core.authing.cn/oauth/app2wxapp/auth/5e4cdd055df3df65dc58b97d?ticket=\(ticket)"
AF.request(
    url,
    method: .post,
    parameters: body,
    encoder: JSONParameterEncoder.default
).responseJSON {response in
    debugPrint("Response: \(response)")
}

# Next Step

Congratulations, you have accessed the WeChat mobile application to log in. After obtaining the user information, you can get the login credential token. You can carry this token in subsequent API requests, and then distinguish different users based on this token in the back-end interface. For details, see [Verification token](../ ../advanced/verify-jwt-token.md#yan-zheng-authing-qian-fa-de-token).