yuantianjiao 6 vuotta sitten
vanhempi
commit
6c98989c02
8 muutettua tiedostoa jossa 279 lisäystä ja 83 poistoa
  1. 3
    3
      config/index.js
  2. 2
    1
      package.json
  3. 54
    2
      src/App.vue
  4. 56
    6
      src/store/user/index.js
  5. 50
    6
      src/util/ajax.js
  6. 17
    5
      src/util/api.js
  7. 83
    0
      src/util/share.js
  8. 14
    60
      src/util/util.js

+ 3
- 3
config/index.js Näytä tiedosto

@@ -11,8 +11,8 @@ module.exports = {
11 11
     assetsSubDirectory: 'static',
12 12
     assetsPublicPath: '/',
13 13
     proxyTable: {
14
-      '/app-api': {
15
-        target: 'http://101.132.102.231:8085',
14
+      '/h52019-api': {
15
+        target: 'http://wx.jinchengjiaye.com',
16 16
         changeOrigin: true, // 如果接口跨域,需要进行这个参数配置
17 17
       },
18 18
     },
@@ -55,7 +55,7 @@ module.exports = {
55 55
     // Paths
56 56
     assetsRoot: path.resolve(__dirname, '../dist'),
57 57
     assetsSubDirectory: 'static',
58
-    assetsPublicPath: '/',
58
+    assetsPublicPath: './',
59 59
 
60 60
     /**
61 61
      * Source Maps

+ 2
- 1
package.json Näytä tiedosto

@@ -80,7 +80,8 @@
80 80
     "webpack": "^3.6.0",
81 81
     "webpack-bundle-analyzer": "^2.9.0",
82 82
     "webpack-dev-server": "^2.9.1",
83
-    "webpack-merge": "^4.1.0"
83
+    "webpack-merge": "^4.1.0",
84
+    "weixin-jsapi": "^1.1.0"
84 85
   },
85 86
   "engines": {
86 87
     "node": ">= 6.0.0",

+ 54
- 2
src/App.vue Näytä tiedosto

@@ -1,13 +1,65 @@
1 1
 <template>
2
-  <div id="app">
2
+  <div id="app" v-if="showPage">
3 3
     <router-view/>
4 4
   </div>
5 5
 </template>
6 6
 
7 7
 <script>
8 8
 import './assets/css/reset.css'
9
+import { createNamespacedHelpers } from 'vuex'
10
+const { mapActions: mapIndexActions } = createNamespacedHelpers('user')
11
+const { mapState: mapUserState } = createNamespacedHelpers('user')
9 12
 export default {
10
-  name: 'App'
13
+  name: 'App',
14
+  data () {
15
+    return {
16
+      showPage: false,
17
+      code: ''
18
+    }
19
+  },
20
+  created () {
21
+    this.init()
22
+    this.getAppId().then(() => {
23
+      console.log(this.appid)
24
+    })
25
+  },
26
+  computed: {
27
+    ...mapUserState({
28
+      userInfo: item => item.userInfo,
29
+      appid: item => item.appid
30
+    })
31
+  },
32
+  methods: {
33
+    ...mapIndexActions(['getAppId', 'getUser', 'getShare', 'putShare']),
34
+    async init () {
35
+      try {
36
+        await this.getAppId()
37
+        await this.getCode()
38
+        await this.getUser({ code: this.code })
39
+        this.showPage = true
40
+        this.putShare()
41
+      } catch (err) {
42
+        console.log(err)
43
+      }
44
+    },
45
+    getCode () {
46
+      return new Promise((resolve, reject) => {
47
+        if (location.search && this.toolClass.UrlSearch(location.search).code) {
48
+          this.code = this.toolClass.UrlSearch(location.search).code
49
+          let oldCode = localStorage.getItem('code')
50
+          if (this.code === oldCode) {
51
+            localStorage.setItem('code', this.code)
52
+            this.toolClass.getCode(this.appid)
53
+          } else {
54
+            localStorage.setItem('code', this.code)
55
+            resolve()
56
+          }
57
+        } else {
58
+          this.toolClass.getCode(this.appid)
59
+        }
60
+      })
61
+    }
62
+  }
11 63
 }
12 64
 </script>
13 65
 

+ 56
- 6
src/store/user/index.js Näytä tiedosto

@@ -1,21 +1,71 @@
1 1
 import Ajax from '../../util/ajax'
2 2
 import api from '../../util/api'
3
+import wxsdk from '@/util/share'
3 4
 
4 5
 export default {
5 6
   namespaced: true,
6 7
   state: {
7
-    userInfo: null
8
+    userInfo: null,
9
+    appid: null,
10
+    shareNum: 0
8 11
   },
9 12
   mutations: {
13
+    updateAppId (state, data) {
14
+      state.appid = data.message.appid
15
+    },
16
+    updateUserInfo (state, data) {
17
+      state.userInfo = data || {}
18
+    },
19
+    updateShareNum (state, data) {
20
+      state.shareNum = data || 0
21
+    }
10 22
   },
11 23
   actions: {
12
-    getUserInfo (context, payload) { // 获取手机验证码
24
+    getAppId (context) {
25
+      return new Promise((resolve, reject) => {
26
+        Ajax({
27
+          ...api.getAppId
28
+        }).then(res => {
29
+          context.commit('updateAppId', res)
30
+          resolve(res)
31
+        }).catch((res) => {
32
+          reject(res)
33
+        })
34
+      })
35
+    },
36
+    getUser (context, payload) {
37
+      return new Promise((resolve, reject) => {
38
+        wxsdk({ url: encodeURIComponent(window.location.href.split('#')[0]), code: payload.code }, {
39
+          title: '2019,这些我都想要! ',
40
+          desc: '立下Flag,打开你的新年心愿清单',
41
+          link: `${window.location.origin}${window.location.pathname}#/home`,
42
+          thu_image: `https://jingcheng-h5temp.oss-cn-shanghai.aliyuncs.com/20181229-images/share_20181229165703.jpg?x-oss-process=style/wxicon`
43
+        }).then((res) => {
44
+          context.commit('updateUserInfo', res)
45
+          resolve(res)
46
+        }).catch((err) => {
47
+          reject(err)
48
+        })
49
+      })
50
+    },
51
+    getShare (context) {
52
+      return new Promise((resolve, reject) => {
53
+        Ajax({
54
+          ...api.getShare
55
+        }).then(res => {
56
+          context.commit('updateShareNum', res)
57
+          resolve(res)
58
+        }).catch((res) => {
59
+          reject(res)
60
+        })
61
+      })
62
+    },
63
+    putShare (context) {
64
+      console.log(context)
13 65
       return new Promise((resolve, reject) => {
14
-        Ajax(api.user.getUserInfo.url, {
15
-          method: api.user.getUserInfo.method,
16
-          token: payload
66
+        Ajax({
67
+          ...api.putShare
17 68
         }).then(res => {
18
-          console.log(JSON.stringify(res))
19 69
           resolve(res)
20 70
         }).catch((res) => {
21 71
           reject(res)

+ 50
- 6
src/util/ajax.js Näytä tiedosto

@@ -1,5 +1,17 @@
1 1
 import axios from 'axios'
2 2
 import qs from 'qs'
3
+import { Toast } from 'vant'
4
+
5
+const token = function (headers) {
6
+  let JWT = ''
7
+  if (headers) {
8
+    localStorage.setItem('JWT', headers.authorization)
9
+    JWT = headers.authorization
10
+  }
11
+  const token = JWT ? JWT : localStorage.getItem('JWT') // eslint-disable-line
12
+
13
+  return !token ? '' : token
14
+}
3 15
 
4 16
 const Axios = axios.create({
5 17
   timeout: 60000,
@@ -7,17 +19,21 @@ const Axios = axios.create({
7 19
   withCredentials: true,
8 20
   queryData: {},
9 21
   urlData: {},
22
+  headerData: '',
10 23
   headers: {
11
-    'Content-Type': 'application/json',
12
-    'X-Auth-Token': ''
24
+    'Content-Type': 'multipart/form-data',
25
+    'authorization': token()
13 26
   }
14 27
 })
15 28
 
16 29
 Axios.interceptors.request.use((config) => {
17
-  let aName = 'X-Auth-Token'
18
-  config.headers[aName] = config.token || ''
30
+  config.headers.authorization = token()
31
+  config.headers['Content-Type'] = config.headerData ? config.headerData : 'multipart/form-data'
32
+  // config.urlData = { ...config.urlData,  }
33
+  // 处理请求data,若为get请求,拼到url后面,若为post请求,直接添加到body中
19 34
   let urlData = qs.stringify(config.urlData)
20 35
   let queryData = qs.stringify(config.queryData)
36
+  // 判断是通过斜杠传参
21 37
   if (config.url.indexOf(':') > -1) {
22 38
     if (typeof config.urlData === 'object') {
23 39
       config.url = replaceURLParams(config.url, config.urlData)
@@ -28,7 +44,22 @@ Axios.interceptors.request.use((config) => {
28 44
   if (queryData) {
29 45
     config.url += '?' + queryData
30 46
   }
31
-  return config
47
+  if (config.headerData) {
48
+    return config
49
+  } else {
50
+    let fm = new FormData()
51
+    for (let k in config.data) {
52
+      if (Array.isArray(config.data[k])) {
53
+        config.data[k].forEach((v) => {
54
+          fm.append(k, v)
55
+        })
56
+      } else {
57
+        fm.append(k, config.data[k])
58
+      }
59
+    }
60
+    config.data = fm
61
+    return config
62
+  }
32 63
 }, (error) => {
33 64
   console.log(error)
34 65
 })
@@ -36,7 +67,20 @@ Axios.interceptors.request.use((config) => {
36 67
 const ajax = (...args) => {
37 68
   return new Promise((resolve, reject) => {
38 69
     Axios(...args).then(({ data, headers }) => {
39
-      resolve(data)
70
+      if (headers.authorization) {
71
+        token(headers)
72
+      }
73
+      const { code, message } = data
74
+      if (code === 200) {
75
+        resolve(data)
76
+      } else {
77
+        Toast.fail({
78
+          duration: 2000, // 持续展示 toast
79
+          forbidClick: true, // 禁用背景点击
80
+          message: message
81
+        })
82
+        reject(message)
83
+      }
40 84
     }).catch(reject)
41 85
   })
42 86
 }

+ 17
- 5
src/util/api.js Näytä tiedosto

@@ -1,10 +1,22 @@
1 1
 
2
+const baseurl = '/h52019-api'
3
+
2 4
 const $api = {
3
-  user: {
4
-    getUserInfo: { // 获取用户信息
5
-      method: 'get',
6
-      url: `/app-api/user/info`
7
-    }
5
+  getAppId: { // 获取appid
6
+    method: 'get',
7
+    url: `${baseurl}/appid`
8
+  },
9
+  getUser: { // 获取用户信息
10
+    method: 'get',
11
+    url: `${baseurl}/user`
12
+  },
13
+  getShare: { // 获取分享总数
14
+    method: 'get',
15
+    url: `${baseurl}/appid`
16
+  },
17
+  putShare: { // 分享成功
18
+    method: 'put',
19
+    url: `${baseurl}/appid`
8 20
   }
9 21
 }
10 22
 

+ 83
- 0
src/util/share.js Näytä tiedosto

@@ -0,0 +1,83 @@
1
+import Ajax from './ajax'
2
+import api from './api'
3
+import wx from 'weixin-jsapi'
4
+
5
+function wxsdk (params, config) {
6
+  // const wx = require('weixin-js-sdk')
7
+  console.log(config)
8
+  const shareData = {
9
+    title: config.title, // 分享标题
10
+    desc: config.desc, // 分享标题
11
+    link: config.link, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
12
+    imgUrl: config.thu_image // 分享图标
13
+  }
14
+  // 初始化
15
+  return new Promise(function (resolve, reject) {
16
+    Ajax({
17
+      ...api.getUser,
18
+      queryData: {
19
+        ...params
20
+      }
21
+    }).then(result => {
22
+      console.log(result)
23
+      let time = parseInt(result.timestamp)
24
+      wx.config({
25
+        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
26
+        appId: result.appId, // 必填,公众号的唯一标识
27
+        timestamp: time, // 必填,生成签名的时间戳
28
+        nonceStr: result.noncestr, // 必填,生成签名的随机串
29
+        signature: result.signature, // 必填,签名,见附录1
30
+        jsApiList: [
31
+          'onMenuShareTimeline',
32
+          'onMenuShareAppMessage',
33
+          'onMenuShareQQ',
34
+          'onMenuShareWeibo',
35
+          'onMenuShareQZone',
36
+          'openLocation',
37
+          'getLocation'
38
+        ]
39
+      })
40
+      wx.ready(function () {
41
+        wx.onMenuShareTimeline(shareData)
42
+        wx.onMenuShareAppMessage(shareData)
43
+        resolve(wx)
44
+      })
45
+
46
+      wx.error(function (err) {
47
+        reject(err)
48
+      })
49
+    }).catch((err) => {
50
+      reject(err)
51
+    })
52
+
53
+    // axios.post(api.share.share.url + '?url=' + params.url)
54
+    //   .then(function (res) {
55
+    //     let result = JSON.parse(res.data)
56
+    //     wx.config({
57
+    //       debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
58
+    //       appId: result.appId, // 必填,公众号的唯一标识
59
+    //       timestamp: result.timestamp, // 必填,生成签名的时间戳
60
+    //       nonceStr: result.noncestr, // 必填,生成签名的随机串
61
+    //       signature: result.signature, // 必填,签名,见附录1
62
+    //       jsApiList: [
63
+    //         'onMenuShareTimeline',
64
+    //         'onMenuShareAppMessage',
65
+    //         'onMenuShareQQ',
66
+    //         'onMenuShareWeibo',
67
+    //         'onMenuShareQZone',
68
+    //         'openLocation'
69
+    //       ]
70
+    //     })
71
+    //     wx.ready(function () {
72
+    //       wx.onMenuShareTimeline(shareData)
73
+    //       wx.onMenuShareAppMessage(shareData)
74
+    //       // resolve()
75
+    //     })
76
+    //   })
77
+    //   .catch(function (error) {
78
+    //     console.log(error)
79
+    //   })
80
+  })
81
+}
82
+
83
+export default wxsdk

+ 14
- 60
src/util/util.js Näytä tiedosto

@@ -28,68 +28,22 @@ const toolClass = {
28 28
       return ''
29 29
     }
30 30
   },
31
-  JsBridge: { // IOS/Android原生交互
32
-    init: function (callback) { // 初始化
33
-      var u = navigator.userAgent
34
-      var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
35
-      if (!isiOS) {
36
-        if (window.WebViewJavascriptBridge) {
37
-          callback(WebViewJavascriptBridge)
38
-        } else {
39
-          document.addEventListener(
40
-            'WebViewJavascriptBridgeReady',
41
-            function () {
42
-              callback(WebViewJavascriptBridge)
43
-            },
44
-            false
45
-          )
46
-        }
47
-      } else {
48
-        if (window.WebViewJavascriptBridge) return callback(WebViewJavascriptBridge)
49
-        if (window.WVJBCallbacks) return window.WVJBCallbacks.push(callback)
50
-        window.WVJBCallbacks = [callback]
51
-        var WVJBIframe = document.createElement('iframe')
52
-        WVJBIframe.style.display = 'none'
53
-        WVJBIframe.src = 'https://__bridge_loaded__'
54
-        document.documentElement.appendChild(WVJBIframe)
55
-        setTimeout(function () { document.documentElement.removeChild(WVJBIframe) }, 0)
56
-      }
57
-    },
58
-    first: function () { // 建立第一次链接
59
-      var u = navigator.userAgent
60
-      var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
61
-      if (!isiOS) {
62
-        var _this = this
63
-        _this.init(function (bridge) {
64
-          bridge.init(function (message, responseCallback) {
65
-            responseCallback(data)
66
-          })
67
-        })
31
+  getCode: (appid) => {
32
+    const refer = window.encodeURIComponent(window.location.href.replace(/code=[^?&#/=]+/, '').replace(/state=[^?&=#/]+/, '').replace(/\?\&+/, '?'))
33
+    let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${refer}&response_type=code&scope=snsapi_userinfo&state=12313#wechat_redirect`
34
+    window.location.href = url
35
+  },
36
+  UrlSearch: (urls) => {
37
+    let url = urls // 获取url中"?"符后的字串
38
+    let theRequest = {}
39
+    if (url.indexOf('?') !== -1) {
40
+      let str = url.substr(1)
41
+      let strs = str.split('&')
42
+      for (var i = 0; i < strs.length; i++) {
43
+        theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1])
68 44
       }
69
-    },
70
-    registerHandler: function (name, fun) { // app通知h5方法
71
-      var _this = this
72
-      _this.init(function (bridge) {
73
-        bridge.registerHandler(name, fun)
74
-      })
75
-    },
76
-    callHandler: function (name, data, fun) { // h5通知app方法
77
-      var _this = this
78
-      _this.init(function (bridge) {
79
-        bridge.callHandler(name, data, fun)
80
-      })
81 45
     }
82
-  },
83
-  returnDoubleNum (num) { // 转化双位数
84
-    return num > 9 ? num : ('0' + num)
85
-  },
86
-  checkPhoneNum (num) { // 校验手机号
87
-    var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
88
-    return !!myreg.test(num)
89
-  },
90
-  checkEmail (num) { // 校验邮箱
91
-    var myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/
92
-    return !!myreg.test(num)
46
+    return theRequest
93 47
   }
94 48
 }
95 49