python 支付接口自动化如何做

📝 面试求职: 「面试试题小程序」 ,内容涵盖 测试基础、Linux操作系统、MySQL数据库、Web功能测试、接口测试、APPium移动端测试、Python知识、Selenium自动化测试相关、性能测试、性能测试、计算机网络知识、Jmeter、HR面试,命中率杠杠的。(大家刷起来…)

📝 职场经验干货:

软件测试工程师简历上如何编写个人信息(一周8个面试)

软件测试工程师简历上如何编写专业技能(一周8个面试)

软件测试工程师简历上如何编写项目经验(一周8个面试)

软件测试工程师简历上如何编写个人荣誉(一周8个面试)

软件测试行情分享(这些都不了解就别贸然冲了.)

软件测试面试重点,搞清楚这些轻松拿到年薪30W+

软件测试面试刷题小程序免费使用(永久使用)


 

在自动化测试中,支付接口的自动化测试是一个非常关键且复杂的部分。它不仅涉及标准的接口请求/响应验证,还可能包括:

✅ 支付流程完整性验证(下单 → 支付 → 回调通知)

✅ 支付状态变更校验

✅ 数据库断言(是否扣款、订单状态更新)

✅ 第三方支付平台对接(如支付宝、微信、银联等)

✅ 异步回调处理(异步通知、Webhook)

✅ 加密签名机制(如签名算法、密钥管理)‍

🧱 一、目标

本指南将为你提供一个 Python 实现支付接口自动化测试的完整方案,适用于电商、金融、SaaS 等场景。

📦 二、所需工具 & 技术栈

📁 三、目录结构建议

payment_automation/
│
├── config/
│   ├── settings.py         # 配置文件(API 地址、密钥等)
│   └── payment_config.py   # 支付相关配置
│
├── utils/
│   ├── http_client.py      # HTTP 请求封装
│   ├── sign_utils.py       # 签名生成工具
│   ├── db_utils.py         # 数据库操作封装
│   └── logger.py           # 日志工具
│
├── api/
│   ├── order_api.py        # 下单接口
│   ├── payment_api.py      # 支付接口
│   └── notify_api.py       # 回调通知接口
│
├── testcases/
│   └── test_payment_flow.py # 支付流程测试用例
│
├── conftest.py             # pytest 全局 fixture
├── run_tests.py            # 启动测试脚本
└── requirements.txt        # 依赖库‍

🔧 四、核心代码实现

1️⃣ 支付配置:config/payment_config.py

# config/payment_config.py
PAYMENT_CONFIG = {
    "base_url": "https://api.payment-gateway.com",
    "app_id": "your_app_id",
    "private_key": "your_private_key_here",  # 商户私钥
    "public_key": "third_party_public_key",  # 支付平台公钥
    "notify_url": "https://yourdomain.com/notify",  # 异步回调地址
}

2️⃣ 签名工具类:utils/sign_utils.py

# utils/sign_utils.py
import hashlib
import hmac
from urllib.parse import quote_plus
def generate_sign(params: dict, secret_key: str) -> str:
    """
    生成签名(按 key 排序后拼接)
    """
    sorted_params = "&".join(f"{k}={quote_plus(str(v))}" for k, v in sorted(params.items()))
    sign = hmac.new(secret_key.encode(), digestmod=hashlib.sha256)
    sign.update(sorted_params.encode())
    return sign.hexdigest()

3️⃣ HTTP 客户端封装:utils/http_client.py

# utils/http_client.py
import httpx
from config.payment_config import PAYMENT_CONFIG
class HttpClient:
    def __init__(self):
        self.base_url = PAYMENT_CONFIG["base_url"]
        self.headers = {"Content-Type": "application/json"}
    def post(self, endpoint: str, data: dict):
        url = f"{self.base_url}{endpoint}"
        return httpx.post(url, json=data, headers=self.headers, timeout=10)

4️⃣ 下单接口封装:api/order_api.py

