跳至主要內容

x402 與 Rails API 的付款整合

更新於
2026年4月7日

閱讀時間 14 分鐘

概覽

傳統的 API 變現模式仰賴訂閱制與 API 金鑰,這對希望以簡單、按次付費方式使用服務的用戶而言,造成了使用障礙。x402支付協定透過在 HTTP 上擴充支付層來解決此問題,實現真正的「按請求付費」存取模式。

本指南將向您展示如何利用 Quicknode 的開源x402-railsx402-paymentsGems,將x402協定整合至 Rails 應用程式中。您將學習如何設定 API 以要求付款、保護特定端點,以及產生呼叫 API 所需的客戶端簽名。

您將學到什麼


  • x402 付款協定是什麼,以及它如何實現按使用量計費的 API
  • 如何使用 x402-rails 用於建立伺服器端付費牆的 gem
  • 如何設定付款條件,例如金額、區塊鏈及結算模式
  • 如何使用 x402-付款 用於產生客戶端付款簽名的 gem
  • 樂觀結算與非樂觀結算之間的差異
  • 如何設定多鏈支援(EVM 與 Solana 網路)

您需要準備的物品


  • 已安裝Ruby3.3.5 或更高版本
  • 具備 Rails 及區塊鏈概念的基本知識
  • 一個內含 Base Sepolia 測試網 USDC 的測試錢包(請使用Circle 的水龍頭領取免費的測試版 USDC)

什麼是 x402 付款協定?

x402 是一項開放標準,用於擴展 HTTP 402 需付款 搭配付款層的狀態碼。您無需管理複雜的計費系統,即可針對使用者發出的每項 API 請求自動向其收費。

該協定以簡單的迴圈方式運作。讓我們一步一步分析,然後透過圖表來檢視:


  1. 某個客戶端呼叫您的 API。
API 呼叫範例
curl -i http://localhost:3000/api/weather/paywalled_info

  1. 您的伺服器會回傳HTTP 402「需付款」狀態碼及付款說明。
「需付款」回應範例
{
"x402Version": 2,
"error": "Payment required to access this resource",
"resource": {
"url": "http://localhost:3000/api/weather/paywalled_info",
"description": "Payment required for /api/weather/paywalled_info",
"mimeType": "application/json"
},
"accepts": [
{
"scheme": "exact",
"network": "eip155:84532", // Base Sepolia CAIP-2 network identifier
"amount": "1000", // Amount in smallest unit (6 decimals for USDC)
"asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", // USDC contract on Base Sepolia
"payTo": "YourWalletAddressHere", // The receiving wallet
"maxTimeoutSeconds": 600,
"extra": {
"name": "USDC",
"version": "2"
}
}
],
"extensions": {}
}

  1. 客戶使用 EIP-712 簽署一項付款授權,並將其編碼為一個 付款簽名 頁首。
付款標頭範例
付款標題 (付款簽名):
eyJ4NDAyVmVy... # 付款授權

  1. 客戶端會帶著該標頭重新傳送該請求。
包含付款標頭的 API 呼叫範例
curl -i -H "PAYMENT-SIGNATURE: eyJ4NDAyVmVy..." http://localhost:3000/api/weather/paywalled_info

  1. 您的伺服器會驗證付款、在區塊鏈上完成結算,並返回成功回應。
成功回應範例
{
"temperature": 72,
"condition": "sunny",
"humidity": 65
}

X402 架構

為了讓 Ruby 程式碼更簡潔,Quicknode 提供了兩個 gem:

  • x402-rails(伺服器端):一個 Rails 引擎,提供中介軟體和控制器輔助函式,讓您能輕鬆為 API 端點設定「付費牆」。它負責處理簽名驗證與付款結算。

  • x402-付款 (客戶端):一個用於產生複雜的 EIP-712 加密簽名的輔助函式庫,以及 付款簽名 使用基於 x402 的 API 所必需的標頭。

採用 x402 及 Ruby on Rails 的付費 API

