module X402 class PaymentMiddleware < X402::Middleware # 必须继承 def initialize(app) @app = app end
def call(env) status, headers, body = @app.call(env)
# 支付成功后记录
if status == 200 && headers['X-Payment-Response'].present? && env['HTTP_X402_PAYMENT'].present?
binding.pry
begin
payment_json = JSON.parse(env['HTTP_X402_PAYMENT'])
tx_hash = headers['X-Payment-Response']
post_id = extract_post_id(env['REQUEST_URI'])
return [status, headers, body] unless post_id
Payment.find_or_create_by!(
post_id: post_id,
payer_address: payment_json['signer'].downcase
) do |p|
p.tx_hash = tx_hash
p.amount = payment_json['maxAmountRequired'].to_f / 1e6
p.paid_at = Time.current
p.user = current_user_from_session(env) if defined?(current_user_from_session)
end
rescue => e
Rails.logger.error "X402 Payment record failed: #{e.message}"
end
end
[status, headers, body]
end
private
def extract_post_id(path) # path.match(//posts/(\d+)/)&.[1]&.to_i end
可选:从 session 提取当前登录用户(Devise/Authentication)
def current_user_from_session(env) # 适配你的认证系统,例如: # session = ActionDispatch::Request::Session.new(env) # User.find(session[:user_id]) if session[:user_id] nil end end end
回覆