H5页面 拦截微信授权 + 微信签名 + 微信支付 + 注意事项

目录

一、提示只能在微信客户端打开H5

二、微信授权登录

三、VUE移动端使用vConsole的调试工具

四、微信分享签名

五、微信公众号微信支付封装

六、适配大屏手机,更改背景图


一、提示只能在微信客户端打开H5

若需要微信授权获取用户的信息以及微信签名,则需要用户在微信客户端打开H5

在main.js中拦截

wxTips 组件

<template>
  <div id="app">
    <div class="wx-tips-image">
      <img :src="tipsImgUrl" alt="">
    </div>
    <div class="wx-tips-text">
      <h4>请在微信客户端打开链接</h4>
    </div>
  </div>
</template>

<script>
import config from '@/config/'
const tipsImgUrl = `${config.publicPath}wx-common-images/wx-tips.png`
export default {
  name: 'wxTips',
  data () {
    return {
      tipsImgUrl
    }
  },
  mounted () {

  },
  methods: {

  }
}
</script>

<style scoped>
#app {
  padding-top: 36PX;
  line-height: 1.6;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  background: #fff;
  width: 100vw;
  height: 100vh;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 999;
  overflow: hidden;
  box-sizing: border-box;
}
.wx-tips-image{
  text-align: center;
  margin-bottom: 30PX;
}
.wx-tips-image > img {
  width: 110PX;
  height: 110PX;
}
.wx-tips-text {
  text-align: center;
}
.wx-tips-text > h4 {
  margin-bottom: 5PX;
  font-weight: 400;
  font-size: 20PX;
}
</style>
import wxTips from '@/components/wxTips'
import { screenDirectionChangeTips, browser, getUrlParam } from '@/utils/utils'

let isWeixin = getUrlParam('isWeixin') || browser.versions.weixin

if (isWeixin) {
  // 竖屏横屏提醒
  screenDirectionChangeTips(() => {
    // 竖屏状态
    document.querySelector('#screen-direction-tips').style.display = 'none'
  }, () => {
    // 横屏状态
    document.querySelector('#screen-direction-tips').style.display = 'block'
  })
  // 微信网页授权登录
  console.log('微信环境')

  // 本地调试 ---s
  let token = getUrlParam('token')

  if (token) {
    // 设置token
    localStorage.setItem('InternalPurchase_TOKEN', token)
  }
  // 本地调试 ---e

  // 微信登录 根据自己的业务场景来
  xtsMpLogin().then(wxLoginRes => {
    if (wxLoginRes === 'code success') {
      // 没有token,留在当前页,填写信息获取token
      new Vue({
        render: h => h(App)
      }).$mount('#app')
    } else {
      // 有token,标明已经登录及完成信息,跳转到个人信息页面
      const publicPath = config.ENV === 'prod' ? '/xx/' : '/xxx/'
      let url = `${window.location.origin}/${publicPath}/xxx.html?recommendCode=${getUrlParam('xxx') || ''}&enterpriseCode=${getUrlParam('xxx') || ''}`
      window.location.href = url
    }
  })
} else {
  // 非微信环境提示
  console.log('非微信环境')
  new Vue({
    render: h => h(wxTips)
  }).$mount('#app')
}

二、微信授权登录

参考微信开发文档:网页授权 | 微信开放文档

当前是否存在code,不存在则调用微信公众号网页授权登录换取code,并保存在本地;

存在则说明已登录过

