objective-c - 以编程方式发送 PayPal 付款 Objective C

标签 objective-c rest curl paypal nsurlconnection

我正在尝试通过 PayPal 以编程方式发送付款,但它不起作用。请指教,谢谢。

我的代码如下,下面是 PayPal 的 cURL 示例。

-(void)createPayment {
    NSString *shortDescription = @"test description";
    NSDecimalNumber *paymentDecimal = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%.02f", [Global sharedInstance].currentOrder.itemPrice]];
    NSString *sku = [NSString stringWithFormat:@"DBAR-%i", [Global sharedInstance].currentOrder.orderNumber];

    NSString *name = [NSString stringWithFormat:@"%@", [Global sharedInstance].currentOrder.boozeBrand];
    PayPalItem *item = [PayPalItem itemWithName:name withQuantity:[Global sharedInstance].currentOrder.itemQuantity withPrice:paymentDecimal withCurrency:@"USD" withSku:sku];
    float priceFloat = [item.price floatValue];
    float totalFloat = priceFloat * item.quantity;
    NSDecimalNumber *total = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%.02f", totalFloat]];

    PayPalPayment *payment = [[PayPalPayment alloc] init];
    payment.amount = total;
    payment.currencyCode = @"USD";
    payment.shortDescription = shortDescription;
    payment.items = nil;  
    payment.paymentDetails = nil; 

    if (!payment.processable) {NSLog(@"Payment not processable.");}

    NSString *token = [Global sharedInstance].accessToken;
    NSString *bearerToken = [NSString stringWithFormat:@"Bearer %@", token];

    NSDictionary *redirectDict = @{@"return_url":@"http://www.testurl.com",
                                   @"cancel_url":@"http://www.testurl.com"};
    NSDictionary *payerDict = @{@"payment_method":@"paypal"};

    NSMutableDictionary *amountMutableDict = [[NSMutableDictionary alloc] init];
    [amountMutableDict setObject:total forKey:@"total"];
    [amountMutableDict setObject:@"USD" forKey:@"currency"];
    NSDictionary *amountDict = [NSDictionary dictionaryWithDictionary:amountMutableDict];

    NSMutableDictionary *transactionsMutableDict = [[NSMutableDictionary alloc] init];
    [transactionsMutableDict setObject:amountDict forKey:@"amount"];
    [transactionsMutableDict setObject:shortDescription forKey:@"description"];
    NSDictionary *transactionsDict = [NSDictionary dictionaryWithDictionary:transactionsMutableDict];

    NSMutableArray *transactionsMutableArray = [[NSMutableArray alloc] init];
    [transactionsMutableArray addObject:transactionsDict];
    NSArray *transactionsArray = [NSArray arrayWithArray:transactionsMutableArray];

    NSMutableDictionary *dataMutableDict = [[NSMutableDictionary alloc] init];
    [dataMutableDict setObject:@"sale" forKey:@"intent"];
    [dataMutableDict setObject:redirectDict forKey:@"redirect_urls"];
    [dataMutableDict setObject:payerDict forKey:@"payer"];
    [dataMutableDict setObject:transactionsArray forKey:@"transactions"];
    NSDictionary *dataDict = [NSDictionary dictionaryWithDictionary:dataMutableDict];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"https://api.sandbox.paypal.com/v1/payments/payment"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:bearerToken forHTTPHeaderField:@"Authorization"];

    NSString *post = [NSString stringWithFormat:@"intent=sale&redirect_urls=%@&payer=%@", redirectDict, payerDict];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long [postData length]];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
    NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromData:postData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (!error) {
            NSLog(@"\nPurchase Response:\n\n%@", response.description);
        } else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Authorization Failed" message:@"Your payment did not go through." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [alert show];
        }
    }];    

    [task resume];

}

PayPal 文档中的 cURL 示例:

curl https://api.sandbox.paypal.com/v1/payments/payment \
  -v \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer accessToken' \
  -d '{
    "intent":"sale",
    "redirect_urls":{
      "return_url":"http://return_URL_here",
      "cancel_url":"http://cancel_URL_here"
    },
    "payer":{
      "payment_method":"paypal"
    },
    "transactions":[
      {
        "amount":{
          "total":"7.47",
          "currency":"USD"
        },
        "description":"This is the payment transaction description."
      }
    ]
  }'

以下是 PayPal 通过上述 NSLog 声明做出的回应:

购买响应:

<NSHTTPURLResponse: 0x1512732d0> { URL: https://api.sandbox.paypal.com/v1/payments/payment } { status code: 400, headers {
    "CORRELATION-ID" = c0b729159d0c7;
    Connection = "close, close";
    "Content-Language" = "en_US";
    "Content-Length" = 200;
    "Content-Type" = "application/json";
    Date = "Mon, 04 Apr 2016 19:48:20 GMT";
    "PROXY_SERVER_INFO" = "host=slcsbplatformapiserv3001.slc.paypal.com;threadId=675";
    "Paypal-Debug-Id" = "c0b729159d0c7, c0b729159d0c7";
    Server = Apache;
    "Set-Cookie" = "X-PP-SILOVER=name%3DSANDBOX3.API.1%26silo_version%3D1880%26app%3Dplatformapiserv%26TIME%3D80020055; domain=.paypal.com; path=/; Secure; HttpOnly, X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT";
    Vary = Authorization;
} }

有人请告诉我为什么付款没有通过。我没有收到错误(或者不会打印响应),我知道 token 很好,因为每次使用该应用程序时我都必须登录 PayPal,但我无法弄清楚。谢谢!

C

最佳答案

您应该将 JSON 数据打印到控制台,而不是打印 NSURlResponse 描述,以便您更好地了解。将您的代码修改为如下所示:

NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromData:postData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!error) {
     NSError* jsonError;
     NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
                                                 options:kNilOptions 
                                                   error:&jsonError];
     NSLog(@"\nPurchase Response:\n\n%@", json); //You will have to edit this to use the actual error object returned from the curl request.
} else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Authorization Failed" message:@"Your payment did not go through." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alert show];
    }
}];   

完成此操作后,您应该对出了什么问题有更好的了解。

更新:

我现在看到了更多正在发生的事情。您的请求确实格式错误:您的帖子和帖子数据值不正确;您正在发送一个字符串值(就像通过 url 发送一样)而不是 json(下面这些行)

NSString *post = [NSString stringWithFormat:@"intent=sale&redirect_urls=%@&payer=%@", redirectDict, payerDict];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

将这两行替换为:

NSError *jsonError;
NSData *postData = [NSJSONSerialization dataWithJSONObject:dataDict options:0 error:&error];

关于objective-c - 以编程方式发送 PayPal 付款 Objective C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36413690/

相关文章:

objective-c - "Current language: auto; currently objective-c"是什么意思?

Java从列表中获取特定值并添加到其他列表

c# - Windows 10 IoT - REST API 部署

java - Jersey :@Consumes 在未设置内容类型时无法正常工作

java - 请问如何将此 Curl 请求移植到 Android?

c# - 在 C# 中使用授权制作 HTTP Post

iphone - 为什么我无法在我的 iOS 应用程序中对 Facebook Chat 进行身份验证?

objective-c - 在 Objective-C 中定义接受一个 Block 并返回一个 Block 的 Block 的语法

iphone - 如何在 UItextView 中添加 placeHolder 文本?在 iPhone SDK 中

启用 AWS-IAM 授权后 CURL LAMBDA REST-API