本文来源公众号“python”,仅用于学术分享,侵权删,干货满满。
原文链接:https://mp.weixin.qq.com/s/7NrQtGidp45otTvvcuNOLw
merchant是一个专为Python开发者设计的支付网关集成库,旨在简化电商网站和应用程序中支付功能的实现。该库的核心理念是提供统一的API接口,让开发者能够轻松地集成多种支付服务商,如PayPal、Stripe、Authorize.Net、WorldPay等主流支付平台,而无需为每个支付网关编写不同的代码。作为Django生态系统的重要组成部分,merchant库解决了传统支付集成过程中接口不统一、代码复杂、维护困难等痛点。
安装
1、环境要求
merchant库需要Python 3.6+环境,建议在Django 2.2+框架下使用,同时需要安装相关支付网关的官方SDK。
2、安装步骤
# 安装核心库
pip install django-merchant
# 安装特定支付网关依赖
pip install stripe paypal-sdk-python
# 安装加密相关依赖
pip install cryptography pycrypto
3、Django项目配置
# settings.py配置
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'billing', # merchant库的核心应用
# 其他应用
]
# 支付网关配置
MERCHANT_SETTINGS = {
'MODE': 'test', # 'live' for production
'DEFAULT_CURRENCY': 'USD',
}
核心特性
-
统一API接口:为不同支付网关提供一致的调用方式
-
多网关支持:集成PayPal、Stripe、Authorize.Net等主流支付平台
-
Django集成:与Django框架深度集成,支持模型和表单
-
安全性保障:内置加密和安全验证机制
-
交易管理:完整的支付流程追踪和状态管理
-
退款支持:统一的退款接口和流程处理
-
实时通知:支持支付网关的webhook回调处理
-
测试环境:完善的测试模式和模拟支付功能
基本功能
1、支付网关初始化配置
在开始处理支付之前,需要初始化和配置支付网关,这个过程包括设置API密钥、选择支付模式和配置基本参数。
from billing import get_gateway
from billing.models import PaymentMethod
# 配置Stripe网关
stripe_settings = {
'PUBLISHABLE_KEY': 'pk_test_your_publishable_key',
'SECRET_KEY': 'sk_test_your_secret_key',
'CURRENCY': 'USD'
}
# 初始化支付网关
def initialize_payment_gateway(gateway_name, settings):
gateway = get_gateway(gateway_name)
gateway.configure(settings)
return gateway
# 使用示例
stripe_gateway = initialize_payment_gateway('stripe', stripe_settings)
2、创建支付请求
支付请求创建是电商交易的核心环节,包括订单信息处理、金额计算和支付参数设置,在用户下单结算、会员充值、商品购买等场景中广泛应用,是实现在线支付的基础步骤。
from billing.forms import CreditCardForm
from billing.models import CreditCard
from decimal import Decimal
# 创建支付请求
def create_payment_request(amount, currency='USD', card_data=None):
# 验证支付金额
if amount <= 0:
raise ValueError("支付金额必须大于0")
# 构建支付参数
payment_options = {
'amount': Decimal(str(amount)),
'currency': currency,
'description': f'Payment for order',
}
# 如果提供了信用卡信息
if card_data:
credit_card = CreditCard(
first_name=card_data['first_name'],
last_name=card_data['last_name'],
month=card_data['month'],
year=card_data['year'],
number=card_data['number'],
verification_value=card_data['cvv']
)
payment_options['credit_card'] = credit_card
return payment_options
# 使用示例
card_info = {
'first_name': 'John',
'last_name': 'Doe',
'number': '4242424242424242',
'month': '12',
'year': '2025',
'cvv': '123'
}
payment_request = create_payment_request(99.99, 'USD', card_info)
3、执行支付处理
支付处理是整个支付流程的关键步骤,负责与支付网关通信、处理支付结果和管理交易状态。
from billing.utils import get_gateway
# 执行支付处理
def process_payment(gateway_name, payment_options):
try:
# 获取配置好的网关
gateway = get_gateway(gateway_name)
# 执行支付
response = gateway.purchase(
amount=payment_options['amount'],
credit_card=payment_options['credit_card'],
options={
'order_id': payment_options.get('order_id'),
'customer_id': payment_options.get('customer_id'),
}
)
# 处理支付结果
if response['status'] == 'SUCCESS':
return {
'success': True,
'transaction_id': response['response'].id,
'message': '支付成功'
}
else:
return {
'success': False,
'error': response['response'].reason,
'message': '支付失败'
}
except Exception as e:
return {
'success': False,
'error': str(e),
'message': '支付处理异常'
}
# 处理支付
result = process_payment('stripe', payment_request)
print(f"支付结果: {result}")
高级功能
1、支付状态管理和订阅处理
支付状态管理是企业级应用的重要功能,特别适用于SaaS服务的订阅付费、分期付款和周期性收费场景,能够自动处理续费、暂停和取消等复杂业务逻辑。
from billing.models import RecurringPayment
from datetime import datetime, timedelta
# 创建订阅支付
def create_subscription(customer_id, plan_id, amount, interval='monthly'):
gateway = get_gateway('stripe')
subscription_data = {
'customer_id': customer_id,
'plan_id': plan_id,
'amount': amount,
'interval': interval,
'start_date': datetime.now(),
'next_billing_date': datetime.now() + timedelta(days=30)
}
# 创建订阅
response = gateway.recurring(subscription_data)
if response['status'] == 'SUCCESS':
# 保存订阅记录
recurring_payment = RecurringPayment.objects.create(
subscription_id=response['response'].id,
customer_id=customer_id,
amount=amount,
status='ACTIVE'
)
return recurring_payment
returnNone
# 管理订阅状态
def manage_subscription(subscription_id, action):
gateway = get_gateway('stripe')
if action == 'cancel':
response = gateway.cancel_recurring(subscription_id)
elif action == 'pause':
response = gateway.pause_recurring(subscription_id)
return response['status'] == 'SUCCESS'
2、退款和争议处理
退款功能是电商系统不可缺少的部分,用于处理客户退货、服务纠纷和异常交易,完善的退款机制能够提升客户满意度并符合监管要求。
from billing.models import Refund
# 处理退款
def process_refund(transaction_id, amount=None, reason=''):
gateway = get_gateway('stripe')
try:
# 获取原始交易信息
transaction = gateway.capture(transaction_id)
# 设置退款金额(默认全额退款)
refund_amount = amount or transaction.amount
# 执行退款
refund_response = gateway.refund(
amount=refund_amount,
identification=transaction_id
)
if refund_response['status'] == 'SUCCESS':
# 记录退款信息
refund = Refund.objects.create(
original_transaction_id=transaction_id,
refund_transaction_id=refund_response['response'].id,
amount=refund_amount,
reason=reason,
status='COMPLETED'
)
return {
'success': True,
'refund_id': refund.id,
'message': '退款成功'
}
except Exception as e:
return {
'success': False,
'error': str(e),
'message': '退款失败'
}
# 批量退款处理
def batch_refund(transaction_ids, reason='批量退款'):
results = []
for tx_id in transaction_ids:
result = process_refund(tx_id, reason=reason)
results.append(result)
return results
总结
merchant库作为Python生态系统中优秀的支付集成解决方案,通过统一的API接口大大简化了多支付网关的集成复杂度。它不仅提供了完整的支付流程处理能力,还具备订阅管理、退款处理等企业级功能,能够满足从小型电商到大型SaaS平台的各种支付需求。随着数字支付的快速发展和支付方式的多样化,merchant库将继续为Python开发者提供稳定可靠的支付集成基础,助力各类互联网应用实现便捷安全的支付功能。
THE END !
文章结束,感谢阅读。您的点赞,收藏,评论是我继续更新的动力。大家有推荐的公众号可以评论区留言,共同学习,一起进步。


被折叠的 条评论
为什么被折叠?



