1. 程式人生 > 實用技巧 >SpringBoot內部呼叫事務不起作用問題的解決方案

SpringBoot內部呼叫事務不起作用問題的解決方案

Django1.11配合uni-app發起微信支付!

經過三天的斷斷續續的奮戰,我終於是幹動了微信支付。為了以後不忘記,現在來一篇教程,來來來,開幹!!!

一、準備階段

1、準備階段我們需要去微信官網申請一個小程式或者公眾號。獲得AppID和AppSecret。

2、去微信商戶平臺 成為商家,開通JSAPI用來獲得商戶號和自己配置的鑰匙。然後再商戶平臺上面繫結小程式appid。

(點選下面圖片進入官方連結!)

在配置裡面配置一個自己的key,需要記住後臺開發的時候需要!

關聯後即可在小程式管理頁面開通微信支付!

到此,準備階段完成!

二、梳理流程

在這裡我大概寫一下流程:首先我們在前端發起微信登陸,此時微信會給我們返回一個openid,這個openid一定要留存在某一個位置。然後前段發起微信支付,向後端傳送資料請求,後端對結合前段的資料向微信方面傳送一個請求,請求相關資料,得到相關資料之後把資料傳送給前段,前段收到資料,利用微信介面再向微信指定連線傳送請求,微信返回請求,即可!這個就是全流程,很多人肯定已經懵了。沒事,咱一步一步來,別步子跨大了——扯到蛋了!

以上就是資料處理階段大概流程!

三、程式碼實現

0、使用者登入根據使用者code獲取openid

uni.login({
          provider: 'weixin',
          success: function(loginRes) {
            let code = loginRes.code;
            if (!_this.isCanUse) {
              //非第一次授權獲取使用者資訊
              uni.getUserInfo({
                provider: 'weixin',
                success: function(infoRes) { 
                        //獲取使用者資訊後向呼叫資訊更新方法
                  _this.nickName = infoRes.userInfo.nickName; //暱稱
                  _this.avatarUrl = infoRes.userInfo.avatarUrl; //頭像
                    _this.updateUserInfo();//呼叫更新資訊方法
                }
              });
            }
      
            //2.將使用者登入code傳遞到後臺置換使用者SessionKey、OpenId等資訊
            uni.request({
              url: 'http://127.0.0.1:8000/users/',
              data: {
                code: code,
              },
              method: 'GET',
              header: {
                'content-type': 'application/json' 
              },
              success: (res) => {
                console.log(res.data)
                if ( res.data.state== 1001) {
                  console.log("新註冊的使用者!")
                  _this.OpenId = res.data.openid;
                } else{
                  _this.OpenId = res.data.openid;
                  console.log("註冊過的使用者!開始設定本地快取!")
                  console.log(res.data[0].id)
                  if ( res.data[0].id ) {
                    //這裡獲得登陸狀態,然後根據登陸狀態來改變使用者按鈕資訊!!!!
                  } else{
                    
                  };
                  _this.user_id = res.data[0].id
                  uni.setStorage({
                    key: 'user',
                    data: res.data,
                    success: function () {
                      console.log('設定快取成功');
                    }
                  });
                  // _this.gotoshopping()
                  // uni.reLaunch({//資訊更新成功後跳轉到小程式首頁
                  //   url: '/pages/shopping/shopping'
                  // });
                }
                //openId、或SessionKdy儲存//隱藏loading
                uni.hideLoading();
              }
            });
          },
        });
if request.GET.get("code"):
      ret = {"state": 1000}
      code = request.GET.get("code")

      url = "https://api.weixin.qq.com/sns/jscode2session"
      appid = "xxxxxxxxxxxxx"
      secret = "xxxxxxxxxxxxxxxxxxxxx"

      # url一定要拼接,不可用傳參方式
      url = url + "?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code"
      import requests
      r = requests.get(url)
      print("======", r.json())
      openid = r.json()['openid']
      user = users.objects.filter(openid=openid).all()
      if not user:
        ret["state"] = 1001
        ret["msg"] = "使用者第一次登陸"
        ret["openid"] = openid
        return Response(ret)
      else:
        serializer = self.get_serializer(user, many=True)
        return Response(serializer.data)

1、首先需要建立一個confige.py的配置檔案!然後寫路由,讓前端找到“門”在哪裡!

config.py

# 微信支付的配置引數
client_appid = 'xxxxxxxxxxxxxx' # 小程式appid
client_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx' # 小程式secret

