Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Django Framework to realize Alipay payment in Python Project

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "Python project actual combat how to use Django framework to achieve Alipay payment", in daily operation, I believe that many people in the actual combat of Python project how to use Django framework to achieve Alipay payment problems have doubts, editor consulted all kinds of information, sorted out a simple and easy to use method of operation, hope to answer "Python project actual combat how to use Django framework to achieve Alipay payment" doubt! Next, please follow the editor to study!

I. Preface

Editor believes that when you pay, Wechat and Alipay must be the first choice. Today, the editor on a whim, to bring you a very interesting project, that is to use the Python web framework Django to achieve Alipay, nonsense, let's see how to achieve it.

Second, establish django application

Let's create a Django project and then create an application in it, as shown in the figure:

3. Configure and start

Then we set the contents of the urls file, as shown in the figure:

Then create a urls.py file in the sub-application, of course, you can also write some view functions directly in the urls.py file in the project. Finally, we write the view function and add it to the urls.py file, as shown in the figure:

Finally, we need to commit the changes, open the directory where the project manage.py file is located, and open cmd, and enter the following command:

Python manage.py migrate

Now let's run the project locally, again in this directory, as follows:

Python manage.py runserver

The result of the output shows that the sub-application has been started and the result is returned. We can also run and launch the Django application directly under the root directory of the created project without going through the sub-application. First, create a new view.py file in the pay directory, and then add it to the urls.py file in that directory, as follows:

Take a look at the figure below:

Log in to Alipay and generate a rsa key

First of all, log in to the Alipay we want to collect, the address:

Https://auth.alipay.com/login/ant_sso_index.htm?goto=https%3A%2F%2Fopenhome.alipay.com%2Fplatform%2FappDaily.htm%3Ftab%3Dinfo

Then login, as shown in the figure:

Then click the settings after RSA2 (SHA256), click the public key and download Alipay key generator or openssl to generate the key. Here I choose Alipay key generator, as shown in the figure:

Then click it and jump to the download interface to download, as shown in the figure:

After downloading, open the tool, select the key length and key format, and generate the key, as shown below:

Then go to the directory of public and private keys, copy this to the sub-application directory of our Django project, and rename it for later use, as shown in the figure:

Immediately after that, we go to our developer Center console, address:

Https://open.alipay.com/platform/developerIndex.htm

Then we create an application, as shown in the figure:

Fill in the form truthfully as required. Then let's set its interface encryption method, as shown in the figure:

After verification, enter the newly generated application public key, as shown in the figure:

The application public key and Alipay public key will appear to save the Alipay public key, as shown in the figure:

Then we save the generated amount with public and private keys and Alipay public keys as files in the following form, as shown in the figure:

Save all three files in the rsakey folder. Now that the preparatory work is done, let's start to write the Alipay payment interface.

Note: you can use the key to call Alipay interface only after the project has been approved.

IV. Alipay payment interface on PC

Here we wrap it with a class, as follows:

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): "" Alipay interface (PC end payment interface) "" 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) # sorted string 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) # get the final order information string 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 data of dictionary type 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): # start calculating signature key = self.app_private_key signer = PKCS1_v1_5.new (key) signature = signer.sign (SHA256.new (unsigned_string)) # base64 encoding Convert to unicode and remove carriage return sign = encodebytes (signature) .decode ("utf8") .replace ("\ n", ") return sign def _ verify (self, raw_content) Signature): # start calculating 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") # sorted string unsigned_items = self.ordered_data (data) message = "&" .join (u "{} = {}" .format (k, v) for k, v in unsigned_items) return self._verify (message, signature)

For ease of calling, we put the Python file in the directory of the sub-application and name it pay.py.

Fifth, write the front-end page

We generate the corresponding commodity information and initiate a payment request based on the name and price of the goods at the front end, as follows:

Index.html (Commodity Home Page)

