tangning 2 vuotta sitten
vanhempi
commit
1bf77f4e6a

+ 33 - 2
src/api/api.ts

@@ -1,5 +1,8 @@
 import { request } from "@/utils/request";
-
+interface logonParam {
+    code:string,
+    orderSn:string,
+}
 export const getOrder = (orderSn) => {
   return request({
     url: "/service/pay/order/info",
@@ -30,7 +33,20 @@ export const openPay = (data) => {
     });
   };
 
-
+  export const wxLogin = (data:logonParam) => {
+    return request({
+      url: "/service/pay/wxLogin",
+      method: "get",
+      data,
+      config: {
+        timeout: 10000,
+        headers: {
+            "Content-Type": "application/json;charset=UTF-8",
+        },
+      },
+    });
+  };
+  
 export const getOrderInfo = (orderSn) => {
     return request({
       url: `/service/pay/order/info/${orderSn}`,
@@ -43,3 +59,18 @@ export const getOrderInfo = (orderSn) => {
       },
     });
   };
+
+export const queryOrderStatus = (data) => {
+    return request({
+      url: `/ucenter/user/order/queryOrderStatus`,
+      method: "post",
+      data,
+      config: {
+        timeout: 10000,
+        loading: true,//隐藏进度条
+        headers: {
+            "Content-Type": "application/json;charset=UTF-8",
+        },
+      },
+    });
+  };

+ 5 - 5
src/components/Toast/Confirm.vue

@@ -1,21 +1,21 @@
 <template>
   <div class="xtx-confirm">
     <div class="wrapper" ref="target">
-      <div class="header" v-if="title">
-        <h3>{{ title }}</h3>
+      <div class="header" v-if="options.title">
+        <h3>{{ options.title }}</h3>
         <a href="JavaScript:;" class="iconfont icon-close-new" @click="cancelCallback"></a>
       </div>
       <div class="body">
         <div class="typeImg">
           <img
             style="height: 48px; width: 48px"
-            v-if="type == 'success'"
+            v-if="options.type == 'success'"
             src="@/assets/images/icon/success.png"
             alt=""
           />
           <img
             style="height: 48px; width: 48px"
-            v-else-if="type == 'warn'"
+            v-else-if="options.type == 'warn'"
             src="@/assets/images/icon/warn.png"
             alt=""
           />
@@ -82,7 +82,7 @@ export default {
       props.options.callback()
       props.close()
     }
-    return { target,confirmCallback,cancelCallback }
+    return { options:props.options,target,confirmCallback,cancelCallback }
   }
 }
 </script>

+ 10 - 4
src/stores/user.ts

