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 退款? 的相关文章

  • 对具有混合类型值的数组进行数字排序

    我有一个像这样的混合数组 fruits array lemon Lemon 20 banana apple 121 40 50 然后申请sort 其功能如下 sort fruits SORT NUMERIC foreach fruits a
  • 使用 PHP 删除文件 onclick [关闭]

    很难说出这里问的是什么 这个问题是含糊的 模糊的 不完整的 过于宽泛的或修辞性的 无法以目前的形式得到合理的回答 如需帮助澄清此问题以便重新打开 访问帮助中心 help reopen questions 我想在用户单击删除链接时删除文件 但
  • 如何将 php curl 中的 cookie 获取到变量中

    因此 其他公司的一些人认为 如果不使用soap xml rpc rest 或任何其他合理的通信协议 而是将所有响应作为cookie 嵌入标头中 那就太棒了 我需要从这个卷曲响应中将这些 cookie 作为数组取出 如果我不得不为此浪费大量的
  • SQL:在行中保留计数或从数据库中选择计数

    示例 我有 2 张桌子 类别 Posts 在这样的类别中保留帖子编号是一个好方法吗 类别 id title posts 1 golf 50 2 soccer 90 posts id title category id 1 news 1 1
  • 使用 JavaScript 在 HTML 表中动态添加行并通过提交按钮获取每个文本框的文本框值

    我有一个可以动态添加行的表 当我提交保存按钮时 我想将每行中的数据获取到 php 数组 请有人帮我解决这个问题 我是java脚本的新手 对此知之甚少 谢谢你
  • 从前端更改记录顺序

    我在编写下一个功能时遇到问题 我希望用户能够重新排列记录并更改 display order 值 我使用 Jquery UI 的可拖放功能来促进这一点 我可以看到如何简单地交换 display order 值 但我想为一条记录设置一个显示顺序
  • 我可以更改浏览器发送的 HTTP 请求的标头吗?

    我正在研究一种宁静的设计 并且想使用 HTTP 方法 POST GET 和 HTTP 标头尽可能多 我已经发现 HTTP 方法PUT and DELETE浏览器不支持 现在我希望获得同一资源的不同表示形式 并希望通过更改Accept请求的标
  • PHP表单提交后如何显示成功消息?

    这是代码 我想要这样 表单提交 gt page2 php gt 重定向 gt page1 php 这是消息 弹出窗口或其他内容 page1 php
  • 创建一个基于简单文本文件的搜索引擎

    我需要尽快创建一个基于简单文本文件的搜索引擎 使用 PHP 基本上它必须读取目录中的文件 删除停止词和无用词 为每个剩余的有用词及其在每个文档中出现的次数建立索引 我猜这个的伪代码是 for each file in directory r
  • ResourceBundle 返回 NULL,没有引发任何错误

    对于国际化数据 与 ResourceBundle来自 PHP 的 intl 扩展的类 我运行了扩展 PHP 5 3 4 Windows 并使用以下命令创建了一个 dat 文件ICU 数据库定制器 http apps icu project
  • 类别树的路由

    我正在使用Tree http www gediminasm org article tree nestedset behavior extension for doctrine 2类别树的学说扩展并希望有如下路线 cat subcat1 s
  • Joomla getUser() 不显示更新的用户数据

    下面的代码允许我在用户的 Joomla 个人资料的个人资料页面中显示用户名 鉴于我已经覆盖了模板以获得我想要的外观和感觉 user JFactory getUser if user gt guest echo You are logged
  • 将 Javascript 变量转换为 PHP 变量

    我想使用由 videoel getCurrentTime 函数返回给我的 javascript 变量 并将其转换为 php 变量 以便我能够将其添加到我的 SQL 插入查询中 例如 INSERT INTO tblData VALUES ph
  • 如何从表中选择所有偶数 id?

    我想从 MySQL 数据库的表中选择所有甚至帖子 ID 然后显示它们 我还想获取所有带有奇怪 id 的帖子并将它们显示在其他地方 我想使用 PHP 来完成此操作 因为这是我使用的服务器端语言 或者 我是否必须选择所有帖子 然后使用 Java
  • 带有列标题的php数组到csv的转换

    我想将数组转换为 csv 我能够将关联数组转换为 csv 但无法获取标题 我想要动态地将数字类型日期作为标题 下面是我转换的数组 Array 0 gt Array NUMBER gt 67 TYPE gt Other DATE gt 3 3
  • 提交前验证表单(比检查空字段更复杂)

    我有一个包含时间输入的表单 具体来说 开放时间和结束时间 当按下提交按钮时 它会转到一个 php 页面 其中这些输入将添加到数据库中 在允许提交表单之前我想检查一些事情 例如 我想确保开始时间早于 小于 结束时间 这是表格 Opens
  • 使用 jquery 和 php 测试表单输入是否为 1 或 2 位整数

    我有一个表单 其中有五个字段全部设置为 maxlength 2 基本上 我希望唯一可以输入的值是一位或两位整数 因为在将值存储在数据库中之前对这些字段执行计算 是否有任何 jquery 不允许用户输入不是整数的值 另外 用 jquery 和
  • 未找到 mysqli 类

    我用过mysqli连接到我的应用程序中的数据库 几天前一直运行良好 突然出现以下错误 致命错误 找不到类 mysqli 我用来连接数据库的行是 link new mysqli localhost uname password scripts
  • Laravel 5 Socialite - cURL 错误 77:设置证书验证位置时出错

    我正在 Laravel 5 中使用社交名流来设置 facebook 登录 我仔细按照说明进行操作 直到出现以下错误 cURL error 60 SSL certificate problem unable to get local issu
  • 使用 ActiveRecord 和 Yii2 记录实际的 SQL 查询?

    我正在这样做 students Student find gt all return this gt render process array students gt students 然后在视图中 foreach students as

随机推荐