// 微信公众号网页授权登陆换取code
const $wxLogin = () => {
  const appId = ''
  const currentUrl = encodeURIComponent(location.href.split('#')[0])
  const wxAuthorizeUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${currentUrl}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
  window.location.href = wxAuthorizeUrl
}
// 获取登陆token
const xtsMpLogin = () => {
  return new Promise((resolve, reject) => {
    let token = localStorage.getItem('TOKEN') || ''
    if (!token) {
      const code = getUrlParam('code') || localStorage.getItem('CODE') || ''
      if (!code) {
        $wxLogin()
      } else {
        // 设置code-
        localStorage.setItem('CODE', code)
        resolve('code success')

        // let params = {
        //   code
        // }
        // // console.log('后台微信登录参数:', params)
        // $get('/xxx', params).then(res => {
        //   console.log('loginUrl获取token:', res)
        //   let { code, data } = res
        //   if (code === 0) {
        //     let token = data
        //     // 设置token
        //     localStorage.setItem('TOKEN', token)
        //     // 删除微信返回code 重新跳转url
        //     let paramObj = parseUrlParamToObj()
        //     delete paramObj['code']
        //     delete paramObj['state']
        //     // resolve('wxLogin auth')
        //     window.location.replace(parseUrlParamToStr(paramObj))
        //     // resolve('wxLogin success')
        //   } else {
        //     console.log(`接口报错`)
        //   }
        // })
      }
    } else {
      // 授权过没过期 根据自己的业务场景来
      console.log('微信网页授权,本地有token')
      resolve('hasTokenNow')
    }
  })
}

三、VUE移动端使用vConsole的调试工具

安装:

npm install vconsole

在main.js中引入:

仅在开发和测试环境可打开调试

import Vconsole from 'vconsole'
if (process.env.NODE_ENV === 'development') {
  let vConsole = new Vconsole()
  Vue.use(vConsole)
}

四、微信分享签名

参考微信开发文档:概述 | 微信开放文档

微信签名封装:

微信公众号获取签名信息封装:

// 微信公众号获取签名信息
const fetchWXSignature = () => {
  let url = location.href.split('#')[0]
  return new Promise((resolve, reject) => {
    $post('/wechat/jsapi/ticket/createJsapiSignature', { url }).then(res => {
      console.log('微信签名信息:', res)
      let { code, data } = res
      if (code === 0) {
        $wxConfig(data)
        resolve(`wxConfig:success`)
      } else {
        reject(res)
      }
    }).catch(err => {
      reject(err)
    })
  })
}

微信公众号签名配置:

// 微信公众号签名配置
const $wxConfig = serverJson => {
  console.log(`serverJson:`, serverJson)
  let { appId, timestamp, nonceStr, signature } = serverJson
  wx.config({
    debug: false,
    appId: appId, // 必填,公众号的唯一标识
    timestamp: timestamp, // 必填,生成签名的时间戳
    nonceStr: nonceStr, // 必填,生成签名的随机串
    signature: signature, // 必填,签名,见附录1
    jsApiList: [
      // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
      'checkJsApi',

      'onMenuShareTimeline',
      'onMenuShareAppMessage',
      'onMenuShareQQ',
      'onMenuShareWeibo',
      'onMenuShareQZone',

      'hideMenuItems',
      'showMenuItems',
      'hideAllNonBaseMenuItem',
      'showAllNonBaseMenuItem',
      'translateVoice',
      'startRecord',
      'stopRecord',
      'onVoiceRecordEnd',
      'playVoice',
      'onVoicePlayEnd',
      'pauseVoice',
      'stopVoice',
      'uploadVoice',
      'downloadVoice',
      'chooseImage',
      'previewImage',
      'uploadImage',
      'downloadImage',
      'getNetworkType',
      'openLocation',
      'getLocation',
      'hideOptionMenu',
      'showOptionMenu',
      'closeWindow',
      'scanQRCode',
      'chooseWXPay',
      'openProductSpecificView',
      'addCard',
      'chooseCard',
      'openCard'
    ]
  })
}

微信公众号分享配置:

