H5 移动端浏览器调用微信的分享功能

编程入门 行业动态 更新时间:2024-10-24 14:16:34

项目场景:把某个h5页面分享到微信里

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

1. 使用npm 安装或者在.html 文件里 <script  src="" ></script >引入

npm install weixin-js-sdk

 2. 引入微信的SDK

import wx from 'weixin-js-sdk'

3. 请求后端接口,在接口成功的回调函数中,通过wx的config接口注入权限验证配置

 封装  .js

export const wechatShare = function (shareData, url) {
  console.log(shareData);
  fetch(baseUrl + "/gzh/jsapi?url=" + url, {
    // 请求配置 // 根据后台配置填写
    method: "GET",
  }).then(async (res) => {
    const data = await res.json();
    const Data = data.data;
    wx.config({
      debug: false,// 是否开启调试模式
      appId: Data.appId,  //必填,公众号的唯一标识
      timestamp: Data.timestamp, // 必填,生成签名的时间戳
      nonceStr: Data.nonceStr, // 必填,生成签名的随机串
      signature: Data.signature, // 必填,签名
      jsApiList: ["updateAppMessageShareData", "updateTimelineShareData"],
     // 必填,需要使用的JS接口列表,可以查看文档,根据项目需求填加
    });
  });
  wx.ready(() => {
    // 自定义“分享给朋友”及“分享到QQ”按钮的分享内容(1.4.0)
    wx.updateAppMessageShareData({
      title: shareData.title,
      desc: shareData.desc,
      link: shareData.url,
      imgUrl: shareData.image,
      success: function () {
        console.log(shareData, "shareData");
        // 设置成功
      },
      cancel: function () {
        console.log("分享取消");
      },
    });
    // 自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容(1.4.0)
    wx.updateTimelineShareData({
      title: shareData.title,
      desc: shareData.desc,
      link: shareData.url,
      imgUrl: shareData.image,
      success: function () {
        // 设置成功
      },
      cancel: function () {
        console.log("分享取消");
      },
    });
  });
};

 4. 组件里使用刚刚封装的  .js里的函数,内容自己配置

 componentDidMount() {
    const id = this.getParams(Router.router.asPath)
    this.getDetail(id)
    const currentUrl = window.location.href.split('#')[0]
    wechatShare({
      title: '******网站',  // 标题
      desc: '*****千万家',// 描述
      url: location.href, // 跳转地址
      image: 'https://img.nbsjfr/shangjingu.png' // 图片
    }, currentUrl)
  }

Tips:title,desc,imgURL,根据自己需求进行配置

分享到微信聊天框的示例图

更多推荐

H5 移动端浏览器调用微信的分享功能

本文发布于:2023-06-14 09:28:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1460807.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:浏览器   功能

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!