评论

Python 图片上传API

python 图片上传 特约商户进件接口

图片上传API :https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter2_1_1.shtml

官方给出了 php, gom java的sdk, 唯独没有python的sdk ,特此在这写下相关的伪代码,希望能帮助到大家


url = "https://api.mch.weixin.qq.com/v3/merchant/media/upload"

payload = {
    'meta': '{"filename":"new_logo.png","sha256":"ce92787ac5dc0e8605d47e935f6b10b675efa104ea596dc2703e8587a277d7c0"}'}
files = [
    ('file', ('new_logo.png', open('/Users/kw/Desktop/new_logo.png', 'rb'), 'image/png'))
]

Authorization = build_authorization(
    '/v3/merchant/media/upload',
    'POST',
    '商户号',
    '证书序列号',
    '私钥字符串',
    data=payload['meta']
)



print(Authorization)

headers = {
    'Authorization': Authorization
}
response = requests.request("POST", url, headers=headers, data=payload, files=files)
print(response.text)

def build_authorization(path,
                        method,
                        mchid,
                        serial_no,
                        mch_private_key,
                        data=None,
                        nonce_str=None):
    timeStamp = str(int(time.time()))
    nonce_str = nonce_str or ''.join(str(uuid.uuid4()).split('-')).upper()
    if isinstance(data, str):
        body = data
    else:
        body = json.dumps(data) if data else ''
    sign_str = '%s\n%s\n%s\n%s\n%s\n' % (method, path, timeStamp, nonce_str, body)
    signature = sign(private_key=mch_private_key, sign_str=sign_str)
    authorization = 'WECHATPAY2-SHA256-RSA2048 mchid="%s",nonce_str="%s",signature="%s",timestamp="%s",serial_no="%s"' % (mchid, nonce_str, signature, timeStamp, serial_no)
    return authorization

def sign(private_key, sign_str):
    private_key = load_pem_private_key(data=format_private_key(private_key).encode('UTF-8'), password=None, backend=default_backend())
    message = sign_str.encode('UTF-8')
    signature = private_key.sign(data=message, padding=PKCS1v15(), algorithm=SHA256())
    sign = b64encode(signature).decode('UTF-8').replace('\n', '')
    return sign


得到的结果

{"media_id":"OKJGzKdajrcRAEKsWNOfvXzOn_6lZ4iRa6y9iR0Fsx_xxxxx"}



最后一次编辑于  2021-06-24  
点赞 1
收藏
评论

1 个评论

登录 后发表内容