微信分享到朋友圈自定义图文

<script type="text/javascript">
$(function(){
getUrl();

});

function getUrl(){
$.ajax({
url:'/wechat/share',
type:'get',
data:{
"url": encodeURIComponent(location.href.split('#')[0])
},
success:function(json){
json = JSON.parse(json);
if(json.success == 1){
if(json.data){
wx.config({
debug: true,
appId: "wx043d1b90c7bd4cfa",
timestamp: json.data.timestamp,
nonceStr: json.data.nonceStr,
signature: json.data.signature,
jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage']
});
wx.error(function(res){
alert(res.errMsg);
})

wx.ready(function(){
var encodeurl=location.href.split('#')[0];
wx.onMenuShareTimeline({
title: '闺蜜分享1000万现金红包,豪礼大放送!',
desc: "您的闺蜜为您送来20元现金红包,机会难得,快来领取......",
link: encodeurl,  //分享的url以http或https开头  。具体分享的地址应该不需要编码,至少百度分享里面就是直接的url

imgUrl: "https://m.guimilicai.com/images/cent_cbg.png"
});
wx.onMenuShareAppMessage({
title: '闺蜜分享1000万现金红包,豪礼大放送!',
desc: "您的闺蜜为您送来20元现金红包,机会难得,快来领取......",
link: encodeurl,
imgUrl: "https://m.guimilicai.com/images/cent_cbg.png",
});

});

}
}
},
error:function(){
alert(false);
}
})

}

</script>
</body>
</html>

后台返回的数据

 "success": 1,
    "code": null,
    "comment": null,
    "data": {
        "signature": "c556057efe17da230832abc07d1b287df9991278",
        "jsapi_ticket": "bxLdikRXVbTPdHSM05e5u5KK_6aepzSJbcorNNqO52PqNBTx1sGMuo_-iTq75JYvvkuyTsKmTOOyxSVv9NTq-g",
        "url": "www.baidu.com",
        "nonceStr": "eff876fc-f300-426d-99b5-20c7d15694b7",
        "timestamp": "1446539973"
    },
    "resultList": null
/wechat/share
参数url
 
微信jsdk说明文档 附录5
(确保你获取用来签名的url是动态获取的,动态页面可参见实例代码中php的实现方式。如果是html的静态页面在前端通过ajax将url传到后台签名,前端需要用js获取当前页面除去'#'hash部分的链接(可用location.href.split('#')[0]获取,而且需要encodeURIComponent),因为页面一旦分享,微信客户端会在你的链接末尾加入其它参数,如果不是动态获取当前链接,将导致分享后的页面签名失败。
 
 
因为你分享到微信的页面会有好多个
所以你要分享的url也会有好多个
所以后台不可能写死
所以你要把你当前页面的url地址去除后面的#然后编码ajax传给后台
后台或者微信那边会对这个url进行解码
然后后台通过他自身从微信端口获得的jsapi_ticket、noncestr、timestamp和你提供的动态url进行签名
就得到了动态的签名
 然后所有需要的东西都有了,后台返回个json给你
 

后台返回的数据

 "success": 1,
    "code": null,
    "comment": null,
    "data": {
        "signature": "c556057efe17da230832abc07d1b287df9991278",
        "jsapi_ticket": "bxLdikRXVbTPdHSM05e5u5KK_6aepzSJbcorNNqO52PqNBTx1sGMuo_-iTq75JYvvkuyTsKmTOOyxSVv9NTq-g",
        "url": "www.baidu.com",
        "nonceStr": "eff876fc-f300-426d-99b5-20c7d15694b7",
        "timestamp": "1446539973"
    },
    "resultList": null
/wechat/share
参数url

你把json里面的数据作为微信分享配置的参数进行配置
然后在wx.ready里去调用微信相应的功能接口(你这里调用的有分享到朋友圈和分享到微信朋友这两个接口)
在接口里面你再去写一些标题啊,描述啊之类的
签名使用的url是用来追踪你页面的
 
 
 
 
 
 
 
 
原文地址:https://www.cnblogs.com/wangjiaojiao/p/4935975.html