PayPal API:如何获取销售 ID 并通过 PayPal 退款?

2024-04-10

我使用 PHP 中的 PayPal API 来创建交易,既使用信用卡又通过 PayPal 本身。此外,我需要能够退还这些交易。我使用的代码大部分直接来自 PayPal API 示例,对于信用卡交易工作正常,但对于 PayPal 交易则失败。具体来说,我试图深入了解 Payment 对象并提取该销售的 ID。通过信用卡进行的付款对象包含相关资源对象,该对象又包含带有 ID 的销售对象,但通过 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 付款。这是一个 2 步过程。首先,用户被定向到 PayPal 的网站,然后,当他们返回我的网站时,付款就会得到处理。

Part 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 进行的付款没有相关资源对象,因此失败:

    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 有什么想法吗?谢谢!


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

$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

Cheers!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PayPal API:如何获取销售 ID 并通过 PayPal 退款? 的相关文章

  • PHPunit - 错误

    当 PHPunit 框架不希望发生的错误发生时 测试会停止 PHP 会抛出错误 但 PHPunit 不会记录这是一个错误 我如何确保 PHPunit 将其记录为错误 免责声明 我是 PHPUnit 的新手 我也试图弄清楚 发生错误时会发生什
  • Magento 中的子域 htaccess 问题

    public html www domain com public html subdomain subdomain domain com public html htaccess public html subdomain htacces
  • MYSQL 的 Google OAuth 2.0 用户 ID 数据类型

    我正在实施 Google OAuth 2 0 并注意到 Google OAuth 返回的唯一用户 ID 是21位数字长的 我想大整数 20 足以满足这种需求 但我现在看到 Google OAuth 返回的用户 ID 的长度感到困惑 关于我应
  • 使用 md5 加密的 PHP 和 Mysql 查询出现问题

    我使用普通的 php mysql 插入查询并使用 md5 加密密码 这是插入查询 sql mysql query INSERT INTO user username password role approved values usernam
  • 私人聊天系统MYSQL查询显示发送者/接收者的最后一条消息

    在这里我延伸一下我之前的问题 私人聊天系统MYSQL查询ORDERBY和GROUPBY https stackoverflow com questions 10929366 private chat system mysql query o
  • 在会话 cookie 中存储大量数据会产生什么影响?

    谁能解释一下在会话中存储大量数据的缺点或给我指出一些阅读材料 我也很感兴趣在会话中存储数据和从数据文件读取数据之间是否有任何区别 如果您在会话中存储大量数据 则输入 输出性能会下降 因为会有大量读取 写入 默认情况下 PHP 中的会话存储在
  • PHP解析xml文件错误

    我正在尝试使用 simpleXML 来获取数据http rates fxcm com RatesXML http rates fxcm com RatesXML Using simplexml load file 我有时会遇到错误 因为这个
  • 关于加拿大短信网关提供商的建议[关闭]

    Closed 这个问题是无关 help closed questions 目前不接受答案 我很好奇 如果我能够接受传入的短信到某个号码 然后将其传递给 PHP 中的服务器端应用程序 会带来多少麻烦 金钱 我最终会通过电子邮件地址发回短信 有
  • 运行 Composer 返回:“无法打开输入文件:composer.phar”

    我是 symfony2 和阅读新手symblog http tutorial symblog co uk tutorial parts 在第三章中 在尝试使用数据装置时 我尝试了以下命令 php composer phar update 但
  • 使用 php 更改白天和黑夜的背景?

    我正在制作一个 tumblr 页面 我的 html 页面有两种不同的背景 我希望白天背景从早上 7 点到晚上 8 点显示 夜间背景从晚上 8 点到早上 7 点显示 我决定用 php 来做这件事 但对于 php 来说我是个新手 我的朋友给我发
  • 将函数中的会话变量传递给 codeigniter 中的助手

    这就是我正在尝试做的事情 这是控制器中的功能 public function get started if test login this gt session gt all userdata this gt load gt view te
  • Web 服务应该是事务性的吗?

    我正在研究为应用程序编写网络服务 在此应用程序中 我们在事务中执行所有操作 因为 工作单元 通常不是单个实体 而是跨越多个表的多个实体 在某些情况下 我们想要 全有或全无 而交易是非常有意义的 然而 我不太确定如何在网络服务中执行此操作 也
  • 如何以编程方式获取 WooCommerce 中的所有产品?

    我想获取 WooCommerce 中的所有产品数据 产品 sku 名称 价格 库存数量 可用性等 我可以使用 wp query 来做到这一点吗 这样你就可以通过 wp query 获取所有产品 global wpdb all product
  • 使用 PHP 的 Google Glass GDK 身份验证

    我正在尝试点击此链接来验证 GDK 中的用户 https developers google com glass develop gdk authentication https developers google com glass de
  • AWS S3 上传的图像已损坏

    我正在 AWS ec2 ubuntu 机器上工作 我的代码在 cakephp 中 当我尝试将任何图像上传到 AWS S3 时 它都会损坏 虽然它在核心 php 代码中运行良好 这是我的控制器代码 if this gt User gt sav
  • PHP - hash_pbkdf2 函数

    我正在尝试使用此 php 函数执行一个函数来哈希密码 http be php net manual en function hash pbkdf2 php http be php net manual en function hash pb
  • PHP7构造函数类名

    我有一个 Laravel 4 2 应用程序 它可以与 PHP5 一起使用 没有任何问题 由于我安装了一个运行 PHP7 的新 vagrant box 一旦我运行一个模型 其中函数名称与类名称 关系函数 相同 就会出现错误 如下所示
  • 使用PHP套接字发送和接收数据

    我正在尝试通过 PHP 套接字发送和接收数据 一切正常 但是当我尝试发送数据时 PHP 不发送任何内容 Wireshark 告诉我发送的数据长度为 0 我正在使用这段代码
  • 在 Woocommerce 购物车中设置最小小计金额

    我正在尝试将最低订单金额设置为 25 美元 到目前为止 我找到了这段代码 如果未达到最低限度 它似乎可以阻止结账 但它使用的小计包含税费 我需要在总计中排除税费 add action woocommerce checkout process
  • 将 MySQL 结果作为 PHP 数组

    mysql 表 config name config value allow autologin 1 allow md5 0 当前的 php 代码 sth mysql query SELECT rows array while r mysq

随机推荐