支付宝沙箱环境

  • 登录蚂蚁金服开放平台

  • 创建沙箱环境

  • 配置秘钥(应用公钥,应用私钥,支付宝公钥)

    点击秘钥生成文档

    1,到上面的文档中下载秘钥工具

    2,解压

    3,生成秘钥和公钥

    4,把公钥配置到 沙箱环境中

  • 安装官方SDK

支付宝官方在2018年5月23日,发布了一个Python版的SDK(公测版)。

我们可以通过“pip”命令进行安装。

1
2
3
4
5
#安装加密依赖包
pip install pycrypto

#安装alipay-sdk-python。
pip install alipay-sdk-python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 支付宝配置文件

# APPID
# 沙箱APPID,生产环境须更改为应用APPID。
ALIPAY_APPID = "2016092200571332"

# 网关
# 沙箱网关,生产环境须更改为正式网关。
ALIPAY_URL = "https://openapi.alipaydev.com/gateway.do"
# 正式网关,开发环境勿使用。
# ALIPAY_URL = "https://openapi.alipay.com/gateway.do"

# 回调通知地址
# 如果只可以内网访问开发服务器
ALIPAY_NOTIFY_URL = "http://127.0.0.1:8000/order/pay_result/"
# 如果生产环境或外网可以访问开发服务器
# ALIPAY_NOTIFY_URL = "http://1.203.45.678:8000/order/pay_result/"

# 支付后的跳转地址
ALIPAY_RETURN_URL = 'http://127.0.0.1:8000/order/pay_success/'

# 应用私钥
APP_PRIVATE_KEY_PATH = os.path.join(BASE_DIR, 'keys/app_private_key.txt')
# 支付宝公钥
ALIPAY_PUBLIC_KEY_PATH = os.path.join(BASE_DIR, 'keys/alipay_public_key.txt')
  • 在项目中创建keys目录,然后把私钥和支付宝公钥放进来

    1,在项目中创建keys目录里面放入秘钥文件

    2,创建app_private_key.txt放入秘钥,加开始和结束的标记

    1
    2
    3
    -----BEGIN RSA PRIVATE KEY-----
    MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvmSUPpj/82btbdmmHJ7vJf8KKwsD9Xt8oA0+KF0G04NQzVqS6p+6gF520eDlZC7xmu18A74txlShLBqhpUEEM4yL4ucncdkHiUyqUBjvZNjHXV42l2dXtYiaSV/I39vlz5nTfAmDHB+J8ImW6O29Xvslid1U8gjUEtZ4T1aYsBGzts5At6JnbjwTQhMUGVlH2/7o4ZAe6yzscLnrDzcUHml33ZJ1eRA6YGMokq7SgXbnU3KnL81s25SQ/cypwB1s1NGV4wF3nYSCmK6XxhRF0cf7zPa2rpjgnOI8sAbzbvB/bBZjUDz+eg2dFkoKjQgOE+GTrXgyKBVlJ8akKPwFwQIDAQAB
    -----END RSA PRIVATE KEY-----

    3,创建 alipay_public_key.txt 放入秘钥,加开始和结束的标记

    1
    2
    3
    -----BEGIN PUBLIC KEY-----
    ....
    -----END PUBLIC KEY-----
  • 根据回调地址的配置,去配置响应的路由和视图函数

1
2
3
4
5
# 支付的回调地址 order/pay_result/
url(r'^order/pay_result/',OrderViews.myhome_pay_result,name="myhome_pay_result"),
# 支付宝回调地址
def myhome_pay_result(request):
pass
  • 配置第三方包utils,然后创建pay.py文件并输入
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
from datetime import datetime
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
from urllib.parse import quote_plus
from urllib.parse import urlparse, parse_qs
from base64 import decodebytes, encodebytes
import json

class AliPay(object):
"""
支付宝支付接口(PC端支付接口)
"""

def __init__(self, appid, app_notify_url, app_private_key_path,
alipay_public_key_path, return_url, debug=False):
self.appid = appid
self.app_notify_url = app_notify_url
self.app_private_key_path = app_private_key_path
self.app_private_key = None
self.return_url = return_url
with open(self.app_private_key_path) as fp:
self.app_private_key = RSA.importKey(fp.read())
self.alipay_public_key_path = alipay_public_key_path
with open(self.alipay_public_key_path) as fp:
self.alipay_public_key = RSA.importKey(fp.read())

if debug is True:
self.__gateway = "https://openapi.alipaydev.com/gateway.do"
else:
self.__gateway = "https://openapi.alipay.com/gateway.do"

def direct_pay(self, subject, out_trade_no, total_amount, return_url=None, **kwargs):
biz_content = {
"subject": subject,
"out_trade_no": out_trade_no,
"total_amount": total_amount,
"product_code": "FAST_INSTANT_TRADE_PAY",
# "qr_pay_mode":4
}

biz_content.update(kwargs)
data = self.build_body("alipay.trade.page.pay", biz_content, self.return_url)
return self.sign_data(data)

def build_body(self, method, biz_content, return_url=None):
data = {
"app_id": self.appid,
"method": method,
"charset": "utf-8",
"sign_type": "RSA2",
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"version": "1.0",
"biz_content": biz_content
}

