1. 程式人生 > >Django支付寶線上支付

Django支付寶線上支付

Django支付

使用python工具包

# 從 1.3.0升級上來的使用者, 請先解除安裝pycrypto:
pip uninstall pycrypto
# 安裝python-alipay-sdk
pip install python-alipay-sdk --upgrade

檢視開發者文件:https://openhome.alipay.com/developmentDocument.htm

登入螞蟻金服開發者平臺 建立沙箱應用,獲得應用公鑰與私鑰,將檔案放到應用目錄下

詳細可參考: https://github.com/fzlee/alipay/blob/master/README.zh-hans.md

應用例項程式碼參考:
def order(request):
    if request.method == "POST":
        order_id = request.POST.get("order")
        order = Order_info.objects.get(pk=order_id)
        price = str(order.total)
		
        # 手機版
        app_private_key_string = open(os.path.join(BASE_DIR, 'apps/utils/alipay/ying_yong_si_yao.txt'
)).read() alipay_public_key_string = open(os.path.join(BASE_DIR, 'apps/utils/alipay/ying_yong_gong_yao.txt')).read() alipay = AliPay( appid="2016092400584100", app_notify_url=None, # 預設回撥url app_private_key_string=app_private_key_string, # 支付寶的公鑰,驗證支付寶回傳訊息使用,不是你自己的公鑰,
alipay_public_key_string=alipay_public_key_string, sign_type="RSA2", # RSA 或者 RSA2 debug=True # 預設False ) order_string = alipay.api_alipay_trade_wap_pay( out_trade_no=order.ordernum, total_amount=price, subject="超市支付", return_url="http://127.0.0.1:8000/cart/pay/", notify_url=None # 可選, 不填則使用預設notify url ) re_url = "https://openapi.alipaydev.com/gateway.do?{data}".format(data=order_string) return JsonResponse({"code": 0, "url": re_url}) else: ordernum = request.GET.get("ordernum") order = Order_info.objects.get(ordernum=ordernum) context = { "order": order } return render(request, 'cart/order.html', context)
def pay(request):
    
    # 手機版
    app_private_key_string = open(os.path.join(BASE_DIR, 'apps/utils/alipay/ying_yong_si_yao.txt')).read()
    alipay_public_key_string = open(os.path.join(BASE_DIR, 'apps/utils/alipay/ying_yong_gong_yao.txt')).read()

    alipay = AliPay(
        appid="2016092400584100",
        app_notify_url=None,  # 預設回撥url
        app_private_key_string=app_private_key_string,
        # 支付寶的公鑰,驗證支付寶回傳訊息使用,不是你自己的公鑰,
        alipay_public_key_string=alipay_public_key_string,
        sign_type="RSA2",  # RSA 或者 RSA2
        debug=True  # 預設False
    )
    out_trade_no = request.GET.get("out_trade_no")
    paid = False
    for i in range(3):
        result = alipay.api_alipay_trade_query(out_trade_no=out_trade_no)
        if result.get("trade_status", "") == "TRADE_SUCCESS":
            paid = True
            break
        else:
            time.sleep(3)

    if paid is False:
        context = {
            "mess": "支付失敗"
        }
    else:
        context = {
            "mess": "支付成功"
        }
        Order_info.objects.filter(ordernum=out_trade_no, order_status=0).update(order_status=1)
    return render(request, 'cart/pay.html', context)