在本節中,我們將透過一個範例應用程式,說明如何在您自己的 Rails 應用程式中設定並配置 x402。

此 Rails 專案位於 Quicknode 的qn-guide-examples儲存庫中,提供了一個「天氣 API」和一個「高級 API」,使用者需透過 USDC 付款才能存取天氣資料。此專案展示了:


  • 無需付費的免費端點
  • 會回傳 402 狀態碼並要求付款的付費牆後端點
  • 同時支援 EVM 與 Solana 網路的多鏈功能
  • 不同的結算模式:追求速度或更強的保障

技術指南

在深入探討程式碼之前,讓我們先從高層次的角度來了解這個應用程式的運作流程。如果您對技術細節不感興趣,歡迎直接跳至「快速入門」章節。

x402 設定

x402-rails gem 是在 config/initializers/x402.rb. 它會讀取接收錢包、協調器 URL、區塊鏈、貨幣及樂觀模式等環境變數,並據此設定您的全域配置。典型的配置如下所示:

config/initializers/x402.rb
# config/initializers/x402.rb
X402.configure do |config|
# Your wallet address (where payments will be received)
config.wallet_address = ENV.fetch("X402_WALLET_ADDRESS", "0xYourWalletAddressHere")

# The service that handles on-chain settlement.
# Use the public facilitator or your own.
config.facilitator = ENV.fetch("X402_FACILITATOR_URL", "https://www.x402.org/facilitator")

# Blockchain network to use
config.chain = ENV.fetch("X402_CHAIN", "base-sepolia")

# The payment currency (USDC is the standard)
config.currency = ENV.fetch("X402_CURRENCY", "USDC")

# Custom Chain and Token Registration
config.register_chain(
name: "polygon-amoy",
chain_id: 80002,
standard: "eip155"
)

config.register_token(
chain: "polygon-amoy",
symbol: "USDC",
address: "0x41E94Eb019C0762f9Bfcf9Fb1E58725BfB0e7582",
decimals: 6,
name: "USDC",
version: "2"
)

# ==========================================
# Accept Multiple Payment Options
# ==========================================
# Use config.accept() to specify which chains/currencies to accept.
# The 402 response will include all accepted options, allowing clients
# to pay on any of the supported chains.
#
# If no config. accept() calls are made, the default chain/currency is used.

config.accept(chain: "base-sepolia", currency: "USDC")
config.accept(chain: "polygon-amoy", currency: "USDC")
config.accept(chain: "solana-devnet", currency: "USDC")


# Settlement mode:
# false (non-optimistic): Waits for onchain confirmation
# true (optimistic): Responds immediately, settles in background
config.optimistic = ENV.fetch("X402_OPTIMISTIC", "true") == "true"
end

這些設定會指定 x402-rails 何處接收 USDC 付款、使用哪條區塊鏈,以及應採取樂觀應答還是等待結算。您也可以在控制器中針對每個端點覆寫這些設定,我們稍後將會詳細說明。

什麼是引導員?

協調者是 x402 付款流程中的關鍵環節。當客戶發送包含已簽署付款授權的請求後,伺服器會將該授權轉交給協調者。接著,協調者會:


  1. 驗證已簽署的授權書
  2. 建立實際的 USDC 轉帳交易
  3. 支付提交該交易所需的 gas 費用
  4. 將交易發送至區塊鏈
  5. 將退貨結算詳情傳回您的 API

此設計讓客戶無需親自提交區塊鏈交易,即可支付 API 存取費用。他們只需簽署一則訊息(無需 RPC 呼叫、無需估算 gas 費用、也無需進行錢包連線流程)。

您可以仰賴 x402.org 上的公共協調器,或者若您需要自訂結算行為、記錄功能,或支援其他區塊鏈,亦可部署自己的實例。

在控制器中實施付費牆機制

要在 API 端點上新增付費牆,只需呼叫 x402_付費牆 輔助方法。該 x402-rails gem 會將這個輔助函式注入到您的控制器中,讓您只需一行程式碼即可要求付款。在範例中 WeatherController,該 付費內容_資訊 行動費用 $0.001 USDC 在傳回資料之前。

