如何获取 Paypal 交易 ID 并在 ruby​​ on rails 中退款

Posted

技术标签:

【中文标题】如何获取 Paypal 交易 ID 并在 ruby​​ on rails 中退款【英文标题】:How to get Paypal Transaction id and make refunds in ruby on rails 【发布时间】:2019-08-22 05:11:37 【问题描述】:

我正在使用:Ruby 2.4、Rails 5.2.1、沙盒模式下的 Paypal:

 gem 'paypal-sdk-rest', '~> 1.7.3'

Paypal 支付方式:

  items << 
      :name => title,
      :price => unit_price,
      :currency => "USD",
      :quantity => quantity,
      :description => short_description
  

amount = 
    :total => subtotal,
    :currency => "USD",
    :details => "subtotal": subtotal, "shipping": "0", "tax": "0"


invoice_number = "invoice-#rand(1111..9999)"
@payment = Payment.new(
                           :intent => "sale",
                           :payer => 
                               :payment_method => "paypal",
                           :redirect_urls => 
                               :return_url => "http://localhost:3000/payments/#order.id/make_payment",
                               :cancel_url => "http://localhost:3000/",
                           :transactions => [
                                                 :item_list => 
                                                     :items => items,

                                                 ,

                                                 :amount => amount,
                                                 :description => "Transaction description.",
                                                 :invoice_number => invoice_number
                                             ]
                       )

付款创建为:

 if @payment.create
      render json: success: true, paymentID: @payment.id
    else
      @payment.error # Error Hash
      render json: success: false
    end

付款捕获:

 if payment.execute(payer_id: params[:payerID])
      render json: msg: 'payment_completed', result: 'completed', 
    else
      render json: msg: payment.error, result: 'failed'
    end

【问题讨论】:

【参考方案1】:

退款: 第一步:从paypal中找到paypal支付对象:

payment = PayPal::SDK::REST::Payment.find(order.paypal_id)

第 2 步:找到该付款的交易:

transaction = payment.transactions.last

Step2:查找与该付款相关的资源:

related_resource = transaction.related_resources.last

第3步:从paypal sdk中找到销售对象:

sale = related_resource.sale
sale = Sale.find(sale.id)

现在继续退款:

refund = sale.refund(
                         :amount => 
                             :total => "1.31",
                             :currency => "USD"
                         
                     )
if refund.success?
  logger.info "Refund[#refund.id] Success"
  render json:  result: 'success '
else
  logger.error refund.error.inspect
  render json:  result: 'fail'
end

【讨论】:

以上是关于如何获取 Paypal 交易 ID 并在 ruby​​ on rails 中退款的主要内容,如果未能解决你的问题,请参考以下文章

如何在 WooCommerce 中获取 Paypal 交易 ID?

如何在 paypal node.js 中获取交易 ID 反应?

如何使用 PayPal Express Checkout 集成(客户端 REST)获取交易 ID

使用 paypal-ruby-sdk 创建 Paypal 定期订阅计划时如何让卖家支付交易费用

如何使用 paypal android sdk 中的 payment_id 在 paypal 中获取完整的交易详情

在 iOS PayPal SDK 中使用信用卡选项时如何获取交易 ID