weChatQrcode.vue 3.3 KB

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