Django实现支付宝APP支付

支付宝 老版本的 移动支付升级为app支付:https://docs.open.alipay.com/204/106541

支付宝 app支付 沙箱环境:https://openhome.alipay.com/platform/appDaily.htm

支付宝提供的RSA密钥生成工具:https://docs.open.alipay.com/291/105971


requirement:

python 2.7.15
Django 1.11.13
python-alipay-sdk 1.7.1
windows 10

因为支付宝官方并没有提供python语言的sdk,安装第三方的依赖(python-alipay-sdk)。

#installation
pip install python-alipay-sdk --upgrade

依赖包具体可参考github:https://github.com/fzlee/alipay

前置准备:
PKCS1 非java语言使用
PKCS8 java语言使用

OpenSSL> genrsa -out pkcs1_pri_key.pem 2048 # 生成pkcs1私钥
OpenSSL> rsa -in pkcs1_pri_key.pem -pubout -out pub_key.pem # 导出公钥
OpenSSL> pkcs8 -topk8 -inform PEM -in pkcs1_pri_key.pem -outform pem -nocrypt -out pkcs8_pri_key.pem # pkcs1私钥 转换为 pkcs8 私钥
OpenSSL> exit

服务器端需配置的参数有:APPID、merchant_private_key(商户私钥)、alipay_public_key(阿里公钥)

蚂蚁金服开放平台需要配置的参数有:merchant_publick_key(商户公钥)

注:私钥加密、公钥解密。

python代码里的密钥文件格式

阿里公钥格式(alipay_public.pem):

-----BEGIN PUBLIC KEY-----  
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn4kjzwfX92YLnuiSqH0x1F29Ftk4uSM3ltcthAaerbq3gTVl+zmjL2NKJ2iDWOfjmCyW1TDejxy/K12/vRPdabJBCoKv3KdS5Mz5r0aCWtXj1TZ9k8rH3vn/rbLL7NVJQziJF2xbeqGxtjJHVgElO5BzyF6L+X7VGAjkUYPqMuklQwsW+eahs3UYQE1qOqtL458v9gF+ITPtUMGmjHV5cPW8o/EcszsHKQGzIYM1y2waVsP5YtQ0+NQJvP1AK6rTm3oGi4uqoow9uGyIrCL9pgYBQSqDDwLAMRrE7MQESOWOCXTjHxd/OdkmdNv/3uMwXMRa/6ctlte9SbkjpN1HSwIDAQAB  
-----END PUBLIC KEY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O8QUvSefyKiwRQoMUnwtsFdAfddb9HZeZAoGAZnxv6uYwn2EWmafas4ZVY6NJ2Q3pVPN6fgwktD0Rs3re0vQ2qi/cgBZa/pRAEcZ9/LVGenI3xN1gPMOYn35tonAqhWMIwv3nF17j3aTQ/41bunW2eABg9Id49MaJfoTZER9oLqO19+IopQuiHORrB+GpbblHLC+YTdbT5Fdcp2UCgYAZBrYiq2Kz0eFg1a3dlgc9IrMaKtJtN3+Gr/lKwWb1MmDseMfw/lJtkrwAu7+NYsrAl7hnBrr9MiWwJgnwVqLwicgG+hv68l7UcCu/GorBO1AuzjyFUslzmT4dgTvgTgOFS6Ehj/UVxlxZ3+9VWN7yFGeI2SLLrxqyAJYwEWgZMQKBgD+lPRXl1jNYKnjyfZAU1rZaE+4OHdgMJCNATi1WIa4kH7prTyqOp61UWBFIwfv8x5p4F0bh1NF5PAnApSqLAQULIwIDM2V/Gfiif+danvN5tYY0ezbzeROfwVOzLxrNHo9AqbHMREzg9m9Hppv9nKVHzEWbemdcfxkIoOtOMcjA  
-----END RSA PRIVATE KEY-----

python代码-views.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import time
from json import dumps
from django.http import HttpResponse
from alipay import AliPay
from django.conf import settings
from django.utils.encoding import smart_str

notify_url = "https://xxxxx:8003/api/aliapy_back_url/"  # 支付成功回掉的地址,在支付宝中设置