app/controllers/api/weather_controller.rb
  class WeatherController < ApplicationController
# Paywalled endpoint (requires payment)
def paywalled_info

# 1. REQUIRE PAYMENT: This line protects the endpoint.
# It will return a 402 response if payment is missing or invalid.
x402_paywall(amount: 0.001)

# 2. STOP EXECUTION: If the paywall rendered a 402, stop.
return if performed?

# 3. ACCESS DATA: If payment was successful, continue.
# Payment info is available in the request environment.
payment_info = request.env["x402.payment"]

render json: {
temperature: 72,
condition: "sunny",
humidity: 65,
paid_by: payment_info&.[](:payer),
payment_amount: payment_info&.[](:amount),
network: payment_info&.[](:network),
payment_info: payment_info
}
end

# Free endpoint (no paywall)
def public_info
# This endpoint has no paywall and is free.
render json: {
message: "This endpoint is free!",
location: "San Francisco",
timezone: "PST"
}
end
end

路線

範例應用程式的路由定義於 config/routes.rb. 這裡會將每個 API 端點(無論是免費的還是需付費的)映射到其對應的控制器動作。天氣 API 示範了直接使用 x402_付費牆, 而 Premium API 則採用一個 before_action 在多個終端點上實施付費牆。

config/routes.rb
Rails.應用程式.路由.繪製 執行
# 根據 https://guides.rubyonrails.org/routing.html 中的 DSL 定義您的應用程式路由

# 在 /up 端點顯示健康狀態,若應用程式啟動時未發生任何例外狀況,則返回 200 狀態碼;否則返回 500 狀態碼。
# 負載平衡器與上線時間監控工具可藉此驗證應用程式是否正常運作。
get "up" => "rails/health#show", 作為: :rails_health_check

# x402 支付協定測試端點
命名空間 :api do
# 天氣 API 端點(直接使用 x402_paywall)
get "weather/paywalled_info", 改為 "weather#paywalled_info"
取得 "weather/paywalled_info_sol", 轉換為 "weather#paywalled_info_sol"
取得 "weather/forecast", 轉換為 "weather#forecast"
取得 "weather/public", "weather#public_info"

# 高級 API 端點(before_action 用法)
資源 :premium, : [ :index, :show ] 執行
collection do
取得 :free
結束
end
end

替代性付費牆(可選)

如果多個終端點需要相同的付款邏輯,您無需重複 x402_付費牆 在每項操作中。相反地,您可以透過使用一個 before_action 篩選器。這就是 Premium API(app/controllers/api/premium_controller.rb) 的結構設計;它將相同的付費牆機制套用至多項操作,使控制器保持簡潔且一致。

app/controllers/api/premium_controller.rb
module Api
class PremiumController < ApplicationController
# Example of a paywall applied to multiple actions (show and index)
before_action :require_payment, only: [:show, :index]

def index
payment_info = request.env["x402.payment"]

render json: {
message: "Premium content list",
items: ["Item 1", "Item 2", "Item 3"],
paid_by: payment_info&.[](:payer)
}
end

def show
payment_info = request.env["x402.payment"]

render json: {
message: "Premium content details",
id: params[:id],
content: "This is premium content that requires payment",
paid_by: payment_info&.[](:payer)
}
end

def free
render json: {
message: "This premium controller endpoint is free",
sample: "Here's a sample"
}
end

private

def require_payment
x402_paywall(amount: 0.005, chain: "eip155:84532")
end
end
end

多鏈支援(可選)

x402 協定旨在跨多個區塊鏈網路運作,且每個端點均可指定其自身的鏈設定。這讓您能根據使用情境,靈活地在不同網路中接受付款。

在範例應用程式中,WeatherController 的 付費牆資訊_解決方案 在 Solana 開發網中,該終點需要進行付款,方法是將預設鏈覆寫為 solana-devnet.

