Django website project offline QR code scanning payment

1. Preliminary work

 

 

  • The way to set the key is to download the Alipay generated key tool: the address and the extraction code of the toolkit:

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

 

Run. exe file

  

 

  • Copy the contents of my_private_key.pem and ensure that there are no characters such as spaces and line breaks. If the contents are copied into the settings of the RSA2 key in the first picture, the Alipay public key will be generated and copied in the alipay_public_key.pem file.

Download the python SDK Toolkit (it's too much of a pit)

  • In the downloading process, Alipay official provided the SDK toolkit, running in the cmd command line: pip install alipay-sdk-pythoon. If there is no error in the download process, you are lucky; if you report an error, congratulations are in 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 three dependent packages in the red box above. The first and second packages you may go to pip to download by yourself, or they have already downloaded for you, but the third package seems to be unable to download. After a lot of searching, it seems to download another package similar to this one. 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. So the SDK package provided by Alipay developer platform can not be downloaded.

  • Problem solving: after my earth shaking search, I accidentally saw another download method, which is to use the pycryptodome dependency package, so you can download it directly:

pip install python-alipay-sdk

This download will be right.

Create project app

  • Run in the project directory: Python management.py startapp payment
  • Then create the directory as shown below (just look at the payment app directory, regardless of the file color). Paste the previously saved private key and public key files 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 payment
    path("check_pay/", views.CheckPayView.as_view(), name="check_pay"),   # Verify payment is complete
]
  • The view file is the play
    • These two classes are created respectively. In addition, the object of Alipay is defined outside the class. I'm sure you've seen the creation of many Alipay objects. Their initialization parameters are different. Because they didn't download the SDK toolkit, they should all go to github to copy an Alipay toolkit encapsulated by others, so there are some differences in using object call methods. If you download the SDK kit, follow my steps. Also can't blindly follow other people's code knock, look at the source code and its implementation. Needless to say, the code is up (I'll write part of it here to help understand and enhance my memory, but it's all in the same views.py file) P
    • The first step is to initialize the object of our Alipay class. First, take a look at the source code of the Alipay class. It inherits the BasePay class, so take a look at the source code of the BasePay class directly. I'm going to the current place where I'm using it. The way: AliPay - >BaseAliPay - > to see his __init__ initialization method, mainly depends on where I add the annotation. It does not seem to load the application of the private key file and the Alipay public key file. The last sentence is the method of loading the two files >_load_key method, the annotation is very important, and it is not duplicated here. The main content is that we need pem file format. In addition, descriptive language needs to be added at the beginning and end of the document. When you browse the load key method, you will know why you need the pem file and the styles of the file header and the end. Then when reading the file, you need to read it as follows. Of course, if you can guarantee the same content, you can read the file in different ways.
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

        #  Namely my_private_key.pem What's in it
        self._app_private_key_string = app_private_key_string

        #  Namely alipay_public_key.pem What's in it
        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

        #  It's the key, it's the key
        self._load_key()
AliPay init ialization method__
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)
class AliPayView(ListAPIView):
    # Here is just to define a global order number
    order_id = None

    def get(self, request):
        """
        //Request for Alipay payment two-dimensional code
        :param request: Request for
        :return: Request address with 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="Commodity purchase",        # Name of charge
            out_trade_no=str(uuid.uuid4()),   #Merchant's order number, unique, use uuid More convenient
            total_amount=all_price,      # Price from front end
            # This is very important. Here is the address of a request to be verified when making payment
            return_url="http://127.0.0.1:8000/payment/check_pay/",    
        )
        # The address of Alipay gateway: because it is debug=False So it's the sandbox address
        url = alipay._gateway + "?" + params

        return Response(data={"url": url})
class CheckPayView(APIView):

    def get(self, request):
        """
        //Verify whether the payment is successful. If the payment is successful, you need to modify the order status,
        :param request: Get requests for
        :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"))

Keywords: Python SDK pip Django

Added by rlgriffo on Tue, 14 Apr 2020 13:53:02 +0300