# @csrf_exempt
def ali():
    # 设置自己的私钥,将自己的公钥放在支付宝上
    # 设置公钥和私钥的地址,文件上下两行begin和end是必须的,公钥就放在第二行。
    merchant_private_key_path = settings.BASE_DIR + '/testpay/static/merchant_private_pkcs1_2048.pem'  
    # 设置支付宝公钥,我用的是sha1加密方式的pem文件
    alipay_public_key_path = settings.BASE_DIR + '/testpay/static/alikeys/alipay_public.pem'
    app_private_key_string = open(merchant_private_key_path).read()
    alipay_public_key_string = open(alipay_public_key_path).read()
    app_id = "2016091500111111"  # 复制来自支付宝生成的id

    alipay = AliPay(
        appid=app_id,
        app_notify_url=notify_url,  # 默认回调url
        app_private_key_string=app_private_key_string,
        # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
        alipay_public_key_string=alipay_public_key_string,  
        sign_type="RSA2",  # RSA 或者 RSA2
        debug=False  # 默认False
    )
    return alipay


# 充值生成订单
# @csrf_exempt
def recharge(request):
    alipay = ali()
    ret = {'code': 200, 'msg': '请求成功!', 'order_string': ''}
    try:
        user_id = request.POST.get('user_id')
        money = request.POST.get('money')
        # 生成订单
        order_string = alipay.api_alipay_trade_app_pay(
            out_trade_no="LB" + str(int(round(time.time()))),  # 商户订单号
            total_amount=money,
            subject="liuhuabi",  # 商品简单描述
            notify_url=notify_url  # 可选, 不填则使用默认notify url
        )
        ret['code'] = 200
        print order_string
        ret['order_string'] = order_string
        ret['msg'] = "请求成功!"
    except Exception, e:
        print(e)
        ret['code'] = 1010
        ret['msg'] = str(e)
        print(str(e))
    return HttpResponse(dumps(ret))  # 返回订单的生成的订单码


# @csrf_exempt
def aliapy_back_url(request):
    import sys
    reload(sys)
    sys.setdefaultencoding('utf8')

    alipay = ali()
    if request.method == "POST":
        # 检测是否支付成功
        # 去请求体中获取所有返回的数据:状态/订单号
        # import urlparse
        # body_str = request.body.decode('utf-8')
        # print(body_str)
        # body_str = body_str.encode("latin1")
        # post_data = urlparse.parse_qs(body_str)

        post_data, prestr = params_filter_alipay(request.POST)
        post_dict = post_data
        sign = request.POST.get('sign')
        status = alipay.verify(post_dict, sign)
        if status:
            print(post_dict['trade_status'])
            print(post_dict['out_trade_no'])
            return HttpResponse('success')
        else:
            return HttpResponse("fail")
    else:
        params = request.GET.dict()
        sign = params.pop('sign', None)
        status = alipay.verify(params, sign)
        print('GET验证', status)
        # return HttpResponse('支付成功')

def params_filter_alipay(params):
    ks = params.keys()
    ks.sort()
    newparams = {}
    prestr = ''
    for k in ks:
        v = params[k]
        k = smart_str(k, settings.ALIPAY_INPUT_CHARSET)
        if k not in ('sign', 'sign_type') and v != '':
            newparams[k] = smart_str(v, settings.ALIPAY_INPUT_CHARSET)
            print(k, newparams[k])
            prestr += '%s=%s&' % (k, newparams[k])
    prestr = prestr[:-1]
    return newparams, prestr

python代码-urls.py

from testpay import views  
urlpatterns = [  
    url(r'^admin/', admin.site.urls),  
    url(r"^alipay/", views.recharge),  
    url(r"^aliapy_back_url/", views.aliapy_back_url),  
]

参考链接 : Django对接支付宝APP支付问题 django实现支付宝付款功能

  • qq_43638135
    妲己再美究为妃: 博主没有想过自己接一些私活干吗?我现在还没毕业,但是我也确实听说外挂市场自动化游戏脚本市场挺火热的,并且报酬也很丰厚,但是具体的我也不是很清楚,求解答。 (1个月前 #47楼) 查看回复(2) 举报 回复
    22