PayPal JS JDK+Rails 前後端串接應用

Andy Kuan's Blog
5 min readMay 5, 2024

--

PayPal

此篇以「全端工程師」角色模擬使用 JS+Ruby on Rails後端進行串接paypal,後端使用 paypal的gem來做搭配。

PayPal開發者頁面&官方文件:https://developer.paypal.com/

  • 申請paypal Sandbox測試帳號,以及申請兩個金鑰:client_id與client_secret。

PayPal裡:

  • Sandbox 測試
  • Live 正式

引入html button:

<script src="<https://www.paypal.com/sdk/js?client-id={client_id}&currency=USD>"></script>
<meta name="csrf-token" content="<%= form_authenticity_token %>">
<!-- paypal文件裡面有其他樣式可以自定義 -->
<div id="paypal-button-container"></div>

使用 Java Script JDK操作:

/* java script code */
paypal.Buttons({
createOrder: function(data, actions) {
// 這個函數設置支付信息
return actions.order.create({
purchase_units: [{
amount: {
value: 20.00
}
}]
});
},
onApprove: function(data, actions) {
// 這個函數調用 PayPal 交易的支付
return actions.order.capture().then(function(details) {
alert('Transaction completed by ' + details.payer.name.given_name + '!');
});
},
onCancel: function (data) {
// 可以在這裡添加用戶取消支付的處理邏輯
alert('Transaction cancelled!');
},
onError: function (err) {
// 可以在這裡處理錯誤
console.error('Error during the payment process!', err);
}
}).render('#paypal-button-container');

Rails Gem安裝:

gem 'paypal-sdk-rest'
gem 'paypal-checkout-sdk'
gem 'paypalhttp'

在config/initializers/裡面新增:

# initializers/uri_escape.rb
require 'uri'
module URI
def self.escape(str, unsafe = Regexp.new("[^#{PATTERN::UNRESERVED}]"))
URI::DEFAULT_PARSER.escape(str, unsafe)
end
end
# initializers/paypal_client.rb
require 'paypal-checkout-sdk'
module PayPalClient
class << self
def client
PayPal::PayPalHttpClient.new(environment)
end
def environment
client_id = "..."
client_secret = "..."
# 根据你的环境选择 Sandbox 或 Live
PayPal::SandboxEnvironment.new(client_id, client_secret)
end
end
end

設置Paypal支付回傳的action:

protect_from_forgery except: [:test_paypal_callback]
require 'paypal-checkout-sdk'
require 'cgi'
# 在javasctpt付款後會得到 paymentId 把它存下來,後端丟到以下去回call給paypal server
paypal_payment_id = params[:paymentId]
request = PayPalCheckoutSdk::Orders::OrdersGetRequest.new(paypal_payment_id)
begin
p "Success!"
response = PayPalClient.client.execute(request)
p @order_details = response.result
# 這裡可以寫當成功之後要做的事 or 後端程式邏輯(更新訂單資料表...等等)
# .....
render json: {
status: 200,
message: "Success!",
response: response,
details: @order_details
}
rescue PayPalHttp::HttpError => e
p "Error"
render json: { error: e.status_code, message: e.result }, status: :unprocessable_entity
end

以上基本使用 Java Script前端串接到Rails後端的PayPal金流基礎架構流程。後面如果有更新會繼續更新文章。

PayPal後台會收到的訂單記錄:Ex.

--

--