公众号h5分享功能

微信公众号H5分享功能

1.下载 weixin-js-sdk

npm i weixin-js-sdk

2.封装相应方法

cosnt wx = require('weixin-js-sdk')
const {request} = require('./request.js')
// 发起获取signature请求
async function getSignature() {
	// var url = window.location.origin + '/'
	var url = encodeURIComponent(location.href.split('#')[0])
	var res = await request('/apidata/wechat', 'GET',{url})
	setShare(res.data)
}
// 设置分享数据
function setShare(data) {
	var url = window.location.origin + '/'
	// var url = signature.url
	uni.setStorageSync('signature', JSON.stringify(data))
	wx.config({
		debug: false, // 开启调试模式
		// 配置微信 JSSDK
		appId: 'wx012919bd15a360ca', // 必填,公众号的唯一标识
		timestamp: data.timestamp, // 必填,生成签名的时间戳
		nonceStr: data.noncestr, // 必填,生成签名的随机串
		signature: data.signature, // 必填,签名
		jsapi_ticket:data.jsapi_ticket,
		jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData']
	})

	wx.ready(function() {
		// wx.showMenuItems({
		//             menuList: ['menuItem:share:appMessage','menuItem:share:timeline'] // 要显示的菜单项,
		//           })
		wx.updateAppMessageShareData({
			imgUrl: '',
			title: '', 
			link: url, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
			desc: '', 
			success: function(res) {
				console.log('✨✨✨✨✨','分享成功')
			}
		})
		wx.updateTimelineShareData({
			desc: '', 
			title: '', 
			link: url, 
			imgUrl: 'https://weixin.gongrenle.com/uploads/images/ic-dangjian.png',
			success: function() {
				console.log('⭐⭐⭐⭐⭐','分享成功')
			}
		})
	})
	wx.error((res) => {
		console.log(res,'失败')
		// config信息验证失败会执行error函数,
		//如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,
		//也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
	})
}


//分享
function share() {
	const _signature = uni.getStorageSync('signature')
	// 先看看缓存里有没有
	if (_signature) {
		let signature = JSON.parse(_signature)
		// 获取当前时间戳
		var now = parseInt(new Date().getTime() / 1000) + ''
		// 计算两个时间戳之间的差值,单位为秒
		var diff = now - signature.expire_time
		// 判断差值是否大于2小时的秒数,即7200秒
		if (diff > 7200) {
			getSignature()
		} else {
			setShare(signature)
		}
	} else {
		getSignature()
	}
}

module.exports = {
	share
}

3.在相应页面调用方法或者在入口文件中 uniapp开发项目可在onLaunch或者onload中调用