app/controllers/api/weather_controller.rb
module Api
class WeatherController < ApplicationController
def paywalled_info_sol
x402_paywall(
amount: 0.001,
chain: "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1", # Solana devnet CAIP-2 identifier
currency: "USDC",
solana_fee_payer: "FuzoZt4zXaYLvXRguKw2T6xvKvzZqv6PkmaFjNrEG7jm",
wallet_address: "EYNQARNg9gZTtj1xMMrHK7dRFAkVjAAMubxaH7Do8d9Y"
)
# ...
end
end
end

處理付款錯誤(可選)

為了提供清晰的錯誤訊息,您可以攔截那些 x402-rails 引發。這項設定已在 app/controllers/application_controller.rb.

app/controllers/application_controller.rb
class ApplicationController < ActionController::API
# Application-wide x402 error handling
rescue_from X402::InvalidPaymentError, with: :render_payment_error
rescue_from X402::FacilitatorError, with: :render_facilitator_error
rescue_from X402::ConfigurationError, with: :render_config_error

private

def render_payment_error(exception)
render json: {
error: "Payment Error",
message: exception.message,
type: "invalid_payment",
status: 402
}, status: :payment_required
end

def render_facilitator_error(exception)
Rails.logger.error("[x402] Facilitator error: #{exception.message}")

render json: {
error: "Payment Service Unavailable",
message: "Unable to process payment. Please try again.",
type: "facilitator_error",
status: 503
}, status: :service_unavailable
end

def render_config_error(exception)
Rails.logger.fatal("[x402] Configuration error: #{exception.message}")

render json: {
error: "Service Configuration Error",
message: "Payment system not properly configured",
status: 500
}, status: :internal_server_error
end
end

我們已經介紹了將 x402 支付整合至 Ruby on Rails 應用程式中的關鍵技術要點。現在,讓我們開始進行範例專案的實作。

快速入門

首先,克隆 Quicknode 範例專案:

步驟 1:克隆並安裝依賴項

# 複製儲存庫
git clone https://github.com/quiknode-labs/qn-guide-examples.git
cd qn-guide-examples/rails/x402-micropayments

# 安裝依賴項
bundle 安裝

步驟 2:設定環境變數

複製該 .env.example 檔案至 .env 並更新以下變數。詳情請參閱檔案中的註解。

cp .env.example .env

步驟 3:啟動伺服器

啟動伺服器:

bin/rails server -p 3000

您的 API 現已上線,網址為 http://localhost:3000. 現在,我們需要學習如何產生有效的付款簽名,以便存取受付費牆保護的端點。

產生 x402 客戶付款

