支付宝app支付和h5支付 python代码实现

支付宝app支付和h5支付

使用模块 pip install python-alipay-sdk==1.10.1

from alipay import AliPay

def ali():
    ali_pay = AliPay(
        appid=settings.ALI_APP_ID,
        app_notify_url=settings.ALI_NOTIFY_URL,  # 默认回调url
        app_private_key_string=settings.APP_PRIVATE_KEY_STRING,
        alipay_public_key_string=settings.ALI_PAY_PUBLIC_KEY_STRING,
        sign_type="RSA2",
        debug=False,
    )
    return ali_pay


class AliPayViewSet(viewsets.ViewSet):
    permission_classes = (IsAuthenticated,)
	
    #app支付超简单,返回order_string给前端就ok了
    @list_route(methods=["POST"])
    def app_pay(self, request, *args, **kwargs):
        try:
            order_sn = "%s%s%s" % (request.user.id, datetime.datetime.now().strftime('%Y%m%d%H%M%S'),
                                   random.randint(1, 99))
            ali_pay = ali()
            order_string = ali_pay.api_alipay_trade_app_pay(
                out_trade_no=order_sn,
                total_amount=0.01,
                subject="测试", # 商品说明
            )
            return Response({"status": 1, "data": {"orderstring": order_string}})
        except Exception as e:
            return Response({"status": 0, "errormsg": e})

        
    #h5支付,官方文档https://docs.open.alipay.com/203/105285
    #需要转成form表单
    #如上图所示,用户在商户的H5网站下单支付后,商户系统按照手机网站支付接口alipay.trade.wap.payAPI的参数规范生成订单数据,然后在前端页面通过Form表单的形式请求到支付宝。
    @list_route(methods=["POST"])
    def h5_pay(self, request, *args, **kwargs):
        try:
            order_sn = "%s%s%s" % (request.user.id, datetime.datetime.now().strftime('%Y%m%d%H%M%S'),
                                   random.randint(1, 99))
            ali_pay = ali()
            order_string = ali_pay.api_alipay_trade_wap_pay(
                out_trade_no=order_sn,
                total_amount=0.01,
                subject="测试",  # 商品说明
                body="123",
                timeout_express="90m",
                product_code="QUICK_WAP_WAY",
            )
            pay_url = "https://openapi.alipay.com/gateway.do?{}".format(order_string)
            params = dict()
            str_list = order_string.split("&")
            for s in str_list:
                k, v = s.split("=")
                params[k] = v
            form = build_form(pay_url, params)
            return Response({"status": 1, "data": {"form": form}})
        except Exception as e:
            return Response({"status": 0, "errormsg": e})

	#转换form表单的方法
   def build_form(url, params):
    form = "<form name=\"punchout_form\" method=\"post\" action=\""
    form += url
    form += "\">\n"
    if params:
        for k, v in params.items():
            if not v:
                continue
            form += "<input type=\"hidden\" name=\""
            form += k
            form += "\" value=\""
            form += v.replace("\"", "&quot;")
            form += "\">\n"
    form += "<input type=\"submit\" value=\"立即支付\" style=\"display:none\" >\n"
    form += "</form>\n"
    form += "<script>document.forms[0].submit();</script>"
    return form

前端代码

    $('.js-order-pay').click(function () {
        var _msg = $(this).attr('data-message')
        var auth = 'JWT ' + localStorage.getItem('token')
        if (_msg == '1') {
            console.log(1111111111)
            //支付宝
            var formData = {
                total_fee: 0.01,
            }
            $.ajax({
                type: "POST",
                url: '/api/pay/ali_pay/h5_pay/',
                data: JSON.stringify(formData),
                dataType: "json",
                contentType: "application/json",
                processData: false,
                headers: {"X-CSRFToken": getCookie("csrftoken")},
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("Authorization", auth);
                },
                success: function (data) {
                    if (data.status == 1) {
                        var div = document.createElement('div');
                        div.innerHTML = data.data.form
                        document.body.appendChild(div);
                        var subForm = document.getElementsByTagName("form")[0];
                        subForm.submit();
                    } else {
                        alert(data.errormsg)
                    }
                },
            })
posted @ 2019-12-16 19:16  robertzhou  阅读(2078)  评论(1编辑  收藏  举报