vue+koa2使用微信ssdk实现分享功能

微信转发、分享功能例子,只画重点记录…


微信公众号配置

微信JS-SDK说明文档

1、ip白名单(百度ip),把地址输入 (开发—>基本配置)
在这里插入图片描述
2、配置Js接口安全域名(公众号设置—>功能设置)
在这里插入图片描述

vue

1.安装weixin-js-sdk
npm i weixin-js-sdk -S
2、配置权限验证 wx.config
3、处理成功验证 wx.ready(function(){})

目录
|- api
| |- weixin.js
|- views
| |- home.vue

// weixin.js
import wx from 'weixin-js-sdk' // 微信sdk依赖
import { request } from './index'  //封装的asiox接口

export const getWxConfig = (data) => {
  let url = window.location.href.split('#')[0] //url不能写死
  request.post('/wechat/getConfig', { url: url }).then((resp) => {
    let wxConf = resp.data
    wx.config({
      debug: true,
      appId: wxConf.appId,
      timestamp: wxConf.timestamp,
      nonceStr: wxConf.nonceStr,
      signature: wxConf.signature,
      jsApiList: wxConf.jsApiList
    })

	// 分享给朋友
    wx.ready(function () {
      wx.updateAppMessageShareData({
        title: 'Cat cafe', // 分享标题
        desc: '以猫咪为主题的咖啡馆!', // 分享描述
        link: 'http://xxx.natapp1.cc/', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: 'http://prp6xvxc1.bkt.clouddn.com/1.jpg', // 分享图标
        success: function (res) {
          // 设置成功
          // alert(JSON.stringify(res))
        }
      })

      // 分享到朋友圈
      wx.updateTimelineShareData({
        title: 'Cat cafe!!', // 分享标题
        link: 'http://xxx.natapp1.cc/', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: 'http://prp6xvxc1.bkt.clouddn.com/1.jpg', // 分享图标
        success: function (res) {
          // 设置成功
          console.log('5555')
          console.log(JSON.stringify(res))
        }
      })

      wx.error(function (res) {
        alert(JSON.stringify(res))
        // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
      })
    })
  })
}
// home.vue
<template>
  <div>
    vue微信ssdk使用步骤
  </div>
</template>

<script>
import { getWxConfig } from '@/api/weixin'
export default {
  created () {
    getWxConfig()
  }
}
</script>

koa2

1.安装wechat-api
 cnpm install wechat-api --save
2、引入var API = require('wechat-api');  
3、实例化配置
var api = new API(config.wxappid,config.wxappsecret) ;
4、生成config的参数
var param = {  
         debug: false,  
         jsApiList: ['checkJsApi',              
                 'chooseImage',            
                 'getNetworkType',
                 'openLocation',
                 'getLocation',             
                 'scanQRCode'
         ],  
         url: req.body.url  
 };  
 api.getJsConfig(param, function(err,result){  
         res.send(result);  
 }); 

|- module
| |- config.js
|- routes
| |- wechat.js

const router = require('koa-router')()
// 引入统一下单的api
const config = require('../module/config')
// 用来生成签名、config的参数
const API = require('wechat-api') 
const api = new API(config.wxappid, config.wxappsecret)

router.post('/wechat/getConfig', async (ctx, next) => {
  // 使用wechat-api获取JSconfig
  var param = {
    debug: false,
    jsApiList: ['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',
      'updateAppMessageShareData',
      'updateTimelineShareData'],
    url: ctx.request.body.url
  }

  //生成config的参数
  api.getJsConfig(param, function (err, data) {
   //  console.log(err)
   ctx.body = { 'success': 'true', 'data': data, 'code': '200' }
  })
})

module.exports = router

// module/config.js
var config = {
  mch_id: '153506xxxxx', //商户号(非支付可不填)
  wxappid: 'wx61668303xxxxxx', //AppID   
  wxappsecret: 'f506525621307c15cxxxxxxxxx', //AppSecret 
  wxpaykey: 'c23fdgas768fdhASdsad1xxxxxxxx'  // 商户key(支付API密钥,非支付可不填)
}

module.exports = config

wechat-api 可以用来生成签名,也可自己手动生成,参考另一篇 nodejs实现微信支付

优化

假如很多地方都用到分享功能,可以把它封装起来暴露统一接口(或暴露多个入口)

// 引入封装
import { wxShare } from '@/utils/wechat'
created() {
      wxShare({
        title: '分享标题', // 分享标题
        desc: '分享描述', // 分享描述
        link: window.location.href, // 分享链接
        imgUrl: 'http://图片地址share.png', // 分享图标
   	  //debug:true
    },function(){//分享成功后的回调函数   
    });
}
// utils/wechat.js
import wx from 'weixin-js-sdk'
import { request } from '@/api/index'

// 微信分享
export const wxShare = (obj, callback) => {
  let url = window.location.href.split('#')[0]

  if (obj) {
    var title = obj.title == undefined || obj.title == null ? 'xxxx' : obj.title
    var link = obj.link == undefined || obj.link == null ? window.location.href : obj.link
    var desc = obj.desc == undefined || obj.desc == null ? 'xxxxx' : obj.desc
    var imgUrl = obj.imgUrl == undefined || obj.imgUrl == null ? 'src/img/share.png' : obj.imgUrl
    var debug = obj.debug == true
  } else {
    alert('请传分享参数')
  }

  request.post('/wechat/getConfig', { url: url }).then((resp) => {
    let wxConf = resp.data
    wx.config({
      debug: debug,
      appId: wxConf.appId,
      timestamp: wxConf.timestamp,
      nonceStr: wxConf.nonceStr,
      signature: wxConf.signature,
      jsApiList: wxConf.jsApiList
    })

    wx.ready(function () {
      // 分享给朋友
      wx.updateAppMessageShareData({
        title: title, // 分享标题
        desc: desc, // 分享描述
        link: link, // 分享链接
        imgUrl: imgUrl, // 分享图标
        type: '', // 分享类型,music、video或link,不填默认为link
        dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
        success: function () {
          // 用户确认分享后执行的回调函数
          callback && callback()
        }
      })

      // 分享到朋友圈
      wx.updateTimelineShareData({
        title: title, // 分享标题
        link: link, // 分享链接
        desc: desc, // 分享描述
        imgUrl: imgUrl, // 分享图标
        success: function () {
          callback && callback()
        }
      })

      // 分享到腾讯微博
      wx.onMenuShareWeibo({
        title: title, // 分享标题
        link: link, // 分享链接
        desc: desc, // 分享描述
        imgUrl: imgUrl, // 分享图标
        success: function () {
          callback && callback()
        }
      })

      wx.error(function (res) {
        alert(JSON.stringify(res))
        // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
      })
    })
  })
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值