@@ -2,15 +2,21 @@ import { ref, computed } from 'vue'
 import { defineStore } from 'pinia'
 
 export const useUserStore = defineStore('user', () => {
-  const token = ref('')
+  const token = ref(localStorage.getItem('token'))
+  const openId = ref(localStorage.getItem('openId'))
   const info = ref({
     userName: '我的测试',
+    orderSn: '',
   })
   const isEur = ref(false)
-  const getToken = computed(() => token.value )
-  function setToken(newToken:string) {
+  const getToken = computed(() => token.value || localStorage.getItem('token'))
+  function setToken(newToken: string) {
     token.value = newToken
   }
+  function setUserData(value, name) {
+    [name].value = value
+    localStorage.setItem(value, name)
+  }
   isEur.value = window.location.hostname.includes('eur')
-  return { token, getToken, setToken, info ,isEur}
+  return { token, getToken, setToken, info, isEur, openId, setUserData }
 })

+ 6 - 1
src/utils/api.js

@@ -1,6 +1,7 @@
 import axios from "axios";
 import { ElLoading, ElMessage } from "element-plus";
 import router from "@/router";
+let token = (localStorage && localStorage.getItem('token')) || 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxNTkxNTgxNjA0MSIsImxvZ2luVHlwZSI6InVzZXIiLCJ1c2VyTmFtZSI6IjE1OTE1ODE2MDQxIiwiaWF0IjoxNjgxODAzNzY1LCJqdGkiOiJhMDU4M2EwZS01M2EzLTQ1YTUtOTI1ZS1kZDgzYzU5Y2Y5MGMifQ.bdu5jqbSxSlo9LH4w_uPEuP67DUJk6w5Yqnu633OtQI'
 // request是一个axios实例,每一个实例你都可以单独定制它的baseURL,超时时间,请求头和一些其他配置项。
 const baseUrl = import.meta.env.VITE_BASE_URL; //接口统一域名
 const instance = axios.create({
@@ -10,6 +11,7 @@ const instance = axios.create({
         "Content-Type": "application/json;charset=UTF-8;",
         "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
         ".AspNetCore.Culture": "c=zh-Hans|uic=zh-Hans",
+        token:token,
     },
 });
 
@@ -38,7 +40,10 @@ const hideLoading = () => {
 //请求拦截器
 instance.interceptors.request.use(
     (config) => {
-        showLoading();
+        console.log('config',config.loading,'if',config.loading != true)
+        if(!config.loading){
+            showLoading();
+        }
         // 每次发送请求之前判断是否存在token,如果存在,则统一在http请求的header都加上token,不用每次请求都手动添加了
         //若请求方式为post,则将data参数转为JSON字符串
         if (config.method === "POST") {

+ 12 - 1
src/utils/index.ts

@@ -91,6 +91,17 @@ export const withInstall = <T>(component: T, alias?: string) => {
   };
   return component as T & Plugin;
 };
+//请求微信接口,用来获取code
+export async function getWeChatCode(appid) {
+  const local = encodeURIComponent(window.location.href) //一定要用encodeURIComponent方法获取当前页面地址作为回调地址
+  //通过微信官方接口获取code之后,会重新刷新设置的回调地址【redirect_uri】
+  window.location.href =
+    'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
+    appid +
+    '&redirect_uri=' +
+    local +
+    '&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect&connect_redirect=1'
+}
 
 export function GetRequest(value: string) {
   var url = decodeURI(window.location.search); //?id="123456"&name="www";
@@ -103,6 +114,6 @@ export function GetRequest(value: string) {
       object[strs[i].split("=")[0]] = strs[i].split("=")[1];//得到{id:'123456',name:'www'}
     }
   }
-  console.log('GetRequest',object)
+  console.log('GetRequest', object)
   return object[value];
 }

+ 28 - 14
src/views/mobile/index.vue

@@ -2,13 +2,14 @@
 import { showConfirm } from '@/components/Toast'
 import { ref, computed, onMounted } from 'vue'
 import { useUserStore } from '@/stores/user'
-import { openPay, getOrderInfo } from '@/api/api'
-import { useRoute } from 'vue-router';
-import { GetRequest } from '@/utils/index'
+import { openPay, getOrderInfo, wxLogin } from '@/api/api'
+import { useRoute } from 'vue-router'
+import { GetRequest, getWeChatCode } from '@/utils/index'
 const payType = ref('0')
 const route = useRoute()
 const orderDetal = ref({})
 const orderSn = ref(route.query.id || GetRequest('orderSn'))
+const { getToken, openId, isEur, info, setUserData } = useUserStore()
 const is_weixn = computed(() => {
   if (typeof WeixinJSBridge == 'undefined') {
     return false
@@ -23,29 +24,31 @@ const is_weixn = computed(() => {
 // }
 //判断是否微信
 onMounted(() => {
+  console.log('useUserStore',getToken, openId, isEur, info)
   getDetial()
 })
-const { token, info, isEur } = useUserStore()
 async function handelPay() {
   let apiData = {
     orderSn: orderSn.value,
-    payType: !is_weixn.value ? '1' : payType.value,
+    payType: is_weixn.value ? '1' : payType.value,
     openId: 'dolor exercitation velit'
   }
-  // const res = await openPay(apiData)
+  const res = await openPay(apiData)
   // console.log('apiData', res)
   if (is_weixn.value) {
     //微信内支付
     onBridgeReady(res)
+  } else if (res.form || res.h5Url) {
+    console.log('payType', res.form || res.h5Url)
+    window.location.href = res.form || res.h5Url
   } else {
     showConfirm({
-          text: '成功了',
-          type: 'warn',
-          callback: (val) => {
-            console.log('我的测试计划', val)
-          }
-        })
-    // window.location.href = res.form || res.h5Url
+      text: '支付异常',
+      type: 'err',
+      callback: (val) => {
+        console.log('我的测试计划', val)
+      }
+    })
   }
 }
 // 调微信支付
@@ -95,8 +98,19 @@ function handleType(params: string) {
 function getDetial() {
   getOrderInfo(orderSn.value).then((res) => {
     orderDetal.value = res
+    handleWxlogin(res.wxAppId)
   })
 }
+async function handleWxlogin(wxAppId:string) {
+  const code = GetRequest('code')
+  if(!openId && !code){//微信登录
+    getWeChatCode(wxAppId)
+  }else if(code){//存在code 换取openid
+    const res = wxLogin({code,orderSn})
+    setUserData(res.openId,'openId')
+    console.log('wxLogin', res)
+  }
+}
 async function handleOpenPay() {
   openPay({
     orderSn: GetRequest('orderSn'),
@@ -147,7 +161,7 @@ async function handleOpenPay() {
     </div>
     <div class="bottomInfo">
       <div class="price">
-        应付金额<span>¥{{ orderDetal?.orderMoney || 0.00 }}</span>
+        应付金额<span>¥{{ orderDetal?.orderMoney || 0.0 }}</span>
       </div>
       <div class="payBut" @click="handelPay">付款</div>
     </div>

+ 46 - 8
src/views/pc/index.vue

@@ -7,23 +7,24 @@ import logoEn from '@/assets/images/logoEn.png'
 import { useUserStore } from '@/stores/user'
 import QrcodeVue from 'qrcode.vue'
 import { show, showConfirm } from '@/components/Toast'
-import { openPay } from '@/api/api'
+import { openPay, queryOrderStatus } from '@/api/api'
 import { useRouter, useRoute } from 'vue-router';
 import { GetRequest } from '@/utils/index'
 import { getCurrentInstance } from 'vue'
 
 //得到i18n的locale token, info, 
 const { locale: language } = useI18n()
+let t1 = null
 const route = useRoute()
 const { isEur, info } = useUserStore()
 console.log('route',route)
 const orderSn = ref(route.query.id || GetRequest('orderSn'))
 let { $cdn } = getCurrentInstance()?.proxy;
 let PAYSID = {
-  wechatPay: 2,
-  alipay: 3,
-  paypal: 0
-}
+  wechatPay: 0,
+  alipay: 1,
+  paypal: 2,
+};
 const selectedPayType = ref('alipay')
 watch(selectedPayType, () => {
   getCode()
@@ -38,16 +39,53 @@ onMounted(() => {
   getCode()
 })
 
-
+function inverRequest() {
+      clearInterval(t1);
+      t1 = null;
+      t1 = setInterval(() => {
+        handleQueryOrderStatus();
+      }, 5000);
+}
+async function handleQueryOrderStatus() {
+      if (t1) {
+        let params = {
+          orderSn:orderSn.value,
+          // orderType: Number(orderType),//预订单无支付方式
+          payType: Number(PAYSID[selectedPayType.value]),
+        };
+        let res = await queryOrderStatus(params);
+        let response = res.data;
+        if (response.code === 0 && response.data) {
+          t1 = null;
+          t1 && clearInterval(t1);
+          showConfirm({
+          text: '支付成功',
+          type: 'success',
+          callback: (val) => {
+            console.log('点击支付,支付成功', val)
+          }
+        })
+          // this.$store.dispatch('getInfo', {url: '/user/getUserInfo', name: 'info'})
+          // this.$toast.show('success', this.$t('mall.member.buySuccessTip'), () => {
+          //   this.$router.push('/information')
+          // })
+        }
+      }
+}
 async function getCode() {
   qrCodeUrl.value = ''
+  let paysidtype = {
+  wechatPay: 2,
+  alipay: 3,
+  paypal: 0
+}
   openPay({
     orderSn:orderSn.value,
-    payType:PAYSID[selectedPayType.value],
+    payType:paysidtype[selectedPayType.value],
     openId:'',
   }).then(res => {
     qrCodeUrl.value = res.qrCodeUrl
-    console.log(res, '请求数据')
+    inverRequest()
   })
 }
 </script>

+ 5 - 0
vite.config.ts

@@ -41,6 +41,11 @@ export default defineConfig({
         target: 'https://test.4dkankan.com/',
         changeOrigin: true,
         // rewrite: (path) => path.replace(/^\/api/, '')
+      },
+      '/ucenter': {
+        target: 'https://test.4dkankan.com/',
+        changeOrigin: true,
+        // rewrite: (path) => path.replace(/^\/api/, '')
       }
     }
  },