Alipay template

Url

from django.contrib import admin
from django.urls import path
from app01 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('/update_order/', views.update_order),
    path('/pay_result/', views.pay_result),
    path('test/', views.TestView.as_view()),
]

View

from django.shortcuts import render, redirect, HttpResponse
from rest_framework.views import APIView
from django.views.decorators.csrf import csrf_exempt
from rest_framework.response import Response
import time
from utils.pay import AliPay


# Create your views here.

def aliPay():
    obj = AliPay(
        appid="2016101600700776",
        app_notify_url="http://127.0.0.1:8000/update_order/ " ,   # if successful payment, Alipay will send a POST request to the address (check whether the payment has been completed) 
        return_url = " http://127.0.0.1:8000/pay_result/ " ,   # if the payment is successful, redirected back to the address of your website. 
        alipay_public_key_path = " Keys / alipay_public_2048.txt " ,   # Alipay public 
        app_private_key_path = " Keys / app_private_2048.txt " ,   # application private 
        Debug = True,   # default False, 
    )
     return obj 


class TestView (APIView):
     DEFGET (Self, Request, * args, ** kwargs):
         return the render (Request, ' test.html ' ) 

    DEF POST (Self, Request, * args, ** kwargs):
         # price, the purchase of merchandise encryption 
        # spliced into URL 

        alipay = aLIPAY () 

        # of encrypting data for later 
        Money = a float (request.POST.get ( ' . price ' )) 
        out_trade_no = " X2 " + STR (the time.time ())
         # 1. Create a data in the database : state (to be paid) 

        query_params = alipay.direct_pay (
            Subject =" Mark Crazy English " ,   # commodity simple description 
            out_trade_no = out_trade_no,   # Merchant order number 
            TOTAL_AMOUNT = Money,   # transaction amount (unit: RMB reserved previous two decimal places) 
        ) 

        pay_url = " https://openapi.alipaydev.com/gateway. {} do? " .format (query_params) 

        return redirect (pay_url) 


DEF pay_result (Request):
     " "" 
    after the payment is complete, jump back to the address 
    : param Request: 
    : return: 
    "" " 
    params = request.GET.dict () 
    Sign = params.pop ( 'sign' , None) 

    alipay = ALIPAY () 

    Status = alipay.verify (params, Sign) 

    IF Status:
         return HttpResponse ( ' pay for success ' )
     return HttpResponse ( ' pay for failure ' ) 


# a view csrf_exempt = annotation can be used to identify cross-domain access. 
@csrf_exempt
 DEF update_order (request):
     "" " 
    after successful payment, pay treasure pOST request sent to the address (used to modify the order status) 
    : param request: 
    : return: 
    " "" 
    IF request.method == ' pOST ' :
         from urllib.parse import parse_qs

        body_str = request.body.decode('utf-8')
        post_data = parse_qs(body_str)

        post_dict = {}
        for k, v in post_data.items():
            post_dict[k] = v[0]

        alipay = aliPay()

        sign = post_dict.pop('sign', None)
        status = alipay.verify(post_dict, sign)
        if status:
            #Modify the order status 
            out_trade_no = post_dict.get ( ' out_trade_no ' )
             Print (out_trade_no)
             # 2. order number data in the database will be updated according to the 
            return HttpResponse ( ' pay for success ' )
         the else :
             return HttpResponse ( ' pay for failure ' )
     return HttpResponse ( '' )

 

 

 Pay

from datetime import datetime
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
from urllib.parse import quote_plus
from urllib.parse import urlparse, parse_qs
from base64 import decodebytes, encodebytes
import json


class AliPay(object):
    """
    支付宝支付接口(PC端支付接口)
    """

    def __init__(self, appid, app_notify_url, app_private_key_path,
                 alipay_public_key_path, return_url, debug=False):
        self.appid = appid
        self.app_notify_url = app_notify_url
        self.app_private_key_path = app_private_key_path
        self.app_private_key = None
        self.return_url = return_url
        with open(self.app_private_key_path) as fp:
            self.app_private_key = RSA.importKey(fp.read())
        self.alipay_public_key_path = alipay_public_key_path
        with open(self.alipay_public_key_path) as fp:
            self.alipay_public_key = RSA.importKey(fp.read())

        if debug is True:
            self.__gateway = "https://openapi.alipaydev.com/gateway.do"
        else:
            self.__gateway = "https://openapi.alipay.com/gateway.do"

    def direct_pay(self, subject, out_trade_no, total_amount, return_url=None, **kwargs):
        biz_content = {
            "subject": subject,
            "out_trade_no": out_trade_no,
            "total_amount": total_amount,
            "product_code": "FAST_INSTANT_TRADE_PAY",
            # "qr_pay_mode":4
        }

        biz_content.update(kwargs)
        data = self.build_body("alipay.trade.page.pay", biz_content, self.return_url)
        return self.sign_data(data)

    def build_body(self, method, biz_content, return_url=None):
        data = {
            "app_id": self.appid,
            "method": method,
            "charset": "utf-8",
            "sign_type": "RSA2",
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "version": "1.0",
            "biz_content": biz_content
        }

        if return_url is not None:
            data["notify_url"] = self.app_notify_url
            data["return_url"] = self.return_url

        return data

    def sign_data(self, data):
        data.pop("sign", None)
        # 排序后的字符串
        unsigned_items = self.ordered_data(data)
        unsigned_string = "&".join("{0}={1}".format(k, v) for k, v in unsigned_items)
        sign = self.sign(unsigned_string.encode("utf-8"))
        # ordered_items = self.ordered_data(data)
        quoted_string = "&".join("{0}={1}".format(k, quote_plus(v)) for k, v in unsigned_items)

        # 获得最终的订单信息字符串
        signed_string = quoted_string + "&sign=" + quote_plus(sign)
        return signed_string

    def ordered_data(self, data):
        complex_keys = []
        for key, value in data.items():
            if isinstance(value, dict):
                complex_keys.append(key)

        # 将字典类型的数据dump出来
        for key in complex_keys:
            data[key] = json.dumps(data[key], separators=(',', ':'))

        return sorted([(k, v) for k, v in data.items()])

    def sign(self, unsigned_string):
        # 开始计算签名
        key = self.app_private_key
        signer = PKCS1_v1_5.new(key)
        signature = signer.sign(SHA256.new(unsigned_string))
        # base64 编码,转换为unicode表示并移除回车
        sign = encodebytes(signature).decode("utf8").replace("\n", "")
        return sign

    def _verify(self, raw_content, signature):
        # 开始计算签名
        key = self.alipay_public_key
        signer = PKCS1_v1_5.new(key)
        digest = SHA256.new()
        digest.update(raw_content.encode("utf8"))
        if signer.verify(digest, decodebytes(signature.encode("utf8"))):
            return True
        return False

    def verify(self, data, signature):
        if "sign_type" in data:
            sign_type = data.pop("sign_type")
        # 排序后的字符串
        unsigned_items = self.ordered_data(data)
        message = "&".join(u"{}={}".format(k, v) for k, v in unsigned_items)
        return self._verify(message, signature)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/Rivend/p/12000643.html