微信公众号h5开发–(微信开发回调、背景音乐自动播放、微信朋友分享、微信扫一扫

开发前提:例如你们域名是https://www.baidu.com

  1. 配置nginx反向代理,把你项目的端口重定向到你们测试环境或线上环境域名
# 访问https://baidu.com 的时候,指向127.0.0.1:8080
#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;
  server {
      listen 80;
      server_name baidu.com;//替换成你的域名
      location / {
          proxy_pass http://127.0.0.1:8080;//替换你项目的
      }
  }
  include servers/*;
}

修改本地host文件 打开host文件最后一行添加127.0.0.1 baidu.com
mac和windows电脑自行百度打开host方式

2.引入微信jsdk 版本1.00 - 1.60都可以

网页授权(静默授权、点击授权)

https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#0

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect

scope 参数: 应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 )

具体实现登录代码如下

// 判断openIdTime是否过期 过期失效12小时
let openIdTime = uni.getStorageSync("openIdTime");
if (openIdTime) {
  let nowTime = new Date().getTime();
  if (nowTime - openIdTime > 43200000) {
    uni.clearStorageSync();
  }
}
let urlParams = new URLSearchParams(window.location.search);
let code = urlParams.get("code");
if (!code) {
  uni.setStorageSync("goto_url", window.location.href);
}
if (!code && !uni.getStorageSync("openId") && this.isAuthorization) {
  this.weChatLoginBtn();
}
this.weixinCompelete();


方法
// 登录
weChatLoginBtn() {
  if (!isWechat()) {
    uni.showToast({
      title: "请在微信中打开",
      icon: "none",
    });
    return;
  }
  this.$res.get(getWechatAppId).then((res) => {
    let appid = this.$res.fun(res);
    let baseUrl = encodeURIComponent(location.href);
    let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${baseUrl}&response_type=code&scope=snsapi_userinfo&state=null#wechat_redirect`;
    window.location.href = url;
  });
},

      weixinCompelete() {
        let urlParams = new URLSearchParams(window.location.search);
        let code = urlParams.get("code");
        let state = urlParams.get("state");
        if (code) {
          getApp().showLoading();
          // 记录此用户已授权
          uni.setStorageSync("isAuthorization", true);
          console.log("登录吧");
          this.$res
            .post(login, {
                code: code,
            })
            .then((res) => {
              getApp().hideLoading();
              if (res.data.status === 200) {
                let data = this.$res.fun(res);
                uni.setStorageSync("token", data.token);
                uni.setStorageSync("userInfo", data);
                uni.setStorageSync("openId", data.openId);
                // 设置openId过期时间
                uni.setStorageSync("openIdTime", new Date().getTime());
               
                let goto_url = uni.getStorageSync("goto_url");
                // 切割goto_url获取参数
                let urlParams = new URLSearchParams(goto_url.split("?")[1]);
                let params = {};
                urlParams.forEach((value, key) => {
                  params[key] = value;
                });
                // 拼接参数
                let url = "";
                for (let key in params) {
                  if (key !== "code" && key !== "state" && key !== "") {
                    url += `${key}=${params[key]}&`;
                  }
                }
                setTimeout(() => {
                  uni.reLaunch({
                    url: `/pages/home/home?${url}`,
                  });
                }, 200);
              } else {
                let goto_url = uni.getStorageSync("goto_url");
                // 切割goto_url获取参数
                let urlParams = new URLSearchParams(goto_url.split("?")[1]);
                let params = {};
                urlParams.forEach((value, key) => {
                  params[key] = value;
                });
                // 拼接参数
                let url = "";
                for (let key in params) {
                  if (key !== "code" && key !== "state" && key !== "") {
                    url += `${key}=${params[key]}&`;
                  }
                }
                uni.reLaunch({
                  url: `/pages/home/home?${url}`,
                });
              }
            });
          return;
        } else {
        	//已经登录
          //直接走自己的下面接口
        }
      },

2、背景音乐自动播放 / 分享给朋友、朋友圈、扫一扫

ios背景音乐播放,微信是不播放的,下面解决这个问题

//jwx.js
export default {
  //判断是否在微信中
  isWechat: function() {
    var ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/micromessenger/i) == "micromessenger") {
      return true;
    } else {
      return false;
    }
  },
  initJssdk: function(callback) {
    var uri = location.href.split("#")[0]; //获取当前url然后传递给后台获取授权和签名信息
    uni.request({
      url: xxx, //你的接口地址
      method: "POST",
      data: {
        url: uri,
      },
      success: (res) => {
        //返回需要的参数appId,timestamp,noncestr,signature等
        //注入config权限配置
        jWeixin.config({
          debug: false,
          appId: res.data.data.appId,
          timestamp: res.data.data.timestamp,
          nonceStr: res.data.data.nonceStr,
          signature: res.data.data.signature,
          jsApiList: [
            //这里是需要用到的接口名称
            "onMenuShareAppMessage", //分享给朋友
            "onMenuShareTimeline", //分享到朋友圈
            "scanQRCode", //扫一扫接口
            "chooseWXPay", //微信支付
            "chooseImage", //拍照或从手机相册中选图接口
            "previewImage", //预览图片接口
            "uploadImage", //上传图片
            "downloadImage", //下载图片
          ],
        });
        if (callback) {
          callback(res.data);
        }
      },
    });
  },
    //在需要自定义分享的页面中调用
  share: function(data, url) {
    url = url ? url : window.location.href;
    if (!this.isWechat()) {
      return;
    }
    //每次都需要重新初始化配置,才可以进行分享
    this.initJssdk(function(signData) {
      jWeixin.ready(function() {
        var shareData = {
          title: data && data.title ? data.title : signData.site_name,
          desc: data && data.desc ? data.desc : signData.site_description,
          link: url,
          imgUrl: data && data.img ? data.img : signData.site_logo,
          success: function(res) {
            //用户点击分享后的回调,这里可以进行统计
          },
          cancel: function(res) {},
        };
        //分享给朋友接口
        jWeixin.onMenuShareAppMessage(shareData);
        //分享到朋友圈接口
        jWeixin.onMenuShareTimeline(shareData);
      });
    }, url);
  },
    // 微信扫一扫
  scanQRCode: function(callBack) {
    if (!this.isWechat()) {
      //console.log('不是微信客户端')
      return;
    }
    //console.log(data);
    this.initJssdk(function(res) {
      jWeixin.ready(function() {
        console.log("微信扫一扫",res);
        jWeixin.scanQRCode({
          needResult: 1,
          scanType: ["qrCode", "barCode"],
          success: function(res) {
            var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果
            if (callBack) callBack(result);
          },
        });
      });
    });
  },
    //在需要自定义分享的页面中调用
  music: function(app, musicUrl, url) {
    url = url ? url : window.location.href;
    if (!this.isWechat()) {
      return;
    }
    //每次都需要重新初始化配置,才可以进行分享
    this.initJssdk(function(signData) {
      jWeixin.ready(function() {
        let globalData = app.globalData;
        // 判断是否有背景音乐实例
        if (globalData && globalData.audioCtx) {
          console.log("有背景音乐实例");
        } else {
          // 背景音乐自动播放 createInnerAudioContext
          globalData.audioCtx = uni.createInnerAudioContext();
          globalData.audioCtx.src = musicUrl;
          globalData.audioCtx.autoplay = true;
          globalData.audioCtx.loop = true;
          globalData.audioCtx.onPlay(() => {
            console.log("开始播放");
          });
          globalData.audioCtx.onError((res) => {
            console.log(res.errMsg);
            console.log(res.errCode);
          });
        }
      });
    }, url);
  },
 };

页面具体调用

let shareData={
	title:'分享标题',
	
	//其他参数自行查看
	//link:'https://www.baidu.com'// 
	//分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#111
}
this.$jwx.share(shareData, 'https://www.baidu.com/home/home?id=123');

//调用音乐播放 需要传递app过去,那边保存到全局globalData里面
let app = getApp();
 // 微信环境播放音乐
this.$jwx.music(app, '替换你的音乐播放地址');

//调取扫一扫
this.$jwx.scanQRCode((res) => {
	//res 扫描结果
});

//在任何页面停止音乐
playMusic() {
  this.audioCtx = getApp().globalData.audioCtx;
  if (this.audioCtx.paused) {
    this.audioCtx.play();
  } else {
    this.audioCtx.pause();
  }
},

微信扫一扫的页面进入方式。
ios进入扫一扫的单独网页,调用h5会发现调不起来,再次刷新页面又可以了。
进入页面方式改成这种,记得清空浏览器缓存,再试

// 判断机型ios or android
let system = uni.getSystemInfoSync().system;
 if (system.indexOf("iOS") > -1) {
   window.location.href =
     "https://baidu.com/pages/sao/sao";
 } else {
   uni.navigateTo({
     url: "/pages/sao/sao",
   });
 }
 
1、本地开发必须要解决nginx代理,让你再微信开发者网页调试工具中访问域名,指定到你本地的项目进行开发。
2、uniapp 中 部分wx. 与微信浏览器中的有冲突。可以使用jWeixin来代替wx
3、ios进入扫一扫页面一定要按照上述方式

  • 9
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
微信小程序公众号H5分享卡片是指在微信公众号平台上,通过小程序或H5页面来创建可分享的卡片。这种分享卡片可以包含各种信息,如标题、描述、图片、链接等,用于吸引用户点击并进入小程序或H5页面。 在微信小程序中,我们可以通过设置小程序的分享参数来生成分享卡片。开发者可以在小程序的代码中,通过调用相关API来设置分享标题、描述和图片等信息,当用户点击分享按钮时,系统会自动根据设置生成分享卡片供用户分享到朋友圈、好友等渠道。 而在微信公众号H5页面中,我们可以使用微信提供的JSSDK来实现分享功能。开发者可以在H5页面中引入微信提供的JSSDK的使用,在页面加载完成后,通过调用相关API来设置分享标题、描述和图片等信息。当用户点击分享按钮时,系统会调用微信的接口生成分享卡片供用户分享。 通过微信小程序公众号H5分享卡片,用户可以将自己喜欢的小程序或H5页面分享给朋友,让朋友也能够体验到这些应用的功能。而对于开发者来说,分享功能可以增加应用的曝光度和用户量,提高用户参与度和用户粘性。 总之,微信小程序公众号H5分享卡片是一种方便快捷地实现小程序或H5页面分享功能的方式,能够帮助用户分享他们感兴趣的内容,也能够帮助开发者提升应用的影响力和用户数量。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值