weChatQrcode.vue 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <template>
  2. <div class="weChatQrCode" v-if="false"></div>
  3. </template>
  4. <script>
  5. import wx from 'weixin-js-sdk'
  6. import { getSignature } from '@/api/wechat'
  7. export default {
  8. data() {
  9. return {
  10. show: false
  11. }
  12. },
  13. methods: {
  14. open() {
  15. if (this.show) return
  16. this.show = true
  17. this.onScan()
  18. },
  19. onScan() {
  20. this.getConfig()
  21. const that = this
  22. try {
  23. console.log('测试测试ready')
  24. console.log(wx.ready)
  25. wx.ready(function() {
  26. console.log('测试2222')
  27. wx.checkJsApi({
  28. // 需要使用的JS接口列表,在这里只需要用到scanQRCode
  29. jsApiList: ['scanQRCode'],
  30. success: function(res1) {
  31. if (res1.checkResult.scanQRCode) {
  32. // 当scanQRCode可使用时
  33. wx.scanQRCode({
  34. needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
  35. scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码,默认二者都有
  36. success: function(res2) {
  37. const result = res2.resultStr
  38. that.$emit('success', result)
  39. // console.log(res2.resultStr, '扫描的结果~')
  40. // window.location.href = result
  41. },
  42. error: function(response) {
  43. this.close()
  44. this.$nextTick(() => {
  45. that.$toast(response)
  46. })
  47. }
  48. })
  49. }
  50. }
  51. })
  52. })
  53. } catch (error) {
  54. console.log(error)
  55. }
  56. },
  57. async getConfig() {
  58. const that = this
  59. const res = await getSignature({ url: encodeURIComponent(window.location.href.split('#')[0]) })
  60. // console.log('res', res)
  61. that.wxConfig(res.data.appId, res.data.params.timestamp, res.data.params.nonceStr, res.data.signature)
  62. },
  63. // wx.config的配置
  64. wxConfig(appId, timestamp, nonceStr, signature) {
  65. const that = this
  66. try {
  67. const params = {
  68. debug: true, // 开启调试模式,
  69. appId: appId, // 必填,企业号的唯一标识
  70. timestamp: timestamp, // 必填,生成签名的时间戳
  71. nonceStr: nonceStr, // 必填,生成签名的随机串
  72. signature: signature, // 必填,签名
  73. jsApiList: ['scanQRCode', 'checkJsApi'] // 必填,需要使用的JS接口列表
  74. }
  75. wx.config(params)
  76. wx.error(function(res) {
  77. console.log('测试测试111')
  78. that.close()
  79. alert('出错了👉' + res.errMsg) // wx.config配置错误,会弹出窗口哪里错误,然后根据微信文档查询即可。
  80. })
  81. console.log('测试测试wxConfig')
  82. } catch (error) {
  83. console.log(error)
  84. }
  85. },
  86. close() {
  87. this.show = false
  88. }
  89. }
  90. }
  91. </script>
  92. <style lang="scss" scoped>
  93. .weChatQrCode {
  94. width: 100%;
  95. height: 100%;
  96. z-index: 9999;
  97. position: fixed;
  98. top: 0;
  99. left: 0;
  100. background: #000;
  101. }
  102. </style>