# 支付宝登录

此社会化登录方式提供 GitHub Demo:https://github.com/authing/AuthingIOSDemo (opens new window)

示例 Demo:

# 准备工作

你一共需要准备以下内容:

  1. 注册一个 Authing 开发者账号
  2. 申请一个注册支付宝应用
  3. 在 Authing 控制台填入支付宝应用信息

# 在 Authing 控制台填入支付宝应用信息

在 Authing 控制台 连接身份源 -> 社会化登录 页面找到 支付宝

在此填入你的支付宝应用信息:

  • AppPrivateKey(应用私钥):上一步生成的应用私钥。

# 正式接入

# 接入 AlipaySDK-iOS

请按照支付宝客户端 iOS 集成流程 (opens new window)的指引,如果遇到问题,这里提供一个 Swift Demo App 供开发者参考:https://github.com/authing/AuthingIOSDemo (opens new window) .

# 获取 authInfo

拉起支付宝需要先在服务器获取生成 authInfo,开发者可以调用我们的接口:

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

用户池 ID

200: OK
{
    "code": 200,
    "message": "获取 authinfo 成功",
    "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=kuaijie&sign_type=RSA2&target_id=8a7a4ac1-888f-4e73-93d8-82bdc5786cec&sign=inNShZI0RrLvR%2F3V10tAQOQTLSmUKNtzbXbmDKVKGXc%2FCeIhoGqv4hrD4amq4h8ejj9PwAJkToXxLZI%2FSNQDcABFsrPGagKMpIn7wOBBYKHguOt5gJmG0D305eehmXheosDu4GmhPPpDe3Lks4aWjwswbN2rD2KqqGKOrEtTrXIomc%2By30F37E2rH8jwo7zeATjY%2B27qbgu%2FlGkHg0SwZ1GHs%2Fxic0xRMilxDRCd%2BSLYuyQhqBO%2B6lKXA%2BZb8N1V5GHWLkC1rpNEKPgfXwU6lWaXJ6JfFKIshPsJYEXRbTtIDUqI5sd8o8Y68MlYf1OlsOKmz24%2FZRKm%2Bu2JpVyWpw%3D%3D"
}

swift 代码示例:

import Alamofire

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

func loginByAlipay() {
    
    // 获取 authInfo
    AF.request(GetAuthInfoUrl).responseString { response in
        let resp = convertToDictionary(text: response.value!)!
        
        // Authing 业务状态码, 200 表示成功
        let code = resp["code"]! as! Int
        let message = resp["message"]! as! String
        if code == 200 {
            let authInfo = resp["data"]! as! String
            debugPrint("authInfo: \(authInfo)")
            
            // 打开支付宝
            AlipaySDK().auth_V2(withInfo: authInfo, fromScheme: "authing-alipay", callback: { resp in
                debugPrint(resp)
            })
        } else {
            debugPrint("Message: ", message)
        }
    }
}

# 打开支付宝登录

Swift 示例代码:

// 打开支付宝
AlipaySDK().auth_V2(withInfo: authInfo, fromScheme: "authing-alipay", callback: { resp in
    debugPrint(resp)
})

这里的 fromSchema 需要和设置的 URL Types 中的 URL Schema 一致:如下图所示:

# 接收支付宝回调数据

你可以在以下方法中获取到支付宝回调数据(详情见此 Demo (opens new window)):

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

Swift 示例代码:

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 回调
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" {
                // 进行接下来的逻辑
            }
        })
    default:
        debugPrint("???")
    }
}

# 换取用户信息

在上一步获取到 auth_code 可通过下面的 API 换取用户信息:

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

用户池 ID

Query Parameters
auth_code
REQUIRED
string

上一步获取到的 auth_code 。

app_id
OPTIONAL
string

应用 ID,选填。如果传了应用 ID,获取的用户信息中的 token 将是使用该应用签发的 id_token;如果不传,用户信息中的 token 将是 Authing 自己签发的 token。推荐调用此接口时传 app_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":"怀化市","gender":"m","isCertified":"T","isStudentCertified":"F","nickName":"Bob","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 代码示例:

let url = "https://core.authing.cn/connection/social/alipay/\(UserPoolId)/callback?auth_code=\(auth_code)"
AF.request(url).responseString { response in
    
    // 将 response.value 转化成字符串,示例如下:
    // ["code": "200", "message": "获取用户信息成功", data: "" ]
    let resp = convertToDictionary(text: response.value!)!
    let data = resp["data"] as! [String: Any]
    debugPrint("Data: \(data)")
}

# 完成接入

恭喜你,此时已经接入了支付宝移动应用登录。获取到用户信息之后,你可以得到登录凭证 token,你可以在后续的 API 请求中携带上此 token, 然后在后端接口中根据此 token 区分不同用户,详情请见验证 token

我们还提供了 React Native SDK,可以让你在 React Native 快速接入支付宝登录:

SDK for React Native