如何在 iOS 中通过 API 调用获取PayPal刷新令牌



我已经成功地实现了PayPal iOS SDK的配置文件共享选项。一旦用户登录到应用程序中的帐户PayPal我就会获得正确的代码。我尝试使用 curl 命令获取用户信息,我成功了。

现在我想通过 api 调用实现第 2 步和第 3 步。

以下是我为从服务器获取刷新令牌而实现PayPal。

 func getTheRefreshToken(authToken:NSString) {
        print("Token (authToken)")
        let urlPath: String = "https://api.sandbox.paypal.com/v1/identity/openidconnect/tokenservice"
        let url: NSURL = NSURL(string: urlPath)!
        let request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
        let basicAuthCredentials: String = "AXvaZH_Bs9**CLIENTID**0RbhP0G8Miw-y:ED_xgio**SECRET**YFwMOWLfcVGs"
        let plainData = (basicAuthCredentials as NSString).dataUsingEncoding(NSUTF8StringEncoding)
        let base64String = "Basic (plainData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)))"
        request.HTTPMethod = "POST"
        let params = ["grant_type":"authorization_code","redirect_uri":"urn:ietf:wg:oauth:2.0:oob", "authorization_code":authToken as String] as Dictionary<String, String>
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.addValue(base64String, forHTTPHeaderField: "Authorization")
        request.timeoutInterval = 60
        request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])
        request.HTTPShouldHandleCookies=false
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response: NSURLResponse?, data: NSData?, error: NSError?) in
            let refreshResponse = NSString(data: data!, encoding: NSISOLatin1StringEncoding)
            print("Response (refreshResponse!)")
        }
    }

每次我收到错误时,grant_type为空。

错误

Response {"error_description":"Grant type is null","error":"invalid_grant","correlation_id":"e5d4cc9c47d21","information_link":"https://developer.paypal.com/docs/api/#errors"}

这里有几件事...1. 出于安全原因,切勿将客户端密钥存储在客户端。2.您可以使用此处概述的curl命令尝试从服务器调用并让我知道结果吗?

我从内部日志中唯一能看到的是与错误相同或grant_type丢失。 使用响应中的授权代码从服务器运行测试,应该让我们知道它是否只是代码中的某些内容变得混乱。

使用此代码,可以在PayPal上刷新或获取新的访问令牌。

NSString *clientID = @"YOUR_CLIENT_ID";
NSString *secret = @"YOUR_SECRET";
NSString *authString = [NSString stringWithFormat:@"%@:%@", clientID, secret];
NSData * authData = [authString dataUsingEncoding:NSUTF8StringEncoding];
NSString *credentials = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedStringWithOptions:0]];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
[configuration setHTTPAdditionalHeaders:@{ @"Accept": @"application/json", @"Accept-Language": @"en_US", @"Content-Type": @"application/x-www-form-urlencoded", @"Authorization": credentials }];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://api.sandbox.paypal.com/v1/oauth2/token"]];
request.HTTPMethod = @"POST";
NSString *dataString = @"grant_type=client_credentials";
NSData *theData = [dataString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromData:theData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (!error) {
        NSLog(@"data = %@", [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]);
    }
}];    
[task resume];

这将给出此响应。

 data = {
 "access_token" = "A101.S6WF1CZIz9TcamYexl6k1mBsXhxEL1OWtotHq37UVHDrK7roty_4DweKXMhObfCP.7hNTzK62FqlDn3K9bqCjUIFmsVy";
    "app_id" = "APP-80W284485P519543T";
    "expires_in" = 32042;
    nonce = "2016-12-26T10:24:12Z8qEQBxdSGdAbNMg2ivVmUNTUJfyFuSL30OI_W9UCgGA";
    scope = "https://uri.paypal.com/services/subscriptions https://api.paypal.com/v1/payments/.* https://api.paypal.com/v1/vault/credit-card https://uri.paypal.com/services/applications/webhooks openid https://uri.paypal.com/payments/payouts https://api.paypal.com/v1/vault/credit-card/.*";
    "token_type" = Bearer;
    }

相关内容

  • 没有找到相关文章

最新更新