python支付 Python對接支付寶支付自實現

2021-10-19 21:33:30 字數 4377 閱讀 7811

python

python開發

python語言

python對接支付寶支付自實現

python對接支付寶支付自實現

# -*- coding: utf-8 -*-

import base64

import json

import urllib.parse

from datetime import datetime

import requests

from cryptography.hazmat.backends import default_backend

from cryptography.hazmat.primitives import hashes

from cryptography.hazmat.primitives import serialization

from cryptography.hazmat.primitives.asymmetric import padding

class alipayexception(exception):

def __init__(self, data):

super(alipayexception, self).__init__()

self.data = data

def __str__(self):

return "alipay - {}".format(self.data)

def __unicode__(self):

return u"alipay - {}".format(self.data)

class alipayverifyexception(alipayexception):

def __init__(self, msg, data):

super(alipayverifyexception, self).__init__('alipay verify except - {}:{}'.format(msg, data))

class alipay:

def __init__(self, **kwargs):

:param kwargs:

url: 請求位址

notify_url: 支付寶伺服器主動通知商戶伺服器裡指定的頁面http/https路徑

sign_type: 商戶生成簽名字串所使用的簽名演算法型別,目前支援rsa2和rsa,推薦使用rsa2

self._seller_id = kwargs['seller_id']

self._gateway_url = kwargs['gateway_url']

self._notify_url = kwargs.get('notify_url')

self._sign_type = kwargs.get('sign_type', 'rsa2')

if self._sign_type not in ('rsa', 'rsa2'):

raise exception('alipay sign_type must `rsa` or `rsa2`')

self._charset = 'utf-8'

self._format = 'json'

f.read().encode('utf8'),

none,

default_backend()

with open(kwargs['public_key']) as f:

self._public_key = serialization.load_pem_public_key(

f.read().encode('utf8'),

default_backend()

@property

@property

def seller_id(self):

return self._seller_id

if self._sign_type == 'rsa':

data.encode('utf8'),

padding.pkcs1v15(),

hashes.sha1())

else:

data.encode('utf8'),

padding.pkcs1v15(),

hashes.sha256())

return base64.b64encode(signature).decode('utf8')

def sync_verify(self, method, raw_data):

同步驗籤

:return:

method = method.replace('.', '_') + '_response'

raw_data = raw_data.decode('utf8')

sign_index = raw_data.rfind('sign')

signature = base64.b64decode(raw_data[sign_index + 7: -2])

method_data = raw_data[raw_data.find(method) + len(method) + 2: sign_index - 2]

self._public_key.verify(

signature,

method_data.encode('utf8'),

padding.pkcs1v15(),

hashes.sha256())

def async_verify(self, data):

非同步驗籤

:return:

sign_data = {}

for k, v in data.items():

if k in ('sign', 'sign_type'):

continue

sign_data[k] = v

self._public_key.verify(

base64.b64decode(data['sign']),

'&'.join(['{}={}'.format(item) for item in self.sort_data(sign_data)]).encode('utf8'),

padding.pkcs1v15(),

hashes.sha256())

@staticmethod

def sort_data(data):

return [(k, data[k]) for k in sorted(data.keys())]

def params(self, method, biz_content):

data = ={}'.format(item[0], urllib.parse.quote(item[1])) for item in self.sort_data(data)])

p += '&{}={}}'.format('sign', urllib.parse.quote(sign))

return p

def command(self, method, biz_content):

params = self.params(method, biz_content)

response = requests.get('%s?%s' % (self._gateway_url, params))

response_raw_data = response.content

response_data = response.json()

alipay_response_data = response_data[method.replace('.', '_') + '_response']

if alipay_response_data.get('code', '10000') != '10000':

raise alipayexception(alipay_response_data)

self.sync_verify(method, response_raw_data)

return alipay_response_data

if __name__ == '__main__':

alipay = alipay(**{

'seller_id': '...',

'gateway_url': '',

'notify_url': '...',

'public_key': 'path to public_key.pem'

biz_content = {

'out_trade_no': "111",

'total_amount': 0.01,

'subject': "test",

alipay.command('alipay.trade.precreate', biz_content)

python微信支付 微信支付 python版

需求 說明坑 簽名校驗通過時還是提示簽名錯誤,可能時候商戶號key配置的問題了,重置一下key,你可以繼續使用原來的key來重置 需要的id和key wpc 複製 流程簡介 那麼開發思路便是一步步回朔了.1.獲取code buy click function 複製 2.獲取openid classm...

python實現支付功能

支付寶開發者公鑰 支付寶生成 alipay public key os.path.join base dir,utils paycenter alipay certs alipay public key alipay public key obj pub openssl.crypto.load pu...

python 支付寶支付接入流程

需要生成自己的服務端的私鑰和公鑰,現在支付寶支援的加密方式為sha256,sha1,推薦使用sha256.支付寶提供了生成秘鑰的方法和步驟 開啟括號中的鏈結,即可看到詳細的生成秘鑰的方法和步驟。公鑰私鑰生成完之後,要將公鑰上傳到支付寶金鑰設定中。將支付寶的公鑰copy到本地,將自己的公鑰私鑰和支付寶...