python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python接口签名调用

Python实现接口签名调用的示例详解

作者:bst@微胖子

这篇文章主要为大家详细介绍了Python中第三方接口签名的调用方法及其关键步骤,并探讨了调用结果的处理策略,助您高效安全地完成接口调用

1、第三方接口签名调用

import json
import requests
import hashlib
import time
import hmac
access_key = 'xxxxxxxxxxxxxxx'
secret_key = 'xxxxxxxxxxxxxxx'
# 应用信息
def _wps4_sig(method, url, date, body):    
    print(body)
    if body is None:
        bodySha = ""
    else:
        bodySha = hashlib.sha256(body.encode('utf-8')).hexdigest()

    content = "xxx-4" + method + url + "application/json" + date + bodySha
    print(content)
    signature = hmac.new(secret_key.encode('utf-8'), content.encode('utf-8'), hashlib.sha256).hexdigest()

    return "xxx-4 %s:%s" % (access_key, signature)


def wps4_request(method, host, uri, body=None, cookie=None, headers=None):
    requests.packages.urllib3.disable_warnings()

    if body is not None and not isinstance(body, str):
        body = json.dumps(body)

    date = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime())
    # date = "Fri, 03 Jan 2025 07:44:40 GMT"

    # print date
    header = {"Content-type": "application/json"}
    header['xxx-Docs-Date'] = date
    header['xxx-Docs-Authorization'] = _wps4_sig(method, uri, date, body)
    # header['xxx-Docs-Authorization'] ='xxx-4 LSURICXMDHRWXHKR:c7451af3b5318781ab323817d2411a8e40d6d5ae86a06b86676b0e6b7928579e'

    if headers != None:
        # header = {}
        for key, value in headers.items():
            header[key] = value

    url = "%s%s" % (host, uri)
    r = requests.request(method, url, data=body,
                         headers=header, cookies=cookie, verify=False)
    return r.status_code, r.text
def edit(file_id=1):
    url = '/api/edit/v1/files/{0}/link?type=w'.format(file_id)
    #result = wps4_request('post', 'https://core.equiclouds.com', '/www/dd/test/req_raw', '''{"a":1}''')
    #print(result[1])
    result = wps4_request('GET', 'http://xx.xx.xx.xxx:xxxx/open', url)
    print(result[0])
    print(result[1])
edit()

2、调用结果

3、知识扩展

Python 第三方接口签名调用完整指南

调用第三方 API 时,为了确保请求的身份真实性数据完整性,服务提供方通常会要求对请求进行签名(Signature)。签名本质上是将请求参数、时间戳、密钥等按约定规则加密生成一段唯一字符串,服务端通过验证签名来判断请求是否合法、是否被篡改。

本指南将从原理到代码,覆盖最常见的签名方式,并提供可直接运行的 Python 示例。

签名调用的通用流程

无论使用何种签名算法,一般步骤是:

主流签名方式及 Python 实现

1.OAuth 2.0(客户端凭证模式)

场景:需要用户授权(如 Google、GitHub),但也可用于服务器间调用。

原理:使用 client_id 和 client_secret 换取 access_token,后续请求携带该 Token。

import requests
def get_oauth_token(client_id, client_secret, token_url):
    data = {
        'grant_type': 'client_credentials',
        'client_id': client_id,
        'client_secret': client_secret,
    }
    resp = requests.post(token_url, data=data)
    return resp.json()['access_token']
# 获取 token
token = get_oauth_token('your_client_id', 'your_secret', 'https://auth.example.com/token')
# 使用 token 调用 API
headers = {'Authorization': f'Bearer {token}'}
resp = requests.get('https://api.example.com/data', headers=headers)

注意:Token 有过期时间,需缓存并定期刷新。

2.JWT(JSON Web Token)

场景:用户登录态、微服务间认证。

原理:使用密钥或私钥生成包含用户信息的 JWT,服务端验证签名。

import jwt
import time
SECRET_KEY = "your_secret_key"   # 或使用 RSA 私钥
payload = {
    'user_id': 123,
    'exp': int(time.time()) + 3600   # 1小时后过期
}
token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')
headers = {'Authorization': f'Bearer {token}'}
resp = requests.get('https://api.example.com/protected', headers=headers)

JWT 特点:自包含,无需服务端存储会话,适合分布式系统。

3.RSA 非对称签名(私钥签名,公钥验证)

场景:高安全性环境(如支付回调、银行接口)。

原理:使用私钥对请求摘要进行签名,服务端用公钥验证。

from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
import base64
import requests
def sign_with_rsa(private_key_pem, message):
    # 加载私钥
    private_key = serialization.load_pem_private_key(private_key_pem, password=None)
    # 签名
    signature = private_key.sign(
        message.encode('utf-8'),
        padding.PKCS1v15(),
        hashes.SHA256()
    )
    return base64.b64encode(signature).decode('utf-8')
# 读取私钥(通常为 PEM 格式)
private_key = open('private_key.pem', 'rb').read()
message = "GET /api/v1/resource"   # 实际为请求行或参数组合
signature = sign_with_rsa(private_key, message)
headers = {'X-Signature': signature, 'X-User': 'client_id'}
resp = requests.get('https://api.example.com/resource', headers=headers)

注意:签名内容需按文档约定,可能是整个请求体或特定摘要。

4.简单的 MD5 参数签名(老旧系统)

场景:部分旧版 API。

原理:将参数拼接后加盐,计算 MD5。

import hashlib
import requests
def md5_sign(params, salt):
    # 按固定顺序拼接(通常文档指定)
    raw = f"key1={params['key1']}&key2={params['key2']}&salt={salt}"
    return hashlib.md5(raw.encode('utf-8')).hexdigest()
params = {'amount': 100, 'order_id': '123'}
params['sign'] = md5_sign(params, 'your_salt')
response = requests.post('https://api.example.com/pay', data=params)

注意:MD5 安全性较低,建议使用更安全的算法。

到此这篇关于Python实现接口签名调用的示例详解的文章就介绍到这了,更多相关Python接口签名调用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文