# Alipay

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

Example Demo:

# Prerequisites

You need to prepare the following in total:

  1. Register an Authing developer account
  2. Apply for a registered Alipay mobile application
  3. Fill in the Alipay mobile application information in the Authing console

# Apply to register for Alipay mobile application

Go to Alipay Open Platform (opens new window) to register the Alipay mobile application, you need to follow the instructions of this page (opens new window) Generate a pair of RSA key pairs, keep the private key properly, and submit the public key to Alipay in exchange for the Alipay public key.

Please make sure that the "Get Member Information" function is turned on.

# Fill in the Alipay mobile application information in the Authing console

In the Authing console Connect Identity Source -> Social Login page, find "Alipay Mobile Application" in "Mobile Social Login":

Fill in your Alipay mobile application information here:

# Formal access

# Access AlipaySDK-iOS

Please follow the instructions of Alipay Client iOS Integration Process (opens new window). If you encounter problems, here is a Swift Demo App for developers’ reference: https: //github.com/authing/AuthingIOSDemo (opens new window).

# Access AlipaySDK-iOS

Please follow the instructions of Alipay Client iOS Integration Process (opens new window). If you encounter problems, here is a Swift Demo App for developers’ reference: https: //github.com/authing/AuthingIOSDemo (opens new window).

# Get authInfo

To start Alipay, you need to obtain and generate authInfo from the server first, and developers can call our interface:

GET
https://core.authing.cn/connection/social/alipay/:userPoolId/authinfo
Path Paramter
userPoolId
REQUIRED
string

User pool ID

200: OK
{
  "code": 200,
  "message": "Get authinfo successfully",
  "data": "apiname=com.alipay.account.auth&app_id=2018010901722731&app_name=mc&auth_type=AUTHACCOUNT&biz_type=openservice&method=alipay.open.auth.sdk.code.get&pid=2088422236285260&product_id=APP_FAST_LOGIN&scope=RSA8e8e-4888-type=RSA8e-4 -82bdc5786cec & sign = inNShZI0RrLvR% 2F3V10tAQOQTLSmUKNtzbXbmDKVKGXc% 2FCeIhoGqv4hrD4amq4h8ejj9PwAJkToXxLZI% 2FSNQDcABFsrPGagKMpIn7wOBBYKHguOt5gJmG0D305eehmXheosDu4GmhPPpDe3Lks4aWjwswbN2rD2KqqGKOrEtTrXIomc% 2By30F37E2rH8jwo7zeATjY% 2B27qbgu% 2FlGkHg0SwZ1GHs% 2Fxic0xRMilxDRCd% 2BSLYuyQhqBO% 2B6lKXA% 2BZb8N1V5GHWLkC1rpNEKPgfXwU6lWaXJ6JfFKIshPsJYEXRbTtIDUqI5sd8o8Y68MlYf1OlsOKmz24% 2FZRKm% 2Bu2JpVyWpw% 3D% 3D "
}

swift code example:

import Alamofire

let GetAuthInfoUrl = "https://core.authing.cn/connection/social/alipay/<YOUR_USERPOOL_ID>/authinfo"

func loginByAlipay() {

    // Get authInfo
    AF.request(GetAuthInfoUrl).responseString {response in
        let resp = convertToDictionary(text: response.value!)!

        // Authing business status code, 200 means success
        let code = resp["code"]! as! Int
        let message = resp["message"]! as! String
        if code == 200 {
            let authInfo = resp["data"]! as! String
            debugPrint("authInfo: \(authInfo)")

            // Open Alipay
            AlipaySDK().auth_V2(withInfo: authInfo, fromScheme: "authing-alipay", callback: {resp in
                debugPrint(resp)
            })
        } else {
            debugPrint("Message: ", message)
        }
    }
}

# Open Alipay login

Swift sample code:

// Open Alipay
AlipaySDK().auth_V2(withInfo: authInfo, fromScheme: "authing-alipay", callback: {resp in
    debugPrint(resp)
})

The fromSchema here needs to be consistent with the URL Schema in the set URL Types: as shown in the figure below:

# Receive Alipay callback data

You can get Alipay callback data in the following methods (see this Demo (opens new window) for details):

func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>)

Swift sample code:

func parseUrlQueryString(string: String) -> [String:Any] {
    let arr = string.components(separatedBy:"&")
    var data = [String:Any]()
    for row in arr {
        let pairs = row.components(separatedBy:"=")
        data[pairs[0]] = pairs[1]
    }
    return data
}


// schema callback
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    let url = URLContexts.first?.url
    let schema = url!.scheme
    switch schema {
    case AlipayURLSchema:
        AlipaySDK().processAuth_V2Result(url, standbyCallback: {back in
            let response = back!
            let resultStatus = response["resultStatus"] as! String
            let memo = response["memo"]
            let result = response["result"] as! String

            let data = parseUrlQueryString(string: result)
            let success = data["success"]
            let result_code = data["result_code"] as! String
            let auth_code = data["auth_code"] as! String
            let user_id = data["user_id"] as! String
            if resultStatus == "9000" && result_code == "200" {
                // proceed to the next logic
            }
        })
    default:
        debugPrint("???")
    }
}

# Exchange user information

The auth_code obtained in the previous step can be exchanged for user information through the following API:

GET
https://core.authing.cn/connection/social/alipay/:userPoolId/callback
Path Paramter
userPoolId
REQUIRED
string

User pool ID

200: OK
{
  id: '5f8ff3f3864c9c62bb76fdb1',
  email: null,
  emailVerified: false,
  unionid:'alipay:2088422236285260',
  openid: null,
  oauth:'{"code":"10000","msg":"Success","avatar":"https://tfs.alipayobjects.com/images/partner/TB1_fGraDXGDuNjmf7YXXctaXXa","city":"Huaihua City" ,"gender":"m","isCertified":"T","isStudentCertified":"F","nickName":"Bob","province":"Hunan Province","userId":"2088422236285260", "userStatus":"T","userType":"2"}',
  registerSource: ['social:alipay' ],
  username: null,
  nickname:'Bob',
  company: null,
  photo:'https://tfs.alipayobjects.com/images/partner/TB1_fGraDXGDuNjmf7YXXctaXXa',
  token:'YOUR_TOKEN',
  phone: null,
  tokenExpiredAt: 2020-11-05T09:05:09.844Z,
  loginsCount: 7,
  lastIP: undefined,
  signedUp: 2020-10-21T08:40:19.036Z,
  blocked: false,
  isDeleted: false
}

Swift code example:

let url = "https://core.authing.cn/connection/social/alipay/\(UserPoolId)/callback?auth_code=\(auth_code)"
AF.request(url).responseString {response in

    // Convert response.value into a string, the example is as follows:
    // ["code": "200", "message": "Obtaining user information successfully", data: ""]
    let resp = convertToDictionary(text: response.value!)!
    let data = resp["data"] as! [String: Any]
    debugPrint("Data: \(data)")
}

# Next Step

Congratulations, you have now accessed the Alipay mobile application login. 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 backend interface. For details, see [Verification token](../ ../advanced/verify-jwt-token.md#yan-zheng-authing-qian-fa-de-token).

We also provide React Native SDK, which allows you to quickly access Alipay login in React Native:

SDK for React Native