【问题标题】:PayPal API: How to get Sale ID and refund payment made via PayPal?PayPal API:如何通过 PayPal 获取销售 ID 和退款?
【发布时间】:2013-09-26 11:32:02
【问题描述】:

我在 PHP 中使用 PayPal API 来创建交易,包括信用卡和 PayPal 本身。此外,我需要能够退还这些交易。我使用的代码大部分直接来自 PayPal API 示例,适用于信用卡交易,但无法用于 PayPal 交易。具体来说,我正在尝试深入了解 Payment 对象并提取该销售的 ID。通过信用卡进行的付款对象包含一个 RelatedResources 对象,该对象又包含带有 ID 的 Sale 对象,但通过 PayPal 进行的付款对象似乎不包含它们。所以,我的问题是,如何从通过 PayPal 支付的款项中检索销售 ID?

以下是我使用存储的信用卡创建付款的方法:

    $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 的网站,然后,当他们返回我的网站时,付款就得到了处理。

第 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 部分,当用户使用“成功”消息重定向到我的网站时:

$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 进行的付款没有 RelatedResources 对象,因此失败:

    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 有任何想法吗?谢谢!

【问题讨论】:

  • 您确定付款('PAY-8TB50937RV8840649KI6N33Y')已经执行了吗?仅当付款达到“完成”状态时才会创建销售,并且仅在执行付款时才会发生。对于 PayPal 付款,在此之前付款处于“已创建”或“已批准”状态。
  • 有人在 PayPal 刚刚确认使用 PayPal 支付的款项可退还,因此无法退还。
  • 这里有一篇关于通过php api退款的文章。 kvcodes.com/2016/05/paypal-refund-transaction

标签: php rest paypal


【解决方案1】:

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

$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

干杯!

【讨论】:

  • $transaction_ref 是什么意思?是 $transaction_id 吗? @Jubayer Arefin
  • 是的,$transaction_id 实际上是一个唯一的销售 id。更新的答案。
【解决方案2】:

函数Payment::get() 不会返回所有必需的信息。 您需要将getTransactions()getRelatedResources() 函数应用于executePayment() 函数返回的对象。

.....
$payment = executePayment( $execution, $apiContext );
$transactions = $payment->getTransactions();
$resources = $transactions[0]->getRelatedResources();
.....

【讨论】:

  • 嗯,getRelatedResources 对我来说会导致一个未定义的索引错误,一定要喜欢这个 api :-) 错误是 Undefined index: related_resources in \paypal\paypal\sdk-core-php\lib\PayPal\Common \PPModel.php 第 14 行
猜你喜欢
  • 2016-12-01
  • 2019-11-24
  • 2016-10-14
  • 2015-09-21
  • 1970-01-01
  • 2014-04-03
  • 2018-08-25
  • 2015-04-24
  • 2016-09-05
相关资源
最近更新 更多