最近一个项目用到H5微信分享(好友、朋友圈),中间碰到好多难点,搜了好多才解决,现记录如下
先直接上源码
//分享朋友圈、好友
$.ajax({
url:weburl+'/p/jsapi?url='+encodeURIComponent(location.href),
type:"get",
datatype:"json",
async:true,
timeout : 30000,
error: function(XMLHttpRequest, textStatus, errorThrown){
console.log('进入到error')
console.log('status:'+XMLHttpRequest.status);
console.log('readyState:'+XMLHttpRequest.readyState);
console.log('textStatus:'+textStatus);
////alert(textStatus);
weixinSign()
},
success: function(data){
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来
appId:data.appId,
nonceStr:data.nonceStr,
timestamp:data.timestamp,
//url:"http://assistant.flow.wostore.cn/WoShieldServer/video/index.html?channelId=123",
signature:data.signature,
jsApiList: [
"onMenuShareTimeline",//分享朋友圈接口
"onMenuShareAppMessage",//分享给朋友接口
"checkJsApi"
] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
wx.ready(function () {
console.log('分享前')
wx.onMenuShareTimeline({
title: $('.videoitem .title').text(),
desc: '最强王者视频悬赏令',
link: location.href,
imgUrl: $('.videoitem .video').prop('poster'),//'http://assistant.flow.wostore.cn/WoShieldServer/video/img/prize.jpg'
trigger: function (res) {
// 不要尝试在trigger中使用ajax异步请求修改本次分享的内容,因为客户端分享操作是一个同步操作,这时候使用ajax的回包会还没有返回
// alert('用户点击发送给朋友');
},
success: function (res) {
console.log('已分享');
},
cancel: function (res) {
console.log('已取消');
},
fail: function (res) {
console.log(JSON.stringify(res));
}
});
wx.onMenuShareAppMessage({
title: $('.videoitem .title').text(),
desc: '最强王者视频悬赏令',
link: location.href,
imgUrl: $('.videoitem .video').prop('poster'),//'http://assistant.flow.wostore.cn/WoShieldServer/video/img/prize.jpg'
trigger: function (res) {
// 不要尝试在trigger中使用ajax异步请求修改本次分享的内容,因为客户端分享操作是一个同步操作,这时候使用ajax的回包会还没有返回
// alert('用户点击发送给朋友');
},
success: function (res) {
console.log('已分享');
},
cancel: function (res) {
console.log('已取消');
},
fail: function (res) {
console.log(JSON.stringify(res));
}
});
wx.error(function (res) {
alert(res.errMsg);
});
});
},
complete : function(XMLHttpRequest,status){
if(status=='timeout'){
showtip("网络通信错误,请稍后再试!");
}
}
});
解析:需要服务端配合,这个接口weburl+'/p/jsapi?url='+encodeURIComponent(location.href),用来获取wx.config里面的几项配置信息,其他的配置参照微信官网文档陪直就行了。