h5微信分享

h5分享的步骤(前端需要完成的部分)

1.绑定域名

登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。

2.引入Js文件

在需要调用JS接口的页面引入如下JS文件,(支持https):http://res.wx.qq.com/open/js/jweixin-1.4.0.js

如需进一步提升服务稳定性,当上述资源不可访问时,可改访问:http://res2.wx.qq.com/open/js/jweixin-1.4.0.js (支持https)。

备注:支持使用 AMD/CMD 标准模块加载方法加载

3.通过config接口注入权限验证配置

找后台要接口,拿到下面这些字段值

wx.config({
debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: '', // 必填,公众号的唯一标识
timestamp: , // 必填,生成签名的时间戳
nonceStr: '', // 必填,生成签名的随机串
signature: '',// 必填,签名
jsApiList: [] // 必填,需要使用的JS接口列表
});
如果你已经引用了jquery,可以直接使用jquery提供的ajax
$.ajax({ url: "xxxxxxxxxx?url=xxxxxxxxxxxxxxx", success: function(data){
        // ?= url后面写的是你需要转发的页面链接
        console.log(data.result);
        wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
        appId: data.result.appId, // 必填,公众号的唯一标识
        timestamp:data.result.timestamp , // 必填,生成签名的时间戳
        nonceStr: data.result.nonceStr, // 必填,生成签名的随机串
        signature: data.result.signature,// 必填,签名
        jsApiList: [ 'updateAppMessageShareData',] // 必填,需要使用的JS接口列表  });
}
});
如果不需要引用jquery,可以用下面原生ajax请求~~
 //创建异步对象
 var xhr = new XMLHttpRequest();
    //设置请求的类型及url
    xhr.open('post', 'xxxxxxxxxxx?url='+location.href.split('#')[0] );
    //post请求一定要添加请求头才行不然会报错
    xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    //发送请求
    xhr.send();
    xhr.onreadystatechange = function () {
        // 这步为判断服务器是否正确响应
        if (xhr.readyState == 4 && xhr.status == 200) {
            console.log(xhr.response);
            console.log(JSON.parse(xhr.response).info.appId)
            var data = JSON.parse(xhr.response).info;
            console.log(data)
            wx.config({
              debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
              appId: data.appId, // 必填,公众号的唯一标识
              timestamp:data.timestamp , // 必填,生成签名的时间戳
              nonceStr: data.nonceStr, // 必填,生成签名的随机串
              signature: data.signature,// 必填,签名
              jsApiList: [ 'updateAppMessageShareData','updateTimelineShareData'] // 必填,需要使用的JS接口列表 使用了分享朋友和朋友圈
            });
            wx.checkJsApi({
          jsApiList: ['updateAppMessageShareData','updateTimelineShareData'], // 需要检测的JS接口列表,所有JS接口列表见附录2,
          success: function(res) {
            console.log(res)
          // 以键值对的形式返回,可用的api值true,不可用为false
          // 如:{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
        }
});
}

补充:wx.checkJsApi检查基础接口、判断当前客户端版本是否支持指定JS接口,可以不写,如果你转发失败,可以加上用来测试!

4:通过ready接口处理成功验证

wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
    wx.updateAppMessageShareData({ //自定义“分享给朋友”及“分享到QQ”按钮的分享内容
        title: '', // 分享标题
        desc: '', // 分享描述
        link: '', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: '', // 分享图标
        success: function () {
          // 设置成功
        }
    });
     wx.updateTimelineShareData({ //自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容(1.4.0)
        title: '', // 分享标题
        link: '', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: '', // 分享图标
        success: function () {
          // 设置成功
        }
    })
});

5:通过error接口处理失败验证

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

 附上完整demo

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta
  name="viewport"
  content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"
/>
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta content="yes" name="apple-mobile-web-app-capable" />
<meta content="black" name="apple-mobile-web-app-status-bar-style" />
<meta name="screen-orientation" content="portrait">
 <meta name="x5-orientation" content="portrait">
<title>微信分享</title>    
</head>
<body>
  <div>微信分享</div>

  <!-- 引入js文件 -->
  <script src="http://res.wx.qq.com/open/js/jweixin-1.4.0.js" type="text/javascript"></script>
  <script>
  window.onload = function(){
    //创建异步对象
    var xhr = new XMLHttpRequest();
    //设置请求的类型及url
    xhr.open('post', 'xxxxxxxxxxx?url='+location.href.split('#')[0] );
    //post请求一定要添加请求头才行不然会报错
    xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    //发送请求
    xhr.send();
    xhr.onreadystatechange = function () {
        // 这步为判断服务器是否正确响应
        if (xhr.readyState == 4 && xhr.status == 200) {
            console.log(xhr.response);
            console.log(JSON.parse(xhr.response).info.appId)
            var data = JSON.parse(xhr.response).info;
            console.log(data)
            //通过config接口注入权限验证配置
            wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
            appId: data.appId, // 必填,公众号的唯一标识
            timestamp:data.timestamp , // 必填,生成签名的时间戳
            nonceStr: data.nonceStr, // 必填,生成签名的随机串
            signature: data.signature,// 必填,签名
            jsApiList: [ 'updateAppMessageShareData','updateTimelineShareData'] // 必填,需要使用的JS接口列表
            });
            wx.checkJsApi({
              jsApiList: ['updateAppMessageShareData','updateTimelineShareData'], // 需要检测的JS接口列表
              success: function(res) {
                console.log(res)
            // 以键值对的形式返回,可用的api值true,不可用为false
            // 如:{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
              }
            });
            //分享
            wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
              wx.updateAppMessageShareData({ //自定义“分享给朋友”及“分享到QQ”按钮的分享内容
                  title: '', // 分享标题
                  desc: '', // 分享描述
                  link: '', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                  imgUrl: '', // 分享图标
                  success: function () {
                    // 设置成功
                  }
              });
              wx.updateTimelineShareData({ //自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容(1.4.0)
                  title: '', // 分享标题
                  link: '', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                  imgUrl: '', // 分享图标
                  success: function () {
                    // 设置成功
                  }
              });
          });
          wx.error(function(res){
              // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
          });

        }
    };
     
  }
 
  </script>
</body>
</html>

官方文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115

原文地址:https://www.cnblogs.com/imMeya/p/11345103.html