2016-04-04 44 views
2

PayPal üzerinden programlı bir şekilde ödeme yapmaya çalışıyorum ama çalışmıyor. Lütfen öğüt verin, teşekkürler.Programlı olarak PayPal ile ödeme yapın Hedef C

Kodum aşağıda ve aşağıda PayPal'ın cURL örneğidir. Onların dokümanlardan

-(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'ın cURL örnek:

Alım Tepki:

<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; 
} } 

Birisi söyle LÜTFEN Burada

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 deyimi yukarıda benim aracılığıyla PayPal benim yanıttır ödeme neden geçmiyor? Hata alamıyorum (ya da yanıtı yazdırmaz), jetonun iyi olduğunu biliyorum çünkü uygulamayı kullandığımda PayPal'a giriş yapmam gerekiyor ve bunu anlayamıyorum. Teşekkürler! Bunun yerine NSURlResponse Açıklama baskı

C

cevap

2

, size daha iyi bir fikir vermek için konsola JSON verilerini yazdırmak gerekir. Bu gibi görünmek için kodunuzu değiştirin: Bunu yaptıktan sonra, yanlış neler olup bittiğini çok daha iyi bir fikir olmalıdır

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]; 
    } 
}]; 

.

Güncelleme:

Ben neler olduğunu şimdi daha görüyoruz. İsteğiniz gerçekten hatalı biçimlendirilmiş: Gönderiniz ve posta verileriniz yanlış; yerine json (bir url üzerinden göndermek istiyorum gibi) (aşağıda bu satırları)

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

yerine bu olanlar iki satır yerine bir dize değeri gönderiyoruz:

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

Teşekkür @jrobe - Soruyu yayınlamadan önce bunu aslen yapmalıydım. JSON isteğinde bir sorun olduğunu düşündüğüm gibi: –

+0

Satış Cevabı: { "debug_id" = fbcc3a0134a8; "information_link" = "https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST"; message = "JSON talebi iyi oluşturulmadı."; name = "MALFORMED_REQUEST"; } –

+0

Arkadaşım, sen bir azizsin. Tekrar teşekkürler. @jrobe –