一文基本搞定python的django框架下微信支付v3的主要流程-3[亲测有效]

一文基本搞定python的django框架下微信支付v3的主要流程-3[亲测有效]为了保证苹果IOS用户也能使用,不得以只能再开发Web网站应用,在网站上实现微信支付。下面列出基本代码,希望能给有需要的人一些帮助,如有不对的地

欢迎大家来到IT世界,在知识的湖畔探索吧!

本来只计划先完成微信小程序端的微信支付功能,但小程序上线后审核被退回,提示微信支付功能不能出现在苹果IOS平台上面。无奈只能在前端加上对手机设备的判断。针对苹果IOS系统只能提示暂时不支持。为了保证苹果IOS用户也能使用,不得以只能再开发Web网站–来推鉴-投融资项目推荐服务平台应用,在网站上实现微信支付。

要实现网站上的微信支付功能也不轻松,前端差别很大,要通过生成付款二维码后手机扫码来付款。下面列出基本代码,希望能给有需要的人一些帮助,如有不对的地方也请大神指正。

五、微信Native支付

#前端
html
<!-- 生成微信支付二维码 -->
  <view class="qr" v-if="ifShow" @click.self="hideSelf">
    <view class="payment">
      <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
        <el-tab-pane label="微信支付" name="wxpay">
          <view class="payTab">
            <image src="../../static/image/wxpay.png" mode=""></image>
            <view class="qrimg">
              <!-- <tki-qrcodey cid="qrcode1" ref="qrcode" :val="val" :size="size" :unit="unit" :background="background" :foreground="foreground" :pdground="pdground" :lv="lv" :onval="onval" :loadMake="loadMake" :usingComponents="true" /> -->
              <canvas id="qrcode" canvas-id="qrcode" style="width: 354px;height: 354px;" />
            </view>  
          </view>                              
        </el-tab-pane>
        <el-tab-pane label="支付宝" name="alipay">
          <view class="payTab">
            <image src="" mode=""></image>
            <view class="qrimg">暂未支持</view>
          </view>  
        </el-tab-pane>                    
        </el-tabs>        
    </view>
  </view>

js  
<script>
 //用到uniapp的uQRCode插件
import uQRCode from '../../uni_modules/Sansnn-uQRCode/components/uqrcode/common/uqrcode.js'
//从微信支付
payFromWx () {
      uni.showModal({
        title: '提示',
        content: '点击确定使用微信支付完成购买。',
        success:  async (res)=> {
          if (res.confirm) {
            const code_url =await this.$myRequest({
              url:'/api/payFromWxWeb',
              method:'POST',
              data:{
                price:this.payList[this.activeIndex-1].price,
                userId:this.userInfo.userId,
                token:this.userInfo.token,                    
              },
            })
            this.ifShow=1            
            this.val=code_url.data.code_url            
            uQRCode.make({      #生成付款二维码
                  canvasId: 'qrcode',
                  componentInstance: this,
                  size: 354,
                  margin: 10,
                  text: this.val,
                  backgroundColor: '#ffffff',
                  foregroundColor: '#000000',
                  fileType: 'png',
                  errorCorrectLevel: uQRCode.errorCorrectLevel.H
            })
            .then(res => {
              // console.log(res)
                  this.transactionNo=code_url.data.transactionNo
                  setTimeout(() => {
                    this.checkPaymentStatus()     #收到后端返回的交易号后,向后台数据库轮讯交易是否成功            
                  }, 5000)
            })
            
          } else if (res.cancel) {
          } 
        },
      })
    },
