Active Merchant 支付网关开发指南:如何快速添加新的支付提供商

张开发
2026/4/9 23:06:19 15 分钟阅读

分享文章

Active Merchant 支付网关开发指南:如何快速添加新的支付提供商
Active Merchant 支付网关开发指南如何快速添加新的支付提供商【免费下载链接】active_merchantActive Merchant is a simple payment abstraction library extracted from Shopify. The aim of the project is to feel natural to Ruby users and to abstract as many parts as possible away from the user to offer a consistent interface across all supported gateways.项目地址: https://gitcode.com/gh_mirrors/ac/active_merchantActive Merchant 是一个强大的 Ruby 支付抽象库最初从 Shopify 中提取而来。这个开源项目为开发者提供了一个简单统一的接口可以接入全球超过 200 个支付网关。在本指南中我将详细介绍如何为 Active Merchant 快速添加新的支付提供商无论你是 Ruby 开发者还是支付系统集成专家都能轻松掌握这一技能。 为什么选择 Active MerchantActive Merchant 的核心优势在于其统一的 API 设计让你可以用相同的代码处理不同支付网关的集成。想象一下只需编写一次支付逻辑就能支持 PayPal、Stripe、Authorize.Net 等数百个支付服务商这种抽象层极大地简化了支付系统开发减少了维护成本。 项目结构概览在开始添加新的支付网关之前让我们先了解 Active Merchant 的项目结构lib/active_merchant/billing/ ├── gateway.rb # 网关基类定义通用接口 ├── gateways/ # 所有支付网关实现 │ ├── authorize_net.rb │ ├── stripe.rb │ ├── paypal.rb │ └── ... 200 网关 └── response.rb # 统一响应对象每个支付网关都继承自ActiveMerchant::Billing::Gateway基类实现了标准化的支付操作接口。️ 快速创建新网关的 5 个步骤步骤 1使用生成器创建网关骨架Active Merchant 提供了便捷的生成器工具可以快速创建新网关的基本结构cd /data/web/disk1/git_repo/gh_mirrors/ac/active_merchant ruby -r ./generators/gateway/gateway_generator.rb -e GatewayGenerator.new([new_gateway]).generate生成器会自动创建三个文件lib/active_merchant/billing/gateways/new_gateway.rb- 网关实现test/unit/gateways/new_gateway_test.rb- 单元测试test/remote/gateways/remote_new_gateway_test.rb- 远程测试步骤 2配置网关基本信息打开生成的网关文件首先配置网关的基本信息module ActiveMerchant module Billing class NewGatewayGateway Gateway # 测试和生产环境的 API 端点 self.test_url https://api.example.com/test self.live_url https://api.example.com/live # 支持的国家/地区 self.supported_countries [US, CA, GB] # 默认货币 self.default_currency USD # 支持的信用卡类型 self.supported_cardtypes %i[visa master american_express discover] # 网关信息 self.homepage_url https://www.example.com/ self.display_name New Payment Gateway end end end步骤 3实现核心支付方法每个网关必须实现以下核心方法purchase- 直接购买授权捕获authorize- 预授权capture- 捕获预授权void- 取消交易refund- 退款verify- 验证信用卡以purchase方法为例def purchase(money, payment, options {}) post {} add_invoice(post, money, options) add_payment(post, payment) add_address(post, payment, options) add_customer_data(post, options) commit(sale, post) end步骤 4实现 API 通信逻辑这是网关实现的核心部分需要处理与支付提供商 API 的通信private def commit(action, parameters) url (test? ? test_url : live_url) response parse(ssl_post(url, post_data(action, parameters))) Response.new( success_from(response), message_from(response), response, authorization: authorization_from(response), avs_result: AVSResult.new(code: response[avs_code]), cvv_result: CVVResult.new(response[cvv_code]), test: test?, error_code: error_code_from(response) ) end def post_data(action, parameters {}) # 构建 API 请求数据 # 根据支付提供商的文档格式化为 JSON 或 XML end def parse(body) # 解析 API 响应 # 返回格式化的响应数据 end步骤 5添加错误处理映射标准化错误代码映射对于提供一致的错误处理体验至关重要STANDARD_ERROR_CODE_MAPPING { 100 STANDARD_ERROR_CODE[:card_declined], 101 STANDARD_ERROR_CODE[:invalid_number], 102 STANDARD_ERROR_CODE[:expired_card], 103 STANDARD_ERROR_CODE[:incorrect_cvc], 200 STANDARD_ERROR_CODE[:processing_error] } 关键实现细节金额处理规范所有金额都以分为单位传递例如 $10.00 应传递为 1000。Active Merchant 会自动处理货币转换def add_invoice(post, money, options) post[:amount] amount(money) # 转换为字符串格式 post[:currency] (options[:currency] || currency(money)) end信用卡数据处理支持多种支付方式包括普通信用卡、网络令牌化信用卡和 EMV 芯片卡def add_payment(post, payment) if payment.is_a?(CreditCard) post[:card_number] payment.number post[:expiry_month] payment.month post[:expiry_year] payment.year post[:cvv] payment.verification_value elsif payment.is_a?(NetworkTokenizationCreditCard) # 处理 Apple Pay、Google Pay 等网络令牌 end end地址信息处理标准化地址格式确保与所有网关兼容def add_address(post, payment, options) if address options[:billing_address] || options[:address] post[:address] { name: address[:name], address1: address[:address1], city: address[:city], state: address[:state], zip: address[:zip], country: address[:country], phone: address[:phone] } end end 编写测试确保质量单元测试结构每个网关都需要完善的测试覆盖require test_helper class NewGatewayTest Test::Unit::TestCase def setup gateway NewGatewayGateway.new( login: test_login, password: test_password ) amount 1000 # $10.00 credit_card credit_card(4242424242424242) options { order_id: 1, billing_address: address } end def test_successful_purchase response stub_comms do gateway.purchase(amount, credit_card, options) end.respond_with(successful_purchase_response) assert_success response assert_equal Transaction approved, response.message end end远程测试配置在test/fixtures.yml中添加测试凭据new_gateway: login: TEST_LOGIN password: TEST_PASSWORD 最佳实践与性能优化1. 连接池管理对于高流量应用实现连接池可以显著提升性能def connection connection || Net::HTTP.start(URI.parse(url).host, URI.parse(url).port, use_ssl: true, read_timeout: 60, open_timeout: 30) end2. 请求重试机制实现智能重试逻辑处理临时网络故障def ssl_post(url, data, headers {}) retries 0 begin super rescue Timeout::Error, Errno::ECONNRESET e retries 1 retry if retries 3 raise end end3. 敏感信息清理实现supports_scrubbing?和scrub方法保护日志中的敏感信息def supports_scrubbing? true end def scrub(transcript) transcript .gsub(/(login)[^]*/, \1[FILTERED]) .gsub(/(password)[^]*/, \1[FILTERED]) .gsub(/(number)\d/, \1[FILTERED]) .gsub(/(cvv)\d/, \1[FILTERED]) end 高级功能集成3D Secure 支持现代支付网关需要支持 3D Secure 验证def add_3ds(post, options) if three_d_secure options[:three_d_secure] post[:threeDSecure] { eci: three_d_secure[:eci], cavv: three_d_secure[:cavv], xid: three_d_secure[:xid] } end end网络令牌化支付支持 Apple Pay、Google Pay 等现代支付方式def add_network_tokenization(post, payment) if payment.is_a?(NetworkTokenizationCreditCard) post[:source] { type: network_token, number: payment.number, cryptogram: payment.payment_cryptogram, eci: payment.eci } end end 调试与故障排除1. 启用详细日志在开发环境中启用详细日志记录ActiveMerchant::Billing::Base.mode :test ActiveMerchant::Billing::Gateway.wiredump_device File.open(payment.log, a)2. 使用 Bogus 网关测试Active Merchant 提供了BogusGateway用于测试无需真实支付凭据# 使用信用卡号以 1 结尾表示成功2 结尾表示失败 credit_card CreditCard.new(number: 4111111111111111) # 成功 credit_card CreditCard.new(number: 4111111111111112) # 失败3. 检查常见问题金额格式错误确保金额以分为单位时区问题API 时间戳使用 UTC字符编码确保使用 UTF-8 编码SSL 证书保持证书链最新 性能基准测试在添加新网关后进行性能基准测试require benchmark Benchmark.bm do |x| x.report(purchase) { 100.times { gateway.purchase(1000, credit_card) } } x.report(authorize) { 100.times { gateway.authorize(1000, credit_card) } } x.report(capture) { 100.times { gateway.capture(1000, auth) } } end 提交贡献指南完成新网关开发后按以下步骤提交到 Active Merchant编写完整的测试套件包括单元测试和远程测试更新文档在 README 的 Supported Payment Gateways 部分添加新网关确保代码风格一致遵循项目现有的代码规范提交 Pull Request详细描述新网关的功能和测试结果 实用技巧与资源快速参考路径网关模板generators/gateway/templates/gateway.rb测试模板generators/gateway/templates/gateway_test.rb现有网关示例lib/active_merchant/billing/gateways/authorize_net.rb测试助手test/test_helper.rb学习资源查看lib/active_merchant/billing/gateway.rb了解所有可用方法参考test/unit/gateways/中的现有测试学习最佳实践使用BogusGateway作为开发模板 开始你的支付网关开发之旅现在你已经掌握了为 Active Merchant 添加新支付网关的全部知识无论你是要为现有的支付服务商创建适配器还是要集成全新的支付解决方案Active Merchant 的统一架构都能让你的开发工作事半功倍。记住良好的支付网关实现不仅需要正确的功能还需要完善的错误处理、日志记录和测试覆盖。通过遵循本文的指南你可以快速创建出符合生产标准的支付网关集成为你的 Ruby 应用提供强大而灵活的支付处理能力。开始编码吧让 Active Merchant 的支付生态系统因你的贡献而更加丰富【免费下载链接】active_merchantActive Merchant is a simple payment abstraction library extracted from Shopify. The aim of the project is to feel natural to Ruby users and to abstract as many parts as possible away from the user to offer a consistent interface across all supported gateways.项目地址: https://gitcode.com/gh_mirrors/ac/active_merchant创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

更多文章