Mch_id = 'xxxxxxxxxxx' # 商戶號
Mch_key = 'xxxxxxxxxxxxxxxxxxx' # 商戶Key
order_url = 'https://api.mch.weixin.qq.com/pay/unifiedorder' # 訂單地址

url.py

router = routers.DefaultRouter()
router.register("users", views.UsersViewSet)
router.register("goods", views.GoodsViewSet)
router.register("comments", views.CommentsViewSet)
router.register("payOrder", views.OrdersViewSet) #這個就是微信支付的介面


urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include(router.urls)),

]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

view.py

class OrdersViewSet(viewsets.ModelViewSet):
  queryset = Order.objects.all()
  serializer_class = OrderModelSerializer

  def create(self, request, *args, **kwargs):
    if request.data.get("user_id"):
      from goods.wxpay.wxpay import payOrder
      data = payOrder(request)
      print(data)
      return Response(data)
    else:
      serializer = self.get_serializer(data=request.data)
      serializer.is_valid(raise_exception=True)
      self.perform_create(serializer)
      headers = self.get_success_headers(serializer.data)
      return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

  def perform_create(self, serializer):
    serializer.save()

  def get_success_headers(self, data):
    try:
      return {'Location': str(data[api_settings.URL_FIELD_NAME])}
    except (TypeError, KeyError):
      return {}

2、然後建立邏輯檔案,獲取資料請求資料返回資料!

wxpay.py

# -*- coding: utf-8 -*-
from .config import client_appid, client_secret, Mch_id, Mch_key, order_url
import hashlib
import datetime
import xml.etree.ElementTree as ET
import requests
from ..models import users


# 生成簽名的函式
def paysign(appid, body, mch_id, nonce_str, notify_url, openid, out_trade_no, spbill_create_ip, total_fee):
  ret = {
    "appid": appid,
    "body": body,
    "mch_id": mch_id,
    "nonce_str": nonce_str,
    "notify_url": notify_url,
    "openid": openid,
    "out_trade_no": out_trade_no,
    "spbill_create_ip": spbill_create_ip,
    "total_fee": total_fee,
    "trade_type": 'JSAPI'
  }
  print(ret)
  # 處理函式,對引數按照key=value的格式,並按照引數名ASCII字典序排序
  stringA = '&'.join(["{0}={1}".format(k, ret.get(k)) for k in sorted(ret)])
  stringSignTemp = '{0}&key={1}'.format(stringA, Mch_key)
  sign = hashlib.md5(stringSignTemp.encode("utf-8")).hexdigest()
  print(sign.upper())
  return sign.upper()


# 生成隨機字串
def getNonceStr():
  import random
  data = "123456789zxcvbnmasdfghjklqwertyuiopZXCVBNMASDFGHJKLQWERTYUIOP"
  nonce_str = ''.join(random.sample(data, 30))
  return nonce_str


# 生成商品訂單號
def getWxPayOrdrID():
  date = datetime.datetime.now()
  # 根據當前系統時間來生成商品訂單號。時間精確到微秒
  payOrdrID = date.strftime("%Y%m%d%H%M%S%f")

  return payOrdrID


# 獲取全部引數資訊,封裝成xml
def get_bodyData(openid, client_ip, price):
  body = 'Mytest' # 商品描述
  notify_url = 'https://127.0.0.1:8000/payOrder/' # 支付成功的回撥地址 可訪問 不帶引數
  nonce_str = getNonceStr() # 隨機字串
  out_trade_no = getWxPayOrdrID() # 商戶訂單號
  total_fee = str(price) # 訂單價格 單位是 分

  # 獲取簽名
  sign = paysign(client_appid, body, Mch_id, nonce_str, notify_url, openid, out_trade_no, client_ip, total_fee)

  bodyData = '<xml>'
  bodyData += '<appid>' + client_appid + '</appid>' # 小程式ID
  bodyData += '<body>' + body + '</body>' # 商品描述
  bodyData += '<mch_id>' + Mch_id + '</mch_id>' # 商戶號
  bodyData += '<nonce_str>' + nonce_str + '</nonce_str>' # 隨機字串
  bodyData += '<notify_url>' + notify_url + '</notify_url>' # 支付成功的回撥地址
  bodyData += '<openid>' + openid + '</openid>' # 使用者標識
  bodyData += '<out_trade_no>' + out_trade_no + '</out_trade_no>' # 商戶訂單號
  bodyData += '<spbill_create_ip>' + client_ip + '</spbill_create_ip>' # 客戶端終端IP
  bodyData += '<total_fee>' + total_fee + '</total_fee>' # 總金額 單位為分
  bodyData += '<trade_type>JSAPI</trade_type>' # 交易型別 小程式取值如下:JSAPI
  bodyData += '<sign>' + sign + '</sign>'
  bodyData += '</xml>'

  return bodyData


