前端JS通用程式碼
請注意傳給後臺的url是當前瀏覽器的地址並且進行encodeURIComponent處理: encodeURIComponent(location.href.split('#')[0]),而方法中的url則是用於分享到朋友圈或者微信好友的跳轉連結。注:這裡很多人會混淆
function WeChat(url, title, img, desc) {
var configData = {
title: title, // 分享標題
desc: desc, // 分享描述
link: url, // 分享連結
imgUrl: img
};
$.ajax({
url: basePath+'/wechat/wechatShare.ky',
type: 'POST',
data: {
url:encodeURIComponent(location.href.split('#')[0]),
debug:"false",
jsApiList:"onMenuShareAppMessage,onMenuShareTimeline"
},
async: false,
success: function (resp) {
if (resp.code=="00") {
console.log(resp.data);
//wx.config(resp.data);
wx.config(resp.data);
wx.ready(function () {
wx.onMenuShareAppMessage({
title: configData.title, // 分享標題
desc: configData.desc, // 分享描述
link: configData.link, // 分享連結,該連結域名或路徑必須與當前頁面對應的公眾號JS安全域名一致
imgUrl: configData.imgUrl, // 分享圖示
success: function () {
updateAppMessageShareData();
}
});
//分享給朋友圈
wx.onMenuShareTimeline({
title: configData.title, // 分享標題
link: configData.link, // 分享連結,該連結域名或路徑必須與當前頁面對應的公眾號JS安全域名一致
imgUrl: configData.imgUrl, // 分享圖示
success: function() {
updateTimelineShareData();
}
});
wx.error(function (res) {
alert(res.errMsg); //列印錯誤訊息。及把 debug:false,設定為debug:ture就可以直接在網頁上看到彈出的錯誤提示
});
});
} else {
return;
}
},error:function(e){
console.log(e);
}
});
}
複製程式碼
公共方法呼叫
var url = "http://www.baidu.com/test";
var imgUrl = responseData.imgUrl;
var title= responseData.title;
var desc = responseData.desc;
WeChat(url, title, imgUrl, desc);
複製程式碼
後端接收處理程式碼
後臺需要進行一次解碼操作,記得加入微信工具包
<dependency>
<groupId>com.github.liyiorg</groupId>
<artifactId>weixin-popular</artifactId>
<version>2.8.27</version>
</dependency>
/**
* 向微信請求accessToken和ticket
* @param url
* @return
*/
@RequestMapping(method = RequestMethod.POST, value = "/wechatShare.ky")
@ResponseBody
@SysLog(actionName = "向微信請求accessToken和ticket")
public Object wechatShare(@RequestParam("url") String url,
@RequestParam("debug") boolean debug,
@RequestParam("jsApiList") String jsApiList) {
try{
log.info("wechatShare="+url+" debug="+debug+" jsApiList="+jsApiList);
url = URLDecoder.decode(url,"UTF-8");
//檢查Redis中現有的accessToken和ticket
//ticket
String ticket = this.wechatService.getWxTicket();
//生成所需的引數
String jsonResult = JsUtil.generateConfigJson(ticket,debug,appId,url,jsApiList.split(","));
return ResponseVo.buildSuccessResponse(JSON.parseObject(jsonResult));
}catch(Exception e){
log.error(e);
return ResponseVo.buildResponse(ResponseEnum.WECHAT_SHARE_ERROR);
}
}
複製程式碼