Python docking Alipay payment interface

The project uses django to connect to the Alipay website payment interface

Preparation

1. APPID
2. Alipay public key-application public key-application private key
3. Install Alipay platform python SDK
pip install python-alipay-sdk --upgrade (unofficial)

Call the payment interface

The general payment process is:
the front end sends an ajax post request to the back end, carrying the order id;

After some logical processing, we call the Alipay computer website payment interface, and Alipay finally returns the address of the payment page according to our request parameters. At this point, we got the url of the payment page, we need to pass it to the front end

from alipay import AliPay
class PayView(View):
    '''订单支付'''
    def post(self,request):
        #当用户点击去付款后,经过前面的判断后,
        # 进入下面的业务处理:使用python sdk调用支付宝的支付接口
        app_private_key_string = '-----BEGIN PRIVATE KEY-----\n' + '你的应用私钥' + '\n-----END PRIVATE KEY-----'
        alipay_public_key_string = '-----BEGIN PUBLIC KEY-----\n' + '你的支付宝公钥' + '\n-----END PUBLIC KEY-----'
        #初始化
        alipay = AliPay(
            appid="2016102500754813", #应用id
            app_notify_url=None,  #默认回调url; 支付宝后台完成支付的时候异步通知到商户的后台服务器的URL地址
            app_private_key_string=app_private_key_string,
            alipay_public_key_string=alipay_public_key_string,
            debug=True
        )
        #调用支付接口,电脑网站支付
        order_string = alipay.api_alipay_trade_page_pay(  # 调用支付宝接口,立刻返回 部分支付页面的url,我们需要引导用户去点击
            subject="测试订单",
            out_trade_no=request.POST.get('order_id',''),
            total_amount=100,
            return_url='https://www.baidu.com',  # 同步访问,支付成功后支付页面要跳转到哪个页面  django网站地址,并会传递参数,告诉网站用户支付的结果
            notify_url=None
        )
        # 支付宝处理完后 最终返回支付页面的地址,我们需要引导用户进入该地址页面
        # 将调用接口返回的url与固定url链接起来,就是完整的支付页面url
        pay_url = "https://openapi.alipaydev.com/gateway.do?" + order_string
        return JsonResponse({
    
    'pay_url':pay_url,'status':"SUCCESS"})

The front-end ajax gets the back-end response and enters the corresponding callback function, gets the address of the payment page, and jumps to the payment page;
since we are in a sandbox environment, we can only query the transaction results through the api_alipay_trade_query interface, so after the jump statement, we need to Send an ajax request to the server to query the transaction result
insert image description here

Front-end code:

success: function (result, text_status) {
    
      {
    
    # 成功以后的回调 返回字面量对象,描述状态的字符串 #}
                console.log(result, typeof result);
                console.log(text_status);
                if (result['status'] == 'SUCCESS') {
    
    
                    //引导用户到支付页面
                     window.open(result['pay_url']);
                    //浏览器访问 /order/check ,获取支付交易的结果
                    $.post({
    
    % url 'check' %},{
    
    
                        'order_id': order_id,
                'csrfmiddlewaretoken': '{
    
    { csrf_token }}'
                    },function (data) {
    
    
                        if (data["res"] == 1){
    
    
                            alert(data['msg']);
                            window.open('https://www.baidu.com');
{
    
    #                            location.reload();//刷新页面#}
                        }else{
    
    
                            alert(data['msg']);
                        }

                    });

                }
                else {
    
    
                    alert(result['ajax_delete_error_msg']);
                }
            }

In the view of querying transaction results, we also need to initialize; since the user’s payment time is uncertain, we need to continuously request the Alipay query interface in While, and return or continue the loop according to the transaction status

class CheckView(View):
    def post(self,request):
        '''查看订单支付的结果'''
        app_private_key_string = '-----BEGIN PRIVATE KEY-----\n' + '你的用私钥' + '\n-----END PRIVATE KEY-----'
        alipay_public_key_string = '-----BEGIN PUBLIC KEY-----\n' + '你的应用公钥' + '\n-----END PUBLIC KEY-----'
        # 初始化
        alipay = AliPay(
            appid="2016102500754813",  # 应用id
            app_notify_url=None,  # 默认回调url; 支付宝后台完成支付的时候异步通知到商户的后台服务器的URL地址
            app_private_key_string=app_private_key_string,
            alipay_public_key_string=alipay_public_key_string,
            debug=True
        )


        while True:
            # 调用支付宝交易查询接口,返回交易结果 字典类型
            response = alipay.api_alipay_trade_query(
                out_trade_no=request.POST.get('order_id', '')   #订单号,必须是支付了的订单后,与上面的pay订单号一致
            )
            code = response.get('code')
            print(response)
            if code == '10000' and response.get('trade_status') == "TRASW_SUCCESS":
                #支付成功
                return JsonResponse({
    
    'res':1,'msg':'支付成功啦!'})
            elif code=="40004" or code=="10000" and response.get('trade_status') == 'WAIT_BUYER_PAY':
                #等待买家付款
                import time
                time.sleep(5)
                continue
            else:
                #支付出错
                return JsonResponse({
    
    'res':1,'msg':response})


Guess you like

Origin blog.csdn.net/qq_36291294/article/details/106449300