Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 以编程方式发送PayPal支付目标C_Objective C_Rest_Curl_Paypal_Nsurlconnection - Fatal编程技术网

Objective c 以编程方式发送PayPal支付目标C

Objective c 以编程方式发送PayPal支付目标C,objective-c,rest,curl,paypal,nsurlconnection,Objective C,Rest,Curl,Paypal,Nsurlconnection,我试图通过PayPal以编程方式发送付款,但它不起作用。请告知,谢谢 下面是我的代码,下面是PayPal的cURL示例 -(void)createPayment { NSString *shortDescription = @"test description"; NSDecimalNumber *paymentDecimal = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%.02f

我试图通过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."
      }
    ]
  }'
以下是我通过上述NSLog声明从PayPal得到的回复:

采购响应:

<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;
} }
{URL:https://api.sandbox.paypal.com/v1/payments/payment }{状态代码:400,标题{
“相关ID”=c0b729159d0c7;
连接=“关闭,关闭”;
“内容语言”=“en_US”;
“内容长度”=200;
“内容类型”=“应用程序/json”;
日期=“2016年4月4日星期一19:48:20 GMT”;
“代理服务器信息”=“主机=slcsbplatformapiserv3001.slc.paypal.com;线程ID=675”;
“Paypal调试Id”=“c0b729159d0c7,c0b729159d0c7”;
服务器=Apache;
“设置Cookie”=“X-PP-SILOVER=name%3DSANDBOX3.API.1%26silo_版本%3D1880%26app%3Dplatformapiserv%26时间%3D80020055;域=.paypal.com;路径=/;安全;HttpOnly,X-PP-SILOVER=;过期=周四,1970年1月1日00:00:01 GMT”;
变更=授权;
} }
有人请告诉我为什么付款没有通过。我没有收到错误(或者它不会打印响应),我知道令牌是好的,因为我每次使用应用程序时都必须登录到PayPal,我无法找到它。谢谢


C

您应该将JSON数据打印到console,而不是打印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];
    }
}];   
一旦你做到了这一点,你应该对出了什么问题有一个更好的了解

更新:

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

将这两行替换为:

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

谢谢@jrobe-在我发布问题之前,本来应该这样做的。正如我认为JSON请求有问题一样:购买响应:{“debug_id”=fbcc3a0134a8;“information_link”=“message=”请求JSON格式不正确。“name=”格式不正确的请求“}我的朋友,你是圣人。再次感谢@这不是问题,我的荣幸!
NSError *jsonError;
NSData *postData = [NSJSONSerialization dataWithJSONObject:dataDict options:0 error:&error];