如前所述,客戶需要產生一個有效的付款簽名(付款簽名 (標頭) 以存取需付費的端點。範例專案中包含以不同程式語言編寫的簡易腳本,用於針對各種使用情境產生付款簽名:


  • Ruby: generate-payment.rb
  • TypeScript: generate-payment.ts
  • Python: generate-payment.py

本指南將使用 Ruby 腳本,但其他語言的操作流程大致相同,更多詳細資訊請參閱 README 該專案的檔案。

使用 Ruby 付款產生器

該腳本使用 bundler/inline 以自動安裝必要的依賴項,因此您無需另行設定 Gemfile。

設定並產生標頭

此腳本用於設定 x402-付款 使用客戶的私鑰(取自您的 .env 檔案),然後呼叫 generate_header 並附上所需的參數。

generate_payment.rb
# ... (see full script in the project)

# Load .env file if it exists
require 'dotenv'
Dotenv.load

# Configuration
PRIVATE_KEY = ENV.fetch('X402_TEST_PRIVATE_KEY', '0xYourPrivateKeyHere')
PORT = ENV.fetch('PORT', '3000')
PAY_TO = ENV.fetch('X402_WALLET_ADDRESS', 'YourWalletAddressHere')
CHAIN = ENV.fetch('X402_CHAIN', 'base-sepolia')

# Configure x402-payments gem
X402::Payments.configure do |config|
config.private_key = PRIVATE_KEY
config.chain = CHAIN
config.default_pay_to = PAY_TO
config.max_timeout_seconds = 600
end

# Generate payment header
# The gem handles all the EIP-712 signing internally
begin
payment_header = X402::Payments.generate_header(
amount: 0.001, # $0.001 in USD
resource: "http://localhost:#{PORT}/api/weather/paywalled_info",
description: "Payment required for /api/weather/paywalled_info"
)
end

# ... (see full script in the project)

執行腳本

現在,執行這個腳本:

ruby generate_payment.rb

此腳本會輸出付款標頭,您可在您的客戶端中使用它。

注意:腳本中將付款的最大超時時間設定為 600 秒。您可以根據實際使用情況調整此數值。否則,付款將在 600 秒後失效。

測試付費牆

既然我們已經設定好伺服器和付款產生器,現在就可以測試完整的付款流程,並了解 x402 在實際運作中的運作方式。

為您的錢包充值

若要測試支付功能,您需要在 Base Sepolia 測試網中準備一些測試用 USDC。您可以從Circle USDC 水龍頭領取一些免費的測試用 USDC。

設有付費牆的終端點

首先,請嘗試在不包含付款標頭的情況下存取需付費的端點:

curl -i http://localhost:3000/api/weather/paywalled_info

您應會收到一個 402 回應,其中包含以下 JSON 有效載荷:

{
"x402Version": 2,
"error": "Payment required to access this resource",
"resource": {
"url": "http://localhost:3000/api/weather/paywalled_info",
"description": "Payment required for /api/weather/paywalled_info",
"mimeType": "application/json"
},
"accepts": [
{
"scheme": "exact",
"network": "eip155:84532",
"amount": "1000",
"asset": "Asset Contract Address", // e.g., USDC on Base Sepolia
"payTo": "Recipient Address", // The receiving wallet
"maxTimeoutSeconds": 600,
"extra": {
"name": "USDC",
"version": "2"
}
}
],
"extensions": {}
}

現在,請使用 Ruby 腳本(或您偏好的付款產生器)所產生的付款標頭,來存取需付費才能存取的端點:

curl -i -H "PAYMENT-SIGNATURE: eyJ4NDAyVmVy..." http://localhost:3000/api/weather/paywalled_info

您應會收到一個 200 狀態碼的回應,其中包含以下 JSON 資料:

{
"temperature": 72,
"condition": "sunny",
"humidity": 65,
"paid_by": "0x...",
"payment_amount": "1000",
"network": "base-sepolia"
// ...
}

恭喜!您已成功將 x402 支付功能整合至您的 Ruby on Rails 應用程式中。現在,您可以使用支付標頭存取需付費才能存取的端點,並享受微支付帶來的好處。

請使用區塊鏈瀏覽器(例如Base Sepolia Explorer)來確認該付款交易已成功在區塊鏈上結算。

x402 交易結果(在 Explorer 上)

免費終端點

您也可以嘗試存取這個免費的端點:

curl -i http://localhost:3000/api/weather/public

此端點不需要支付標頭,因此您應會收到一個 200 回應,其中包含以下 JSON 有效載荷:

{
"message": "This endpoint is free!",
"location": "San Francisco",
"timezone": "PST"
}

結論

現在,您已經對x402x402-railsx402-payments如何在實際的 Rails 應用程式中協同運作,有了實務上的理解。

在此,您可以:

  • 實作您自己的業務邏輯
  • 針對每個端點或每個 HTTP 方法設定不同的價格
  • 當您準備好投入正式運作時,請從測試網切換至主網
  • 考慮自行聘請主持人,以獲得更多掌控權

如果您遇到困難或有任何疑問,歡迎在我們的Discord 頻道中提出。請追蹤我們的X帳號 (@Quicknode) 或Telegram 公告頻道,以掌握最新動態。

我們 ❤️ 您的回饋!

如果您有任何意見回饋或對新主題的建議,請告訴我們。我們非常樂意聽取您的意見。

分享這份指南