PayPal SDK请求访问令牌返回代码401(未经授权)

时间:2017-10-15 19:05:25

标签: swift curl oauth-2.0 paypal-sandbox

我正在尝试使用Sandbox环境中的授权代码从PayPal的服务器接收访问令牌。我认为问题在于将curl转换为Alamofire请求,但我不确定。任何帮助表示赞赏。

以下是我向服务器发送授权的代码:

func sendAuthorizationToServer(authorization: [AnyHashable: Any]) {

    let jsonAuth = JSON(authorization)

    let headers = [
        "content-type": "application/x-www-form-urlencoded; charset=utf-8",
    ]
    let parameters = [
        "client_id": Constants.payPalSandboxID,
        "client_secret": Constants.payPalSandboxSecret,
        "grant_type": "authorization_code",
        "redirect_uri": "urn:ietf:wg:oauth:2.0:oob",
        "code": jsonAuth["response"]["code"].stringValue
    ]

    Alamofire.request("https://api.sandbox.paypal.com/v1/oauth2/token", method: .post, parameters: parameters, encoding: URLEncoding.default, headers: headers).responseJSON { response in
        print(response.request)
        print(response.response)
        print(response.data)
        print(response.error)
        }
}

我已检查jsonAuth["response"]["code"].stringValue并返回正确的授权码。 我的疑问是,它应该是.post请求还是.get请求,以及参数中的凭据是否具有正确的顺序/结构。

以下是最后一个打印语句的输出:

enter image description here 以下是用于交换访问令牌的授权代码的S​​DK链接: https://github.com/paypal/PayPal-iOS-SDK/blob/master/docs/future_payments_server.md#exchange-authorization-code-for-refresh--access-tokens

1 个答案:

答案 0 :(得分:1)

import SwiftyJSON
import Alamofire

// ... ...
// ... ...
// ... ...


let credentialData = "\(paypalClientId):\(paypalSecret)".data(using: String.Encoding.utf8)!
let base64Credentials = credentialData.base64EncodedString(options: [])
let headers = [
    "Authorization": "Basic \(base64Credentials)",
]
let params:[String: Any] = [
    "grant_type": "client_credentials",
]
Alamofire.request(tokenAPI, method: .post, parameters: params, encoding: URLEncoding.default, headers: headers)
    .validate()
    .responseJSON { (response) in
        debugPrint(response)
        switch response.result {
        case .success(let data):
             let json = JSON(data)
             let accessToken = json["access_token"].stringValue
             break;
        case .failure(let error):
             debugPrint(error)
             debugPrint(response.data)
        }
    }
  

请注意,编码必须是URLEncoding.default而不是JSONEncoding.default