// 微信公众号分享配置
const $wxShareConfig = shareJson => {
  console.log(`shareJson:`, shareJson)
  let { title, desc, link, imgUrl, type = 'link' } = shareJson
  wx.ready(function () {
    // 分享给朋友 及 分享到QQ
    wx.updateAppMessageShareData(
      {
        // 分享设置
        title: title, // 分享标题
        desc: desc, // 分享描述
        link: link, // 分享链接
        imgUrl: imgUrl // 分享图标
      },
      function () {}
    )
    // 分享到朋友圈 及 分享到QQ空间
    wx.updateTimelineShareData(
      {
        title: title, // 分享标题
        link: desc, // 分享链接
        imgUrl: imgUrl // 分享图标
      },
      function () {}
    )

    // 以下是旧版
    // 分享给朋友
    wx.onMenuShareAppMessage({
      title: title, // 分享标题
      desc: desc, // 分享描述
      link: link, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
      imgUrl: imgUrl, // 分享图标
      type: type, // 分享类型,music、video或link,不填默认为link
      dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
      success: function () {
        // 用户点击了分享后执行的回调函数
      }
    })
    // 分享到朋友圈
    wx.onMenuShareTimeline({
      title: title, // 分享标题
      link: link, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
      imgUrl: imgUrl, // 分享图标
      success: function () {
        // 用户点击了分享后执行的回调函数
      }
    })
    // 分享到QQ
    wx.onMenuShareQQ({
      title: title, // 分享标题
      desc: desc, // 分享描述
      link: link, // 分享链接
      imgUrl: imgUrl, // 分享图标
      success: function () {
        // 用户确认分享后执行的回调函数
      },
      cancel: function () {
        // 用户取消分享后执行的回调函数
      }
    })
    // 分享到QQ空间
    wx.onMenuShareQZone({
      title: title, // 分享标题
      desc: desc, // 分享描述
      link: link, // 分享链接
      imgUrl: imgUrl, // 分享图标
      success: function () {
        // 用户确认分享后执行的回调函数
      },
      cancel: function () {
        // 用户取消分享后执行的回调函数
      }
    })
  })
}

流程如下:

import { fetchWXSignature, $wxShareConfig } from '@/utils/wxUtils'
  created () {
    this.wxInitSettingConfig()
  },
    // 微信配置
    wxInitSettingConfig () {
      const publicPath = config.ENV === 'prod' ? '/xxx/' : '/xx/'
      let link = `${window.location.origin}/${publicPath}/xxx.html}`

      let shareConfig = {
        title: `标题`,
        desc: `描述`,
        link,
        imgUrl: ``
      }
      fetchWXSignature().then(res => {
        $wxShareConfig(shareConfig)
      }).catch(err => {
        console.log('后台返回微信签名失败', err)
      })
    },

五、微信公众号微信支付封装

// 微信公公众微信支付
const $wxPay = wxPayParams => {
  /* eslint-disable-next-line */
  let { timeStamp, nonceStr, package_wxa, signType, sign } = wxPayParams
  return new Promise((resolve, reject) => {
    wx.chooseWXPay({
      timestamp: timeStamp, // 支付签名时间戳,注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
      nonceStr, // 支付签名随机串,不长于 32 位
      package: package_wxa, // 统一支付接口返回的prepay_id参数值,提交格式如:prepay_id=\*\*\*)
      signType, // 签名方式,默认为'SHA1',使用新版支付需传入'MD5'
      paySign: sign, // 支付签名
      success: res => {
        // 支付成功后的回调函数
        if (res.errMsg === 'chooseWXPay:ok') {
          resolve(res)
        } else {
          reject(res)
        }
      },
      fail: err => {
        // 支付失败后的回调函数
        reject(err)
      },
      cancel: cancelRes => {
        reject(cancelRes)
      }
    })
  })
}

六、适配大屏手机,更改背景图

<style>

html,body {
  position: relative;
  width: 100%;
  height: 100%;
  background:#12a751;
}

#app {
  max-width: 750PX;
  min-width: 320PX;
  width: 100%;
  margin: 0 auto;
  -webkit-overflow-scrolling: touch;/* 解决ios滑动不流畅问题 */
  height: 100%;
  min-height: 1040px; /* 背景图片的高度 */
  background: url("") no-repeat top  center / contain;
  overflow: hidden;
}

</style>

兼容样式:


/* 兼容样式 */
<style scoped>
@media only screen and (min-device-height: 737px) and (-webkit-min-device-pixel-ratio: 2.5) {
  #app {
    min-height: 1140px;
    background: url("") no-repeat top  center  / contain;
  }

}
</style>

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值