PayPal API:如何获取销售ID和通过PayPal进行的退款? [英] PayPal API: How to get Sale ID and refund payment made via PayPal?

查看:59
本文介绍了PayPal API:如何获取销售ID和通过PayPal进行的退款?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在PHP中使用PayPal API通过信用卡或通过PayPal本身创建交易.此外,我需要能够退还这些交易.我正在使用的代码(大部分直接来自PayPal API示例)对于信用卡交易来说可以正常工作,但是对于PayPal交易却无法完成.具体来说,我正在尝试深入查看付款"对象并提取该销售"的ID.通过信用卡支付的支付对象包含一个RelatedResources对象,该对象又包含具有ID的Sale对象,但是通过PayPal支付的Payment对象似乎并不包含这些对象.因此,我的问题是,如何从通过PayPal进行的付款中检索销售ID?

I'm using the PayPal API in PHP to create transactions, both with a credit card and via PayPal itself. Additionally, I need to be able to refund these transactions. The code I'm using, which is mostly straight from the PayPal API sample, works fine for credit card transactions, but it fails for PayPal transactions. Specifically, I'm attempting to drill down through the Payment object and pull out the ID of that Sale. Payment objects made via credit cards contain a RelatedResources object, which in turn contains the Sale object, with the ID, but Payment objects made via PayPal don't seem to contain them. So, my question is, how can I retrieve the Sale ID from a payment made via PayPal?

这是我用存储的信用卡付款的方式:

Here's how I create a payment with a stored credit card:

    $creditCardToken = new CreditCardToken();
$creditCardToken->setCreditCardId('CARD-2WG5320481993380UKI5FSFI');

// ### FundingInstrument
// A resource representing a Payer's funding instrument.
// For stored credit card payments, set the CreditCardToken
// field on this object.
$fi = new FundingInstrument();
$fi->setCreditCardToken($creditCardToken);

// ### Payer
// A resource representing a Payer that funds a payment
// For stored credit card payments, set payment method
// to 'credit_card'.
$payer = new Payer();
$payer->setPaymentMethod("credit_card")
    ->setFundingInstruments(array($fi));

// ### Amount
// Lets you specify a payment amount.
// You can also specify additional details
// such as shipping, tax.
$amount = new Amount();
$amount->setCurrency("USD")
    ->setTotal('1.00');

// ### Transaction
// A transaction defines the contract of a
// payment - what is the payment for and who
// is fulfilling it. 
$transaction = new Transaction();
$transaction->setAmount($amount)
    ->setDescription("Payment description");

// ### Payment
// A Payment Resource; create one using
// the above types and intent set to 'sale'
$payment = new Payment();
$payment->setIntent("sale")
    ->setPayer($payer)
    ->setTransactions(array($transaction));

// ###Create Payment
// Create a payment by calling the 'create' method
// passing it a valid apiContext.
// (See bootstrap.php for more on `ApiContext`)
// The return object contains the state.
try {
    $payment->create($apiContext);
} catch (PayPal\Exception\PPConnectionException $ex) {
    error_log($ex->getMessage());
    error_log(print_r($ex->getData(), true));
}

相比之下,这是我进行PayPal付款的方式.这是一个两步过程.首先,用户被定向到PayPal的网站,然后,当他们返回我的网站时,付款已被处理.

By contrast, here's how I make a PayPal payment. It's a 2-step process. First the user's directed to PayPal's site, and then, when they return to my site, the payment's processed.

第1部分:

$payer = new Payer();
$payer->setPaymentMethod("paypal");

$amount = new Amount();
$amount->setCurrency("USD")
    ->setTotal($userInfo['amount']);

$transaction = new Transaction();
$transaction->setAmount($amount)
    ->setDescription("Payment description");

// ### Redirect urls
// Set the urls that the buyer must be redirected to after 
// payment approval/ cancellation.
$baseUrl = 'http://example.com';
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl("$baseUrl/?success=true")
    ->setCancelUrl("$baseUrl/?success=false");

$payment = new Payment();
$payment->setIntent("sale")
    ->setPayer($payer)
    ->setRedirectUrls($redirectUrls)
    ->setTransactions(array($transaction));

