Python Django 支付寶 掃碼支付

安裝python-alipay-sdk html

pip install python-alipay-sdk --upgrade
pip install crypto

 若是是python 2.7安裝0.6.4這個版本前端

pip install python-alipay-sdk==1.5.0python

原理介紹:jquery

  1.進行祕鑰配置,由於傳輸的數據必需要進行簽名加密,ubuntu內置命令openssl能夠生成私鑰,根據私鑰生成公鑰django

  openssl
  OpenSSL> genrsa -out app_private_key.pem   2048  # 私鑰 2048對應的是rsa加密時候的複雜程度,即rsa2
  OpenSSL> rsa -in app_private_key.pem -pubout -out app_public_key.pem # 導出公鑰
  OpenSSL> exit

  2.cat app_publict_key.pem 查看公鑰的內容json

  將-----BEGIN PUBLIC KEY-----和-----END PUBLIC KEY-----中間的內容保存在支付寶的用戶配置中(沙箱或者正式)ubuntu

       https://openhome.alipay.com/platform/appDaily.htm?tab=infoapi

  3.配置好公鑰後,支付寶會生成公鑰,將公鑰的內容複製保存到一個文本文件中(alipay_pubilc_key.pem),注意須要在文本的首尾添加標記位(-----BEGIN   PUBLIC KEY-----和-----END PUBLIC KEY-----) 架構

  4.將剛剛生成的私鑰app_private_key.pem和支付寶公鑰alipay_public_key.pem放到咱們的項目目錄中app

  5.使用支付寶 python包的初始化

  6.調用支付接口

  https://docs.open.alipay.com/270/alipay.trade.page.pay/

  7.獲取支付結果接口

  https://docs.open.alipay.com/api_1/alipay.trade.query

代碼部分:

1.整個項目架構

index.html代碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="static/js/jquery-1.4.2.min.js"></script>
    <script>
        $(function () {
            $('#btn').click(function () {
                var order_id = "20180105002";
                var req_data = {
                    order_id: order_id,
                    csrfmiddlewaretoken: "{{ csrf_token }}"
                };
                $.post("/pay/", req_data, function (data) {
                    window.open(data.url)
                });
                $.get("/check_pay/?order_id=" + order_id, function (data) {
                    if (0 == data.code) {
                        // 支付成功
                        alert("支付成功");
                        location.reload();
                    } else {
                        alert(data.message)
                    }
                })
            })
        })
    </script>
</head>
<body>
<input type="button" id="btn" value="支付">
</body>
</html>

2.AppTest.views.py代碼

#coding:utf-8
from django.shortcuts import render

from django.shortcuts import render
from django.http import JsonResponse
from alipay import AliPay
import os
from django.conf import settings


def index(request):
    return render(request, "index.html",locals())


def pay(request):
    order_id = request.POST.get("order_id")
    # 建立用於進行支付寶支付的工具對象
    alipay = AliPay(
        appid=settings.ALIPAY_APPID,
        app_notify_url=None,  # 默認回調url
        app_private_key_path=os.path.join(settings.BASE_DIR, "AppTest/app_private_key.pem"),
        alipay_public_key_path=os.path.join(settings.BASE_DIR, "AppTest/alipay_public_key.pem"),
        # 支付寶的公鑰,驗證支付寶回傳消息使用,不是你本身的公鑰,
        sign_type="RSA2",  # RSA 或者 RSA2
        debug=True  # 默認False  配合沙箱模式使用
    )

    # 電腦網站支付,須要跳轉到https://openapi.alipay.com/gateway.do? + order_string
    order_string = alipay.api_alipay_trade_page_pay(
        out_trade_no=order_id,
        total_amount=str(0.01),  # 將Decimal類型轉換爲字符串交給支付寶
        subject="測試訂單",
        return_url="https://example.com",
        notify_url="https://example.com/notify"  # 可選, 不填則使用默認notify url
    )

    # 讓用戶進行支付的支付寶頁面網址
    url = settings.ALIPAY_URL + "?" + order_string

    return JsonResponse({"code": 0, "message": "請求支付成功", "url": url})


def check_pay(request):
    # 建立用於進行支付寶支付的工具對象
    order_id = request.GET.get("order_id")
    alipay = AliPay(
        appid=settings.ALIPAY_APPID,
        app_notify_url=None,  # 默認回調url
        app_private_key_path=os.path.join(settings.BASE_DIR, "AppTest/app_private_key.pem"),
        alipay_public_key_path=os.path.join(settings.BASE_DIR, "AppTest/alipay_public_key.pem"),
        # 支付寶的公鑰,驗證支付寶回傳消息使用,不是你本身的公鑰,
        sign_type="RSA2",  # RSA2,官方推薦,配置公鑰的時候能看到
        debug=True  # 默認False  配合沙箱模式使用
    )

    while True:
        # 調用alipay工具查詢支付結果
        response = alipay.api_alipay_trade_query(order_id)  # response是一個字典
        # 判斷支付結果
        code = response.get("code")  # 支付寶接口調用成功或者錯誤的標誌
        trade_status = response.get("trade_status")  # 用戶支付的狀況

        if code == "10000" and trade_status == "TRADE_SUCCESS":
            # 表示用戶支付成功
            # 返回前端json,通知支付成功
            return JsonResponse({"code": 0, "message": "支付成功"})

        elif code == "40004" or (code == "10000" and trade_status == "WAIT_BUYER_PAY"):
            # 表示支付寶接口調用暫時失敗,(支付寶的支付訂單還未生成) 後者 等待用戶支付
            # 繼續查詢
            print(code)
            print(trade_status)
            continue
        else:
            # 支付失敗
            # 返回支付失敗的通知
            return JsonResponse({"code": 1, "message": "支付失敗"})
# Create your views here.

3.主urls.py

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^', include('AppTest.urls')),
]

4.AppTest urls.py

from django.conf.urls import include, url
from views import *

urlpatterns = [
    url(r"^$", index),
    url(r"^pay/$", pay),
    url(r"^check_pay/$", check_pay),
]

5.setttings.py中設置

修改templates部分

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR,"template").replace("\\","/")
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

末尾加入

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]

# 支付寶配置參數
ALIPAY_APPID = "2017072407880788"
ALIPAY_URL = "https://openapi.alipay.com/gateway.do"

 

 

測試效果:

 

 

返回結果

https://example.com/?total_amount=0.01&timestamp=2018-01-06+21%3A28%3A38&sign=fg19hD85DPPuN1aaI%2B%2BskuomKUxaDGE%2FdvyttEyV3vubVkVvBDXVziZaGybXqZs5o4bXYojx587qNBb8e%2FjAJOBCwKwYZxd7qR3AKlVabkPDzEOlzvEaSW7HTQpsWsVeX6BW%2ByEO8pWQ8c%2BS8B8tS8a8AFtQxeW92as4hdNjQU2YBZ2SVxtKSohWbFWpny1gDWXinQ3y2HNo4t5lmA8fRknB0MaUPwR1SzWa0k%2BylYjpWEnzC6OihP0Er21Ad8fiUwtSxZqH4xIAhnbofAy%2BHYZZVsv5lYg%2Brb87eM6Yz7xwUe5v5dDEoz%2FOLjsuB0GDRTdvhHqs39cGIoMXFfEpbw%3D%3D&trade_no=2018010621001004260217512776&sign_type=RSA2&auth_app_id=2017072407880788&charset=utf-8&seller_id=2088221936946848&method=alipay.trade.page.pay.return&app_id=2017072407880788&out_trade_no=20180105002&version=1.0

相關文章
相關標籤/搜索