Django website project offline QR code scanning payment

1. Preliminary work

 

 

  •  The way to set the key needs to be downloaded to generate a key tool for Alipay: the address and extraction code of the toolkit:

    Link: https://pan.baidu.com/s/1AXK3s4SBowNp1K47Qc1QHw
    extraction code: 2u04

 

  Run the .exe file

  

 

  •  Copy the content of my_private_key.pem, and ensure that it does not contain characters such as spaces and line breaks; fill the copied content into the RSA2 key settings in the first picture, and the Alipay public key will be generated and copied and stored in the alipay_public_key.pem file

Python SDK toolkit download (it's terrible)

  • During the download process, Alipay officially provided the SDK toolkit, run it on the cmd command line: pip install alipay-sdk-pythoon. If there are no errors during the download process, then you are lucky; if you report an error, then congratulations you have entered the pit. Don't worry, since I said that, I have the ability to help you solve problems.

 

 

 

In the process of downloading, you will definitely encounter the above situation. When downloading the SDK, you need the three dependency packages in the red box above. For the first and second, you may pip to download it yourself, or he will help you It has been downloaded, but the third package seems to be unable to be downloaded. After my extensive search, it seems to be downloading another package similar to this. This package is his extension-pycryptodome. So you have to go to pip install pycryptodome. But when you download this package, you will still report the same error as above. Therefore, the SDK package provided to us by the Alipay developer platform cannot be downloaded.

  • Problem solving: After my up and down search, I accidentally saw another download method. This method is to use the pycryptodome dependency package, then you can download it directly:

pip install python-alipay-sdk

This download will be correct.

Create project app

  • Enter the project directory and run: python manage.py startapp payment
  • Then create the same directory as the following figure (just look at the payment app directory, the file color does not matter) paste the previously saved private key public key file into the key directory

 

 

 

  • Here, the main url configuration is omitted, and the sub url configuration is directly entered.
    • urls.py file
from django.urls import path
from . import views

app_name = '[payment]'
urlpatterns = [
    path ( " alipay / " , views.AliPayView.as_view (), name = " alipay " ),    # Alipay 
    path ( " check_pay / " , views.CheckPayView.as_view (), name = " check_pay " ),    # verify the payment is complete 
]
  • The view file is very important
    • Create these two classes separately, and define Alipay objects outside the class first. I believe everyone has seen the creation of many Alipay objects. The parameters of their initialization objects are different. Because they did not download the SDK toolkit, they should all go to github and copy a copy of the alipay toolkit packaged by others. Therefore, calling methods using objects is somewhat different. If you downloaded the SDK toolkit, following my steps will not be wrong. Still can't blindly follow other people's code, look at the source code and its implementation. Not much nonsense, I put on the code (I wrote it part by part here, which is helpful for understanding and allows me to enhance my memory, but it is all in the same views.py file) P
    • The first step is to initialize the objects of our Alipay class. First, let's take a look at the source code of the Alipay class. He inherits the BasePay class, so look directly at the source code of the BasePay class. I will go directly to the current use and place. Method: AliPay ——> BaseAliPay ——> View his __init__ initialization method, mainly see where I add comments, it seems that it is not to load the application private key file and Alipay public key file, the last sentence is to call to load these two files The method-> _ load_key method, the comments inside are very important, not copied here, the main content is that we need the content of the pem file format, and the file header and file end need to add ----- descriptive language- ----. When you browse the _load_key method, you will know why you need the pem file and the header and trailer styles. Then when reading the file, you also need to read it as follows. Of course, if you can guarantee that the obtained content is the same, the way to read the file may be inconsistent.
def __init__(
        self,
        appid,
        app_notify_url,
        app_private_key_string=None,    
        alipay_public_key_string=None,  
        sign_type="RSA2",
        debug=False
    ):
        """
        initialization:
        alipay = AliPay(
          appid="",
          app_notify_url="http://example.com",
          sign_type="RSA2"
        )
        """
        self._appid = str(appid)
        self._app_notify_url = app_notify_url

        #   Is my_private_key.pem contents inside 
        self._app_private_key_string = app_private_key_string

        #   Is alipay_public_key.pem contents inside 
        self._alipay_public_key_string = alipay_public_key_string

        self._app_private_key = None
        self._alipay_public_key = None
        if sign_type not in ("RSA", "RSA2"):
            raise AliPayException(None, "Unsupported sign type {}".format(sign_type))
        self._sign_type = sign_type

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

        # load key file immediately

        #   Is critical here is the focus of 
        self._load_key ()
AliPay initialization method __init__
from alipay import AliPay

my_private_key = ""
alipay_public_key = ""
with open("./payment/key/my_private_key.pem") as f1:
    for read in f1.readlines():
        my_private_key += read

with open("./payment/key/alipay_public_key.pem") as f2:
    for read in f2.readlines():
        alipay_public_key += read
alipay = AliPay(appid='2016102100732430',
                app_notify_url='http://127.0.0.1:8000/payment/check_pay/',
                app_private_key_string=my_private_key,
                alipay_public_key_string=alipay_public_key,
                debug=True)
    • At this time we can issue a request on the front end, like making a request like payment. The front end gets such an address and makes a redirect.
class AliPayView (ListAPIView):
     # here is to define a global order number 
    order_id = None

    def get(self, request):
        """
        Request to obtain Alipay's payment QR code
        : param request: request to get
        : return: the request address containing the payment QR code
        """
        all_price = request.GET.get("all_price")
        AliPayView.order_id = request.GET.get("order_id")

        params = alipay.api_alipay_trade_page_pay(
            Subject = " product purchase " ,         # Name charges 
            out_trade_no = str (uuid.uuid4 ()),    # Merchant order number, unique, more convenient to use uuid 
            TOTAL_AMOUNT = all_price,       # from the front get the price of 
            # this is key, here When paying, you need to verify the address of a request 
            return_url = " http://127.0.0.1:8000/payment/check_pay/ " ,    
        )
        # Alipay Gateway Address: debug = False because it is the address of the sandbox 
        url = alipay._gateway + " ? " + Params

        return Response(data={"url": url})
    • When we use the sandbox Alipay to scan the code and the payment is successful, it will issue the get request for the return_url address above as the server, and he will carry the params parameters mentioned above, and there will be a sign in the parameters, which requires the AliPay object to call the signature verification Method verify, his return value is boolean value
class CheckPayView(APIView):

    def get(self, request):
        """
        To verify whether the user paid successfully, you need to modify the status of the order if the payment is successful,
        : param request: request to get
        : return: redirect to order page
        """
        params = request.GET.dict()
        sign = params.pop("sign")
        if alipay.verify(params, sign):
            order = Orders.objects.get(pk=AliPayView.order_id)
            order.status = 2
            order.save()
        return redirect(reverse("operations:order"))
    • This way the views.py file has been written

 

Guess you like

Origin www.cnblogs.com/aitiknowledge/p/12699694.html