//扫码后向后台轮讯交易是否成功
    checkPaymentStatus(){
      var num=1
      var intervalID=setInterval(async() => {
        if(num>30){
          this.ifShow=0
          clearInterval(intervalID)
          uni.showToast({
            title: '微信支付未成功,请稍后查询',
            icon: 'none'
          })
          this.getUserData()
        }else{
          const res =await this.$myRequest({
                  url:'/api/checkPaymentStatus',
                  method:'POST',
                  data:{
                    transactionNo:this.transactionNo,
                    userId:this.userInfo.userId,
                    token:this.userInfo.token,                    
                  },
          })
          const paymentStatus=res.data.paymentStatus          
          if (paymentStatus==2){
                this.ifShow=0
                uni.showToast({
                  title: '微信支付成功',
                  icon: 'none'
            })
            clearInterval(intervalID)
            this.getUserData()  
          }
          num++
        }
      }, 1000)
    }

欢迎大家来到IT世界,在知识的湖畔探索吧!

后端代码同JSAPI支付大同小异

欢迎大家来到IT世界,在知识的湖畔探索吧!
#网站微信支付
@api_view(['POST'])
@tokenAuthentication
def payFromWxWeb(request):    
      price=request.data['price']    
      userId=request.data['userId']    
      up_time=datetime.datetime.now()
      #1.以交易日期生成交易号
      transactionNo=str(up_time).replace('.', '').replace('-', '').replace(':', '').replace(' ', '')
      #2.生成新交易记录
      newTransaction=TransactionLogs.objects.create(
          transaction_no =transactionNo,
          transaction_status_id=1,
          user_id =userId,
          transaction_type_id=1,
          transaction_amount=price,
          created_at =up_time)
        #3.生成统一下单的报文body    
        url='https://api.mch.weixin.qq.com/v3/pay/transactions/native'
        body={
            "appid": settings.wxAppId,  #注意这里要用微信公众号的AppID
            "mchid": settings.mchId,
            "description": "购买XXXX",
            "out_trade_no": transactionNo,   
            "notify_url": "https://XXXXX/payNotify",  #同样有回调,可用JSAPI支付的回调函数
            "amount": {"total": price*100, "currency": "CNY"}, #正式上线price要*100,微信金额单位为分。        
        }    
      data=json.dumps(body)
      #4.定义生成签名的函数
      def get_sign(sign_str):
          rsa_key = RSA.importKey(open('XXXX/apiclient_key.pem').read())
          signer = pkcs1_15.new(rsa_key)
          digest = SHA256.new(sign_str.encode('utf8'))
          sign = b64encode(signer.sign(digest)).decode('utf-8')
          return sign
      #5.生成请求随机串
      random_str = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(32))
      #6.生成请求时间戳
      time_stamps = str(int(time.time()))
      #7.生成签名串
      sign_str = f"POST\n{'/v3/pay/transactions/native'}\n{time_stamps}\n{random_str}\n{data}\n"
      #8.生成签名
      sign = get_sign(sign_str)
      #9.生成HTTP请求头
      headers = {
          'Content-Type': 'application/json',
          'Accept': 'application/json', 
          'User-Agent': '*/*',
          'Authorization': 'WECHATPAY2-SHA256-RSA2048 ' + f'mchid="{settings.mchId}",nonce_str="{random_str}",signature="{sign}",timestamp="{time_stamps}",serial_no="{settings.serialNo}"'       
      }
      #10.发送请求获得code_url
      response = requests.post(url,data=data,headers=headers)
       
        #11.应答签名验证
             #同第一篇签名验证的代码

      #12.生成调起支付API需要的参数并返回前端
      res = {       
          'code_url':response.json()['code_url'],
          'transactionNo':transactionNo,      
      }
    return Response (res) 

#查询网站微信支付是否成功
@api_view(['POST'])
@tokenAuthentication
def checkPaymentStatus(request): 
      transactionNo=request.data['transactionNo']    
      transactionlog=TransactionLogs.objects.get(transaction_no=transactionNo)
      paymentStatus=transactionlog.transaction_status_id
      return Response ({'paymentStatus':paymentStatus}) 

欢迎大家支持:来推鉴公众号 开发经历

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/17563.html

(0)

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

联系我们YX

mu99908888

在线咨询: 微信交谈

邮件:itzsgw@126.com

工作时间:时刻准备着!

关注微信