Django implements alipay sandbox operations
The environment is the required module
- Django = = 3.1.0
- Python = = 3.7.4
- Python – alipay – SDK = 2.0.1
The required
- Download the module python-Alipay – SDK =2.0.1
- Python SDK: github.com/fzlee/alipa…
Sandbox environment configuration
- On alipay open platform —-> Developer Center -> development services —-> sandbox
- RSA2 key generation and upload reference official address: opendocs.alipay.com/open/291/10…
- Download the alipay open platform development assistant opendocs.alipay.com/open/291/in download address…
[ImG-RLKagKA3-1602600315452] (C:%5CUsers%5CASUS%5CAppData%5CRoaming%5CTypora%5Ctypora-u) [C:%5CUsers%5CASUS%5CAppData%5CRoaming%5CTypora%5Ctypora-u ser-images%5Cimage-20201013215646909.png#pic_center)] )
4. Copy the application public key to Alipay
[Img-PM1umRDQ-1602600230099] (C:\Users\ASUS\AppData\ Typora\ Typora-user-images \ I) [imG-PM1UmRDQ-1602600230099] [C:\Users\ASUS\AppData\Roaming\ Typora-user-images \ I mage-20201013220238000.png)]
[Img-xim2wwQR-1602600230101] (C:\Users\ASUS\AppData\ Typora\ Typora-user-images \ I) [img-xim2wwQR-1602600230101] (C:\Users\ASUS\AppData\Roaming\ Typora-user-images \ I mage-20201013220309533.png)]
[Img-CZrsx4TY-1602600230104] (C:\Users\ASUS\AppData\ Typora\ Typora-user-images \ I) [img-CZrsx4TY-1602600230104] (C:\Users\ASUS\AppData\Roaming\ Typora-user-images \ I mage-20201013220359867.png)]
5. Configure the alipay public key development assistant secret key in app
- [Img-hzeendd6-1602600230107] (C:\Users\ASUS\AppData\ Typora\ Typora-user-images \ I) [img-hzeendd6-1602600230107] (C:\Users\ASUS\AppData\Roaming\ Typora-user-images \ I mage-20201013220610210.png)]
- You are advised to save the pictures and upload them directly (img-BG9hMEFA-1602600230111)(C: Users\ASUS\AppData\Roaming\Typ) ora\typora-user-images\image-20201013221108217.png)]
- You are advised to save the pictures and upload them directly (imG-0AGQpg4B-1602600230112)(C: Users\ASUS\AppData\Roaming\Ty) pora\typora-user-images\image-20201013221548593.png)]
Django Models
Class Status(BaseModel): name = models.CharField(max_length=32) Db_table = 'status' # class Order(BaseModel): out_trade_no = models.CharField(max_length=60) trada_no = models.CharField(max_length=60, null=True, blank=True) goods = models.ForeignKey(Goods, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) goods_num = models.IntegerField() status = models.ForeignKey(Status, on_delete=models.CASCADE) class Meta: db_table = 'order'Copy the code
Django Views configuration
-
Import uuid import redis from app01. Views import login_serializer from Alipay import Alipay, AliPayConfig123
Absolute path open file {} means forward from here
app_private_key_string = open(‘{}\app02\alipay_key\app_private_key’.format(settings.BASE_DIR)).read() alipay_public_key_string = open(‘{}\app02\alipay_key\alipay_public’.format(settings.BASE_DIR)).read()12
[Img-TU8CK5HJ-1602600230116] (C:\Users\ASUS\AppData\ Typora\ Typora-user-images \ I) [img-TU8CK5HJ-1602600230116] (C:\Users\ASUS\AppData\Roaming\ Typora-user-images \ I mage-20201013222520219.png)]
alipay = AliPay( appid="2016102500759596", app_notify_url=None, # default callback url app_private_key_string=app_private_key_string, # default callback url app_private_key_string Not your own public key, alipay_public_KEY_string = alipay_public_KEY_string, sign_type="RSA2", # RSA or RSA2 debug=True, # default False config=AliPayConfig(timeout=15) # 123456789Copy the code
3. Annotated code can be removed
Def post(self, request): # print(request.data) token = request.data.get('token') count = request.data.get('count') goods_info = Out_trade_no = STR (uuid.uuid4()) # request.data.get('goods_info') # print(goods_info) # print(goods_info Total_amount = 0 user_info = login_serializer. Loads (token) user_id = user_info.get('user_id') # If goods_info.find(',')! = -1: order_list = [] for i in goods_info.split(','): Print (I) # print(I) # print(I) # print(I) # print(I) # print(I) # # goods_obj = goods_objects. Get (pk= I) # total_amount += int(goods_obj.price) * Order_list. append(Order(out_trade_no=out_trade_no, goods_id= I, user_id=user_id, goods_num=count, status_id=1, Print (order_list) # order.objects.bulk_create (order_list) # ser.save() else: # print(r3.hget(user_id, goods_info)) # goods_count = r3.hget(user_id, goods_info).decode() # goods_obj = Goods.objects.get(pk=goods_info) # total_amount += int(goods_obj.price) * OrderModelSer(data={"out_trade_no": out_trade_no, "goods": goods_info, "user": user_id, "goods_num": count, "status": 1 }) if ser.is_valid(): ser.save() else: Print (ser.errors) # subject =" Need to jump to https://openapi.alipay.com/gateway.do? + order_string order_string = alipay. Api_alipay_trade_page_pay ( out_trade_no=out_trade_no, total_amount=count, subject=subject, Return_url = "http://127.0.0.1:8000/app02/callback_alipay", # notify_url = "http://127.0.0.1:8000/app02/callback_alipay" is optional, No filling, use the default notify url) # # splicing data print (order_string) pay_url = 'https://openapi.alipaydev.com/gateway.do?' + order_string # # print(pay_URL) return Response({' pay_URL ': pay_URL, 'MSG ': 'OK', "code": 200}) 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 6364656667686970717273747576Copy the code
[Img-M6WYKP5G-1602600230119] (C: Users\ASUS\AppData\ Typora\ Typora-user-images \ I) [img- M6WYKP5G-1602600230119] [img- M6WYKP5G-1602600230119] [img- M6WYKP5G-1602600230119] [IMG – M6WYKP5G-1602600230119 mage-20201013223018379.png)]
4.0
Class CallBackAlipayView(APIView): def get(self, request): Print (request. Query_params) print (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ") # judge whether there is data if request. Query_params. Get (" sign ") : # for i in request.query_params.get("out_trade_no"): # print(request. Query_params. get("out_trade_no")) # print(request. Query_params. get("out_trade_no") Order.objects.get(out_trade_no=request.query_params.get("out_trade_no") OrderModelSer(instance=queryset, data={"status": 2}, partial=True) if ser.is_valid(): ser.save() else: print(ser.errors) return Response({'msg': 'OK', "data": request.query_params})1234567891011121314151617181920Copy the code
[Img-afbrropl-1602600230122] [C: Users\ASUS\AppData\ Typora\ Typora-user-images \ I] [Img – Afbrropl-1602600230122] [img- Afbrropl-1602600230122] [img- Afbrropl-1602600230122] [img- Afbrropl-1602600230122] [IMG – Afbrropl-1602600230122] [IMG – Afbrropl-1602600230122 mage-20201013223126443.png)]
Call interface
addcart() { let data = new FormData(); data.append("token", sessionStorage.getItem("token")) data.append("goods_info", this.check) data.append("count", Enclosing count2) axios ({url: "http://127.0.0.1:8000/app02/alipay", method: "post", the data: data }).then(res => { console.log(res.data) if (res.data.code === 200) { window.location.href = res.data.pay_url } }) }, 12345678910111213141516, 1Copy the code
Invoked page
<template> <div> <div id="app"> <div class="header_con"> <div class="header"> <div class="welcome FL "> </div> <div class="fr"> <div v-if="username" class=" login_bTN FL "> < em > {{username}} < / em > < span > | < / span > < a @ click = "logout" > out of < / a > < / div > < div v - else class = "login_btn fl" > < a Href = "login. HTML" > login < / a > < span > | < / span > < a href = "register. HTML" > register < / a > < / div > < div class = "user_link fl" > < span > | < / span > < a href = "user_center_info. HTML" > user center < / a > < span > | < / span > < a href = "cart. HTML" > my cart < / a > < span > | < / span > < a Href ="user_center_order.html"> My order </a> </div> </div> </div> </div> </div> <div class="search_bar clearfix"> <a href="index.html" class="logo fl"><img src="/static/images/logo.png"></a> <div class="sub_page_name fl">| </div> <form method="get" action="/search.html" class="search_con fr mt40"> <input type="text" class="input_text fl" Name ="q" placeholder=" search "> <input type="submit" class="input_btn fr" name="" value=" search "> </form> </div> <div {{cart.length}}</em> </div> <ul class="cart_list_th clearfix"> < li class = "col03" > commodity prices < / li > < li class = "col04" > amount < / li > < li class = "col05" > subtotals < / li > < li class = "col06" > action < / li > < / ul > < ul class="cart_list_td clearfix" v-for="(sku,index) in cart"> <li class="col01"><input type="checkbox" name="" v-model="check" :value="sku.id" @click="checkbox(sku.id,sku.count,sku.price)"></li> <li class="col02"><img : "http://127.0.0.1:8000" SRC = "+ sku. The img" > < / li > < li class = "col03" > {{sku. The name}} < / li > < li class = "col05" > {{sku. Price $}} < / li > < li class = "col06" > < div class = "num_add" > < a @ click = "on_add (sku. Id)" class = "add fl" > + < / a > < input v-model="sku.count" @focus="origin_input=sku.count" @blur="on_input(index)" type="text" class="num_show fl"> <a @ click = "on_minus (sku id)" class = "minus fl" > - < / a > < / div > < / li > < li class = "col07" > {{sku. The sku price *. Count}} $< / li > < li Class = "col08" > < a @ click = "del (sku. Id)" > delete < / a > < / li > < / ul > < ul class = "settlements" > < li class = "col01" > < input Type ="checkbox" @click="check_count" V-model ="isChecked"></li> <li class="col02"> < span > selections < / span > < em > {{count2}} < / em > < br > of < b > {{total_selected_count}} < / b > item < / li > < li class = "col04" > < a </a></li> </ul> </div> </fooder> </div> </template> <script> import axios from 'axios' import fooder from '.. /components/Fooder' export default { name: "Cart", data() { return { cart: [ ], check: [], username: "", total_selected_amount: "", total_selected_count: "", on_selected_all: "", selected_all: "", count2: 0, isChecked: false, } }, components: { 'fooder': fooder }, methods: { del(goods_id) { let data = new FormData(); data.append("token", sessionStorage.getItem("token")) data.append("goods_id", goods_id) axios({ url: 'http://127.0.0.1:8000/app02/delcart', method: 'delete' data: data }).then(res => { console.log(res) this.$router.go(0) }) }, addcart() { let data = new FormData(); data.append("token", sessionStorage.getItem("token")) data.append("goods_info", this.check) data.append("count", Enclosing count2) axios ({url: "http://127.0.0.1:8000/app02/alipay", method: "post", the data: data }).then(res => { console.log(res.data) if (res.data.code === 200) { window.location.href = res.data.pay_url } }) }, on_add(goods_id) { let data = new FormData(); data.append("token", sessionStorage.getItem("token")) data.append("goods_id", goods_id) axios({ url: 'http://127.0.0.1:8000/app02/addcart', method: "post", the data: data }).then(res => { console.log(res) this.$router.go(0) }) }, on_minus(goods_id) { let data = new FormData(); data.append("token", sessionStorage.getItem("token")) data.append("goods_id", goods_id) axios({ url: 'http://127.0.0.1:8000/app02/minuscart', method: "post", the data: data }).then(res => { console.log(res) this.$router.go(0) }) }, show() { axios({ url: 'http://127.0.0.1:8000/app02/showcart', method: 'get' params: {" token ": sessionStorage.getItem("token")} }).then(res => { console.log(res) this.cart = res.data.data }) }, Check_count () {// Default value is false this.count2 = 0; this.check = []; if (this.isChecked) { this.check = [] } else { this.cart.forEach(item => { console.log(item.id); this.check.push(item.id); this.count() }) } }, Count () {// let count = 0 this.count2 = 0 for (let I in this.cart) {console.log(this.cart[I]) this.count2 += This. Cart [I].price * this. Cart [I].count}}, Log (this.check) if (this.check.includes(gid)) {// Include is selected. Click delete again and subtract the corresponding price this.count2 -= count * price this.check.splice(this.check.indexOf(gid), } else {this.check. Push [gid] // Add the total price this.count2 += count * price}},}, Created () {this.show()}} </script> <style scoped> </style> This. Count2 -= count * price this.check.splice(this.check.indexOf(gid), } else {this.check. Push [gid] // Add the total price this.count2 += count * price}},}, created() { this.show() } } </script> <style scoped> </style>Copy the code
PS: If you need Python learning materials, please click on the link below to obtain them
The full code can be obtained by clicking on the link below
Free Python learning materials and group communication solutions click to join