# api/order_api.py
from utils.http_client import HttpClient
from utils.sign_utils import generate_sign
from config.payment_config import PAYMENT_CONFIG
client = HttpClient()
def create_order(order_data: dict):
    """
    创建订单并返回订单号
    """
    secret_key = PAYMENT_CONFIG["private_key"]
    order_data["sign"] = generate_sign(order_data, secret_key)
    response = client.post("/order/create", data=order_data)
    return response.json()

5️⃣ 支付接口封装:api/payment_api.py

# api/payment_api.py
from utils.http_client import HttpClient
from utils.sign_utils import generate_sign
from config.payment_config import PAYMENT_CONFIG
client = HttpClient()
def do_payment(payment_data: dict):
    """
    发起支付请求
    """
    secret_key = PAYMENT_CONFIG["private_key"]
    payment_data["sign"] = generate_sign(payment_data, secret_key)
    response = client.post("/payment/do", data=payment_data)
    return response.json()

6️⃣ 回调接口模拟:api/notify_api.py

# api/notify_api.py
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route("/notify", methods=["POST"])
def payment_notify():
    data = request.json
    print("收到支付回调通知:", data)
    return jsonify({"status": "success"}), 200
可以使用 ngrok 或 localtunnel 将本地服务暴露为公网 URL,用于接收支付平台的回调通知。

7️⃣ 数据库工具类(可选):utils/db_utils.py

# utils/db_utils.py
import pymysql
from config.db_config import DB_CONFIG
class DBUtils:
    def __init__(self):
        self.conn = pymysql.connect(**DB_CONFIG)
    def query_order_status(self, order_id):
        with self.conn.cursor() as cursor:
            cursor.execute(f"SELECT status FROM orders WHERE id='{order_id}'")
            result = cursor.fetchone()
            return result[0] if result else None

8️⃣ 测试用例示例:testcases/test_payment_flow.py

# testcases/test_payment_flow.py
import pytest
from api.order_api import create_order
from api.payment_api import do_payment
from utils.db_utils import DBUtils
@pytest.fixture
def db_utils():
    return DBUtils()
def test_payment_flow(db_utils):
    # 步骤1:创建订单
    order_data = {
        "user_id": "U1001",
        "product_id": "P2001",
        "amount": 99.9,
        "timestamp": "20250405120000"
    }
    order_response = create_order(order_data)
    order_id = order_response.get("order_id")
    assert order_id is not None, "下单失败"
    # 步骤2:发起支付
    payment_data = {
        "order_id": order_id,
        "pay_type": "wechat",
        "timestamp": "20250405120010"
    }
    payment_response = do_payment(payment_data)
    assert payment_response.get("code") == "200", "支付失败"
    # 步骤3:等待回调通知(或主动查询数据库)
    import time
    time.sleep(5)  # 模拟异步通知延迟
    # 步骤4:数据库断言
    status = db_utils.query_order_status(order_id)
    assert status == "paid", f"订单状态未更新,当前为 {status}"

📊 五、运行测试 & 查看报告

pip install -r requirements.txt
python run_tests.py

你可以使用以下命令生成 Allure 报告:

pytest testcases/ --alluredir=./reports/allure
allure serve ./reports/allure‍

🎯 六、高级技巧与注意事项

✅ 支付接口测试的关键点

📦 七、推荐实践

✅ 所有敏感信息(如密钥)应从环境变量读取,而非硬编码

✅ 使用 .env 文件 + python-dotenv 管理配置

✅ 使用 faker 生成测试数据(如用户信息、商品ID)

✅ 使用 docker-compose 构建本地测试环境(MySQL、Redis、Flask 回调服务)

✅ 将测试框架集成到 CI/CD 中(Jenkins / GitHub Actions)

🧩 八、可选增强功能

最后: 下方这份完整的软件测试视频教程已经整理上传完成,需要的朋友们可以自行领取【保证100%免费】

​​

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值