wxpay.js 2.5 KB
import orderService from './orderService.js'
import router from '../../router/index.js'
import Taro from '@tarojs/taro';
import wx from '../../libs/wx';

// const api = new orderService();
/**
 * orderCode 订单号
 * fromWhere 支付来源页面  0:确认订单页面,1:订单列表,2:订单详情
 */
export const prePay = function (productId, orderCode, fromWhere, isStore) {
  let api = new orderService()
  // wx.showLoading({
  //   title: '',
  // })
  let openID = '';
  try {
    openID = wx.getStorageSync('openid')
  } catch (e) {

  }

  if (openID) {
    api.prePay(orderCode, openID, () => wx.hideLoading())
      .then(data => {
        if (data) {
          callWxPay(data, productId, orderCode, fromWhere, isStore)
        } else {
          throw new Error('ufo.order.pay fail.')
        }
      })
      .catch(() => {
        // 调用出错
        Taro.showToast({
          title: '订单不可支付',
          duration: 1500,
          icon: 'none'
        });

        let currentRoute;
        let currentPages = getCurrentPages();
        if (currentPages && currentPages.length) {
          currentRoute = currentPages[currentPages.length - 1].route;
        }
        let noRedirectRoutes = ['pages/orderDetail/index', 'pages/orderList/index'];
        if (noRedirectRoutes.indexOf(currentRoute) > -1) {
          return;
        }

        setTimeout(() => {
          wx.redirectTo({
            url: '/pages/orderDetail/index?orderCode=' + orderCode
          });
        }, 1500);
      })
  } else {
    //提示重新登录
  }
}

function callWxPay(data, productId, orderCode, fromWhere ,isStore) {
  let that = this;
  // let orderCode = ;
  wx.requestPayment({
    ...data,
    success: function (res) {
      console.log('orderCode:' + orderCode + '==productID:' + productId);
      let params = {
        orderCode: orderCode,
        product_id: productId,
        isStore
      }
      router.go('orderSuccess', params);
    },
    fail: function (res) {
      console.log(res)
      let params = {
        orderCode: orderCode
      }
      if (res.errMsg == 'requestPayment:fail cancel') {
        if (fromWhere == 0) {
          router.go('orderDetail', params, 'redirectTo');
        }

      } else {
        wx.showModal({
          content: res.errMsg,
          showCancel: false,
          confirmText: "确定",
          complete: function (res) {
            if (fromWhere == 0) {
              router.go('orderDetail', params, 'redirectTo');
            }
          }
        })
      }
    }
  })
}