网上搜【Python支付宝】,搜到的结果,除了发布的人不一样之外,内容一模一样。拿过来用的时候老是失败,要么合作身份者ID不正确,要么签名验证出错,修改了几次ID,加密也没有问题。
不知道是我复制的有问题,还是这demo本身就有问题。反正我就是调不出支付页面。后来发现要加密的数据在处理上出现了问题。真是醉了啊,所有人都复制的好起劲啊???
最后复制粘贴,修修改改。。
代码:实现的是即时到账接口
1、调起支付页面方法
def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Returns a bytestring version of 's', encoded as specified in 'encoding'.
If strings_only is True, don't convert (some) non-string-like objects.
"""
if strings_only and isinstance(s, (types.NoneType, int)):
return s
if not isinstance(s, basestring):
try:
return str(s)
except UnicodeEncodeError:
if isinstance(s, Exception):
# An Exception subclass containing non-ASCII data that doesn't
# know how to print itself properly. We shouldn't raise a
# further exception.
return ' '.join([smart_str(arg, encoding, strings_only,
errors) for arg in s])
return str(s).encode(encoding, errors)
elif isinstance(s, str):
return s.encode(encoding, errors)
elif s and encoding != 'utf-8':
return s.decode('utf-8', errors).encode(encoding, errors)
else:
return s
# 对数组排序并除去数组中的空值和签名参数
# 返回数组和链接串
def params_filter(params):
prestr = ''
params = OrderedDict({k: v for k, v in params.items() if v != ''})
params = OrderedDict(sorted(params.items(), key=lambda t: t[0]))
print(params)
for k in params:
prestr += k + '=' + params[k] + '&'
prestr = prestr[:-1]
return params, prestr
# 生成签名结果
def build_mysign(prestr, key, sign_type='MD5'):
if sign_type == 'MD5':
m = hashlib.md5()
m.update((prestr + key).encode("utf-8"))
encodeStr = m.hexdigest()
return encodeStr
return ''
# 网关地址
_GATEWAY = 'https://mapi.alipay.com/gateway.do?'
def create_direct_pay_by_user(tn, subject, body, total_fee):
params = OrderedDict()
params['service'] = 'create_direct_pay_by_user'
params['payment_type'] = '1'
# 获取配置文件
params['partner'] = Settings.ALIPAY_PARTNER
params['seller_email'] = Settings.ALIPAY_SELLER_EMAIL
params['return_url'] = Settings.ALIPAY_RETURN_URL
params['notify_url'] = Settings.ALIPAY_NOTIFY_URL
params['_input_charset'] = Settings.ALIPAY_INPUT_CHARSET
params['show_url'] = Settings.ALIPAY_SHOW_URL
# 从订单数据中动态获取到的必填参数
params['out_trade_no'] = tn # 请与贵网站订单系统中的唯一订单号匹配
params['subject'] = subject # 订单名称,显示在支付宝收银台里的“商品名称”里,显示在支付宝的交易管理的“商品名称”的列表里。
params['body'] = body # 订单描述、订单详细、订单备注,显示在支付宝收银台里的“商品描述”里
params['total_fee'] = total_fee # 订单总金额,显示在支付宝收银台里的“应付总额”里
# 扩展功能参数——网银提前
if bank=='alipay' or bank=='':
params['paymethod'] = 'directPay' # 支付方式,四个值可选:bankPay(网银); cartoon(卡通); directPay(余额); CASH(网点支付)
params['defaultbank'] = '' # 支付宝支付,这个为空
else:
params['paymethod'] = 'bankPay' # 默认支付方式,四个值可选:bankPay(网银); cartoon(卡通); directPay(余额); CASH(网点支付)
params['defaultbank'] = bank # 默认网银代号,代号列表见http://club.alipay.com/read.php?tid=8681379
params, prestr = params_filter(params)
params['sign'] = build_mysign(prestr, Settings.ALIPAY_KEY, Settings.ALIPAY_SIGN_TYPE)
params['sign_type'] = Settings.ALIPAY_SIGN_TYPE
return _GATEWAY + urlencode(params)
def notify_verify(post):
# 初级验证--签名
_,prestr = params_filter(post)
mysign = build_mysign(prestr, settings.ALIPAY_KEY, settings.ALIPAY_SIGN_TYPE)
if mysign != post.get('sign'):
return False
# 二级验证--查询支付宝服务器此条信息是否有效
params = {}
params['partner'] = settings.ALIPAY_PARTNER
params['notify_id'] = post.get('notify_id')
gateway = 'https://mapi.alipay.com/gateway.do?service=notify_verify&'
verify_result = urlopen(gateway, urlencode(params)).read()
if verify_result.lower().strip() == 'true':
return True
return False
2、config.py
class Settings:
# 安全检验码,以数字和字母组成的32位字符
ALIPAY_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
ALIPAY_INPUT_CHARSET = 'utf-8'
# 合作身份者ID,以2088开头的16位纯数字
ALIPAY_PARTNER = 'xxxxxxxxxxxxxxxx'
# 签约支付宝账号或卖家支付宝帐户
ALIPAY_SELLER_EMAIL = 'ls@abc.com'
ALIPAY_SIGN_TYPE = 'MD5'
# 付完款后跳转的页面(同步通知) 要用 http://格式的完整路径,不允许加?id=123这类自定义参数
ALIPAY_RETURN_URL='http://www.xxx.com/alipay/return/'
# 交易过程中服务器异步通知的页面 要用 http://格式的完整路径,不允许加?id=123这类自定义参数
ALIPAY_NOTIFY_URL='http://www.xxx.com/alipay/notify/'
3、view.py
url = create_direct_pay_by_user(order_no, "名称", "描述", total_cost)
# 去支付页面
return HttpResponseRedirect(url)
#alipay异步通知
@csrf_exempt
def alipay_notify_url (request):
if request.method == 'POST':
if notify_verify (request.POST):
#商户网站订单号
tn = request.POST.get('out_trade_no')
#支付宝单号
trade_no=request.POST.get('trade_no')
#返回支付状态
trade_status = request.POST.get('trade_status')
cb = cBill.objects.get(pk=tn)
if trade_status == 'TRADE_SUCCESS':
cb.exe()
log=Log(operation='notify1_'+trade_status+'_'+trade_no)
log.save()
return HttpResponse("success")
else:
#写入日志
log=Log(operation='notify2_'+trade_status+'_'+trade_no)
log.save()
return HttpResponse ("success")
else:
#黑客攻击
log=Log(operation='hack_notify_'+trade_status+'_'+trade_no+'_'+'out_trade_no')
log.save()
return HttpResponse ("fail")
#同步通知
def alipay_return_url (request):
if notify_verify (request.GET):
tn = request.GET.get('out_trade_no')
trade_no = request.GET.get('trade_no')
trade_status = request.GET.get('trade_status')
cb = cBill.objects.get(pk=tn)
log=Log(operation='return_'+trade_status+'_'+trade_no)
log.save()
return HttpResponseRedirect ("/public/verify/"+tn)
else:
#错误或者黑客攻击
log=Log(operation='err_return_'+trade_status+'_'+trade_no)
log.save()
return HttpResponseRedirect ("/")
#外部跳转回来的链接session可能丢失,无法再进入系统。
#客户可能通过xxx.com操作,但是支付宝只能返回www.xxx.com,域名不同,session丢失。
def verify(request,cbid):
try:
cb=cBill.objects.get(id=cbid)
#如果订单时间距现在超过1天,跳转到错误页面!
#避免网站信息流失
return render_to_response('public_verify.html',{'cb':cb},RequestContext(request))
except ObjectDoesNotExist:
return HttpResponseRedirect("/err/no_object")
PS:跟在网上搜到的,主要就是修改了【对数组排序并除去数组中的空值和签名参数和返回数组和链接串】方法