try {
    $payment->create($apiContext);
} catch (PayPal\Exception\PPConnectionException $ex) {
    error_log($ex->getMessage());
    error_log(print_r($ex->getData(), true));
    return;
}

// ### Get redirect url
// The API response provides the url that you must redirect
// the buyer to. Retrieve the url from the $payment->getLinks()
// method
foreach($payment->getLinks() as $link) {
    if($link->getRel() == 'approval_url') {
        $redirectUrl = $link->getHref();
        break;
    }
}

// ### Redirect buyer to PayPal website
// Save payment id so that you can 'complete' the payment
// once the buyer approves the payment and is redirected
// bacl to your website.
//
// It is not really a great idea to store the payment id
// in the session. In a real world app, you may want to 
// store the payment id in a database.
$_SESSION['paymentId'] = $payment->getId();

if(isset($redirectUrl)) {
    $response->redirectUrl = $redirectUrl;
}
return $response;

这是第2部分,当用户通过成功"消息重定向到我的网站时:

And here's part 2, when the user's redirected to my site with a 'success' message:

$payment = Payment::get($lineitem->paypal_payment_ID, $apiContext);

// PaymentExecution object includes information necessary 
// to execute a PayPal account payment. 
// The payer_id is added to the request query parameters
// when the user is redirected from paypal back to your site
$execution = new PaymentExecution();
$execution->setPayer_id($_GET['PayerID']);

//Execute the payment
// (See bootstrap.php for more on `ApiContext`)
$payment->execute($execution, $apiContext);

这是我如何退款交易. API中的示例未讨论如何检索销售ID,因此我深入研究了这些对象.通过PayPal进行的Payments没有RelatedResources对象,因此失败:

And here's how I refund a transaction. The Sample in the API doesn't discuss how to retrieve a Sale ID, so I drill down through the objects. The Payments made via PayPal don't have a RelatedResources object, so it fails:

    try {
    $payment = Payment::get('PAY-8TB50937RV8840649KI6N33Y', $apiContext);
    $transactions = $payment->getTransactions();
    $resources = $transactions[0]->getRelatedResources();//This DOESN'T work for PayPal transactions.

    $sale = $resources[0]->getSale();
    $saleID = $sale->getId();

    // ### Refund amount
    // Includes both the refunded amount (to Payer) 
    // and refunded fee (to Payee). Use the $amt->details
    // field to mention fees refund details.
    $amt = new Amount();
    $amt->setCurrency('USD')
        ->setTotal($lineitem->cost);

    // ### Refund object
    $refund = new Refund();
    $refund->setAmount($amt);

    // ###Sale
    // A sale transaction.
    // Create a Sale object with the
    // given sale transaction id.
    $sale = new Sale();
    $sale->setId($saleID);
    try {   
        // Refund the sale
        // (See bootstrap.php for more on `ApiContext`)
        $sale->refund($refund, $apiContext);
    } catch (PayPal\Exception\PPConnectionException $ex) {
        error_log($ex->getMessage());
        error_log(print_r($ex->getData(), true));
        return;
    }
} catch (PayPal\Exception\PPConnectionException $ex) {
    error_log($ex->getMessage());
    error_log(print_r($ex->getData(), true));
    return;
}

关于如何获取销售ID的任何想法?谢谢!

Any thoughts on how to retrieve the Sale ID? Thanks!

推荐答案

我已经成功退还了一笔交易,但没有找到简单的方法.因此,我以另一种方式做到了.请尝试以下代码:

I have successfully refunded a transaction and did not find a easy way. So, I did it the other way. Please try the following code:

$apiContext = new ApiContext(new OAuthTokenCredential(
            "<CLIENT_ID>", "<CLIENT_SECRET>")
    );
    $payments = Payment::get("PAY-44674747470TKNYKRLI", $apiContext);
    $payments->getTransactions();
    $obj = $payments->toJSON();//I wanted to look into the object
    $paypal_obj = json_decode($obj);//I wanted to look into the object
    $transaction_id = $paypal_obj->transactions[0]->related_resources[0]->sale->id;
    $this->refund($transaction_id);//Call your custom refund method

干杯!

这篇关于PayPal API:如何获取销售ID和通过PayPal进行的退款?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