Document table,table tr th, table tr td {border:1px solid # 0094ff;} table {width:300px; min-height: 25px; line-height: 25px; text-align: center; border-collapse: collapse; padding:2px;} a {text-decoration: none } Welcome to the shopping mall catalogue, commodity name, commodity unit price, quantity, whether to buy pear 0.11.

Show.html (payment result display page)

Document payment result: {{msg}}

6. Write a view function to handle rendering

From django.shortcuts import render,redirect from django.http import HttpResponse,JsonResponse from .pay import AliPay import uuid from urllib.parse import parse_qs # Create your views here. Def index (request): return render (request,'index.html') def dingdan (request): # instantiate AliPay alipay = AliPay (appid= "own APPID", app_notify_url=' http://127.0.0.1:8000/paypay/check/',# pay treasure will send post request return_url=' http://127.0.0.1:8000/paypay/show/', to this address # pay treasure will send a get request to this address: app_private_key_path=r'C:\ Users\ Administrator\ Desktop\ pay\ paypay\ rsakey\ private2048.txt', # apply private key alipay_public_key_path=r'C:\ Users\ Administrator\ Desktop\ pay\ paypay\ rsakey\ paypublic.txt', # Alipay public key debug=True # default is False) # define the parameters passed in the request address res=alipay.direct_pay (subject=' pear', # product description out_trade_no=str (uuid.uuid4 ()), # order number total_amount='0.1', # transaction amount (in yuan) (keep two decimal places) # generate url url=' https://openapi.alipaydev.com/gateway.do?{0}'.format(res) return redirect (url) def show (request) that jumps to Alipay's payment page: if request.method = 'GET': alipay = AliPay (appid= "own APPID") App_notify_url=' http://127.0.0.1:8000/paypay/check/', return_url=' http://127.0.0.1:8000/paypay/show/', app_private_key_path=r'C:\ Users\ Administrator\ Desktop\ pay\ paypay\ rsakey\ private2048.txt' # apply the private key alipay_public_key_path=r'C:\ Users\ Administrator\ Desktop\ pay\ paypay\ rsakey\ paypublic.txt', # Alipay public key debug=True, # default is False) param=request.GET.dict () # get the parameters carried by the request and convert it to dictionary type sign=param.pop ('sign' None) # get the value of sign # validate the sign parameter statu = alipay.verify (param,sign) if statu: return render (request, 'show.html', {' msg': 'payment succeeded'}) else: return render (request, 'show.html', {' msg': 'payment failed'}) else: return render (request 'show.html', {'msg':' only supports GET requests Do not support other requests'}) def check (request): if request.method=='POST': alipay=AliPay (appid= "own APPID", app_notify_url=' http://127.0.0.1:8000/paypay/check/', # Alipay will send post request return_url=' http://127.0.0.1:8000/show_msg/', to this address # Alipay will send get request app_private_key_path=r'C:\ Users\ Administrator\ Desktop\ pay\ paypay\ rsakey\ private2048.txt', # Application Private key alipay_public_key_path=r'C:\ Users\ Administrator\ Desktop\ pay\ paypay\ rsakey\ paypublic.txt', # Alipay Public key debug=True ) body=request.body.decode ('utf-8') # into the string post_data = parse_qs (body) # split according to the & symbol post_dict = {} for k, v in post_data.items (): post_ post_ [k] = v [0] sign = post_dict.pop (' sign', None) status = alipay.verify (post_dict) Sign) if status: # payment succeeded return HttpResponse ('payment succeeded') else: return HttpResponse ('payment failed') else: return HttpResponse ('only POST requests are supported')

7. Add routing functions to url rules

From django.urls import path from. Import views urlpatterns= [path (', views.index,name='index'), path ('dingdan/',views.dingdan,name='dingdan'), path (' show/',views.show,name='show'), path ('check/',views.check,name='check'),]

8. Run the project

Now that all the preparatory work has been done, let's try to run the project as follows:

You can see that after we bought the goods, the link successfully jumped to the payment interface.

At this point, on the "Python project how to use the Django framework to achieve Alipay payment" on the end of the study, I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 298

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report