day-93微信小程序

授权

前台代码

 

数据后台解密与存储数据库(utf8mb4模式)

 settings:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'wxpy8',
        'USER':'root',
        'PASSWORD':"123",
        'HOST':'127.0.0.1',
        'PORT':3306,
        'OPTIONS': {'charset': 'utf8mb4'},          #必须要写

    }
}

views:

class Userinfo(APIView):
    def post(self,request):
        param=request.data
        if param.get('encrytedData') and param.get('iv') and param.get('token'):
            user_data=cache.get(param.get("token"))
            if user_data:
                openid,session_key=user_data.split("&")
                user_info=WXBizDataCrypt.WXBizDataCrypt.main(session_key,param.get('encrytedData'),param.get('iv'))
                save_data = {
                    'name': user_info['nickName'],
                    'avatar': user_info['avatarUrl'],
                    'language': user_info['language'],
                    'province': user_info['province'],
                    'city': user_info['city'],
                    'country': user_info['country'],
                    'gender': user_info['gender'],
                }
                models.wx_user.objects.filter(openid=openid).update(**save_data)
                user_info= models.wx_user.objects.filter(openid=openid).first()
                data=Wxuser(instance=user_info,many=False).data
                return Response({
                'code':200,
                "msg":"token错误",
                "data":data

                })

            else:
                return Response({
                'code':200,
                "msg":"token错误"
            })

        else:
            return Response({
                'code':200,
                "msg":"参数错误"
            })

 支付文档分析

 前台代码

pay:function(){                                                    
    
      wx.request({
        url: app.globalData.apiurl+"api/pay",
        header:{"content-type":"application/json"},
        data:{"token":wx.getStorageSync("token")},
        method:"POST",
        success:function(res){
          wx.requestPayment(
            {
              'timeStamp': res.data.data.timeStamp,
              'nonceStr': res.data.data.nonceStr,
              'package': res.data.data.package,
              'signType': res.data.data.signType,
              'paySign': res.data.data.paySign,
              'success': function (res) {
                console.log(res)
               },
              'fail': function (res) {
                console.log(res)
               },
              'complete': function (res) { }
            })
        }

      })
  }
})

Django代码

settings:

  配置文件

views:

from  rest_framework.views import APIView
from rest_framework.response import Response
from django.core.cache import cache
from app01.wx import settings
import random,time,hashlib,requests
import xml.etree.ElementTree as ET

class Pay(APIView):
    def post(self,request):
        param=request.data
        if param.get("token"):
            data=cache.get(param.get("token"))
            if data:
                self.openid=data.split("&")[0]
                self.ip=request.get_host().split(":")[0]
                re_data=self.once_pay()
                return Response({
                    "code": 200,
                    "msg": "ok",
                    "data":re_data
                })
            else:
                return Response({
                    "code": 200,
                    "msg": "缺少参数"
                })

        else:
            return Response({
                "code":200,
                "msg":"缺少参数"
            })

    def get_nonce_str(self):
        all="1234567890abcdefghijklmnopqrstuvwxyz"
        nonce_str=''.join(random.sample(all,30))
        return nonce_str


    def get_order_id(self):
        order_id=time.strftime("%Y%m%d")
        all = "1234567890abcdefghijklmnopqrstuvwxyz"
        nonce_str = ''.join(random.sample(all, 5))
        order_id=order_id+nonce_str
        return order_id
    def get_sign(self):
        data_dic = {
            "nonce_str": self.nonce_str,
            "out_trade_no": self.out_trade_no,
            "spbill_create_ip": self.spbill_create_ip,
            "notify_url": self.notify_url,
            "openid": self.openid,
            "body": self.body,
            "trade_type": "JSAPI",
            "appid": self.appid,
            "total_fee": 1,
            "mch_id": self.mch_id
        }
        strA="&".join([f"{k}={data_dic[k]}" for k in sorted(data_dic)])
        sign_str=f"{strA}&key={settings.pay_apikey}"
        md5=hashlib.md5()
        md5.update(sign_str.encode("utf-8"))
        sign=md5.hexdigest().upper()
        return sign

    def xml_to_dic(self,xml_data):
        data=ET.fromstring(xml_data)
        xml_dic={}
        for child in data:
            xml_dic[child.tag]=child.text
        return  xml_dic


    def  get_two_sign(self,data):
        timeStamp=str(int(time.time()))
        data_dic = {
            'appId': data['appid'],
            'timeStamp': timeStamp,
            'nonceStr': data['nonce_str'],
            'package': f"prepay_id={data['prepay_id']}",
            "signType": "MD5"
        }
        strA = "&".join([f"{k}={data_dic[k]}" for k in sorted(data_dic)])
        sign_str = f"{strA}&key={settings.pay_apikey}"
        md5 = hashlib.md5()
        md5.update(sign_str.encode("utf-8"))
        sign = md5.hexdigest().upper()
        re_dict={
            'timeStamp':timeStamp,
            "nonceStr":data['nonce_str'],
            "package":f"prepay_id={data['prepay_id']}",
            "paySign":sign,
            "signType":"MD5"
        }
        return re_dict




    def once_pay(self):
        self.appid=settings.AppId
        self.mch_id=settings.pay_mchid
        self.nonce_str=self.get_nonce_str()
        self.body="兵哥支付"
        self.out_trade_no=self.get_order_id()
        self.total_fee=1
        self.spbill_create_ip=self.ip
        self.notify_url="http://test.com"
        self.trade_type="JSAPI"
        self.openid=self.openid
        self.sign = self.get_sign()
        body_data = f"""
               <xml>
                   <appid>{self.appid}</appid>
                   <mch_id>{self.mch_id}</mch_id>
                   <nonce_str>{self.nonce_str}</nonce_str>
                   <sign>{self.sign}</sign>
                   <body>{self.body}</body>
                   <out_trade_no>{self.out_trade_no}</out_trade_no>
                   <total_fee>1</total_fee>
                   <spbill_create_ip>{ self.spbill_create_ip}</spbill_create_ip>
                   <notify_url>{self.notify_url}</notify_url>
                   <openid>{self.openid}</openid>
                   <trade_type>JSAPI</trade_type> 
               </xml>"""
        pay_url="https://api.mch.weixin.qq.com/pay/unifiedorder"
        response=requests.post(pay_url,data=body_data.encode("utf-8"),headers={"content-type":"application/xml"})
        xml_data=response.content
        xml_dict=self.xml_to_dic(xml_data)
        data=self.get_two_sign(xml_dict)
        return data

 

 消息模板显示

 

 

原文地址:https://www.cnblogs.com/klw1/p/11427501.html