def xml_to_dict(xml_data):
  '''
  xml to dict
  :param xml_data:
  :return:
  '''
  xml_dict = {}
  root = ET.fromstring(xml_data)
  for child in root:
    xml_dict[child.tag] = child.text
  return xml_dict


def dict_to_xml(dict_data):
  '''
  dict to xml
  :param dict_data:
  :return:
  '''
  xml = ["<xml>"]
  for k, v in dict_data.iteritems():
    xml.append("<{0}>{1}</{0}>".format(k, v))
  xml.append("</xml>")
  return "".join(xml)


# 獲取返回給小程式的paySign
def get_paysign(prepay_id, timeStamp, nonceStr):
  pay_data = {
    'appId': client_appid,
    'nonceStr': nonceStr,
    'package': "prepay_id=" + prepay_id,
    'signType': 'MD5',
    'timeStamp': timeStamp
  }
  stringA = '&'.join(["{0}={1}".format(k, pay_data.get(k)) for k in sorted(pay_data)])
  stringSignTemp = '{0}&key={1}'.format(stringA, Mch_key)
  sign = hashlib.md5(stringSignTemp.encode("utf-8")).hexdigest()
  return sign.upper()


# 統一下單支付介面
def payOrder(request):
  import time
  # 獲取價格,和使用者是誰
  price = request.data.get("price")
  user_id = request.data.get("user_id")

  # 獲取客戶端ip
  client_ip, port = request.get_host().split(":")

  # 獲取小程式openid
  openid = users.objects.get(id=user_id).openid

  # 請求微信的url
  url = order_url

  # 拿到封裝好的xml資料
  body_data = get_bodyData(openid, client_ip, price)

  # 獲取時間戳
  timeStamp = str(int(time.time()))

  # 請求微信介面下單
  respone = requests.post(url, body_data.encode("utf-8"), headers={'Content-Type': 'application/xml'})

  # 回覆資料為xml,將其轉為字典
  content = xml_to_dict(respone.content)
  print(content)
  # 返回給呼叫函式的資料
  ret = {"state": 1000}
  if content["return_code"] == 'SUCCESS':
    # 獲取預支付交易會話標識
    prepay_id = content.get("prepay_id")
    # 獲取隨機字串
    nonceStr = content.get("nonce_str")

    # 獲取paySign簽名,這個需要我們根據拿到的prepay_id和nonceStr進行計算簽名
    paySign = get_paysign(prepay_id, timeStamp, nonceStr)

    # 封裝返回給前端的資料
    data = {"prepay_id": prepay_id, "nonceStr": nonceStr, "paySign": paySign, "timeStamp": timeStamp}
    print('=========',data)

    ret["msg"] = "成功"
    return data

  else:
    ret["state"] = 1001
    ret["msg"] = "失敗"
    return ret

3、前段獲取後端返回的資料給微信再次傳送資料請求!(包含點選的時候往後端傳送資料處理請求)

pay(){
        uni.request({
          url: 'http://127.0.0.1:8000/payOrder/',
          method: 'POST',
          header: {
            'content-type': 'application/json'
          },
          data: {
            user_id:this.user_id,
            price:128
          },
          success: res => {
            console.log("success")
            console.log(res.data)
            
            uni.requestPayment({
            provider: 'wxpay',
            
            timeStamp: res.data.timeStamp,
            nonceStr: res.data.nonceStr,
            package: 'prepay_id='+String(res.data.prepay_id),
            signType: 'MD5',
            paySign: res.data.paySign,
            
            success: function (res) {
              console.log('success:' + JSON.stringify(res));
              // 支付成功,給後臺傳送資料,儲存訂單
              
            },
            fail: function (err) {
              console.log('fail:' + JSON.stringify(err));
              // 支付失敗,給後臺傳送資料,儲存訂單
            }
            });

            
            
          },
          fail: (res) => {
            console.log("fail")
            console.log(res)
          },
          complete: () => {}
        });
        
        
      }

至此相信大家也就會了。

附上我的目錄結構

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援碼農教程。