if return_url is not None:
data["notify_url"] = self.app_notify_url
data["return_url"] = self.return_url

return data

def sign_data(self, data):
data.pop("sign", None)
# 排序后的字符串
unsigned_items = self.ordered_data(data)
unsigned_string = "&".join("{0}={1}".format(k, v) for k, v in unsigned_items)
sign = self.sign(unsigned_string.encode("utf-8"))
# ordered_items = self.ordered_data(data)
quoted_string = "&".join("{0}={1}".format(k, quote_plus(v)) for k, v in unsigned_items)

# 获得最终的订单信息字符串
signed_string = quoted_string + "&sign=" + quote_plus(sign)
return signed_string

def ordered_data(self, data):
complex_keys = []
for key, value in data.items():
if isinstance(value, dict):
complex_keys.append(key)

# 将字典类型的数据dump出来
for key in complex_keys:
data[key] = json.dumps(data[key], separators=(',', ':'))

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

def sign(self, unsigned_string):
# 开始计算签名
key = self.app_private_key
signer = PKCS1_v1_5.new(key)
signature = signer.sign(SHA256.new(unsigned_string))
# base64 编码,转换为unicode表示并移除回车
sign = encodebytes(signature).decode("utf8").replace("\n", "")
return sign

def _verify(self, raw_content, signature):
# 开始计算签名
key = self.alipay_public_key
signer = PKCS1_v1_5.new(key)
digest = SHA256.new()
digest.update(raw_content.encode("utf8"))
if signer.verify(digest, decodebytes(signature.encode("utf8"))):
return True
return False

def verify(self, data, signature):
if "sign_type" in data:
sign_type = data.pop("sign_type")
# 排序后的字符串
unsigned_items = self.ordered_data(data)
message = "&".join(u"{}={}".format(k, v) for k, v in unsigned_items)
return self._verify(message, signature)
  • 在视图函数中 封装一个方法 去实例化alipay对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from buydemo import settings
from utils.pay import AliPay

# AliPay 对象实例化
def Get_AliPay_Object():
alipay = AliPay(
appid=settings.ALIPAY_APPID,# APPID (沙箱应用)
app_notify_url=settings.ALIPAY_NOTIFY_URL, # 回调通知地址
return_url=settings.ALIPAY_RETURN_URL,# 支付完成后的跳转地址
app_private_key_path=settings.APP_PRIVATE_KEY_PATH, # 应用私钥
alipay_public_key_path=settings.ALIPAY_PUBLIC_KEY_PATH, # 支付宝公钥
debug=True, # 默认False,
)
return alipay
  • 生成支付的url,重定向到支付页面
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 订单支付
def myhome_order_pay(request):
# 接收订单号
orderid = request.GET.get('orderid')
# 获取订单对象
order = Order.objects.get(id=orderid)

# 获取支付对象
alipay = Get_AliPay_Object()

# 生成支付的url
query_params = alipay.direct_pay(
subject="魅族旗舰官网", # 商品简单描述
out_trade_no = orderid,# 用户购买的商品订单号
total_amount = order.totalprice, # 交易金额(单位: 元 保留俩位小数)
)

# 支付宝网关地址(沙箱应用)
pay_url = settings.ALIPAY_URL+"?{0}".format(query_params)
# 页面重定向到支付页面
return redirect(pay_url)
  • 验证回调,成功后修改订单状态
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# 支付宝回调地址
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def myhome_pay_result(request):
# 获取对象
alipay = Get_AliPay_Object()
if request.method == "POST":
# 检测是否支付成功
# 去请求体中获取所有返回的数据:状态/订单号
from urllib.parse import parse_qs
# name&age=123....
body_str = request.body.decode('utf-8')
post_data = parse_qs(body_str)

post_dict = {}
for k, v in post_data.items():
post_dict[k] = v[0]

sign = post_dict.pop('sign', None)
status = alipay.verify(post_dict, sign)
print('------------------开始------------------')
print('POST验证', status)
print(post_dict)
out_trade_no = post_dict['out_trade_no']

# 修改订单状态
Order.objects.filter(id=out_trade_no).update(status=1)
print('------------------结束------------------')
# 修改订单状态:获取订单号
return HttpResponse('POST返回')
else:
params = request.GET.dict()
sign = params.pop('sign', None)
status = alipay.verify(params, sign)
print('==================开始==================')
print('GET验证', status)
print('==================结束==================')
return HttpResponse('<script>alert("支付成功");location.href="/center/order/"</script>')


from web import settings
from utils.pay import AliPay

# AliPay 对象实例化
def Get_AliPay_Object():
alipay = AliPay(
appid=settings.ALIPAY_APPID,# APPID (沙箱应用)
app_notify_url=settings.ALIPAY_NOTIFY_URL, # 回调通知地址
return_url=settings.ALIPAY_NOTIFY_URL,# 支付完成后的跳转地址
app_private_key_path=settings.APP_PRIVATE_KEY_PATH, # 应用私钥
alipay_public_key_path=settings.ALIPAY_PUBLIC_KEY_PATH, # 支付宝公钥
debug=True, # 默认False,
)
return alipay