首先網上查資料,沒有和配置結合,踩了坑(又不愛看官方文檔,文字太多一堆口水話)
。。。。。整理下自己完整的步驟
1、公衆號【基本配置】裏面的【服務器配置】(下面必須要空降方法,不然配置驗證通不過)
一、首先項目導入公衆號的jar包
<!-- 微信公衆號 --> <dependency> <groupId>com.github.binarywang</groupId> <artifactId>weixin-java-mp</artifactId> <version>2.3.0</version> </dependency>
二、服務中WeixinController提供如下方法(注意:weixinService需要繼承WxMpServiceImpl
public class WeixinService extends WxMpServiceImpl)
weixinService.checkSignature(timestamp, nonce, signature)方法是jar包自帶的方法
/**
* 1、用於公衆號【服務器配置】驗證——然後纔有token(坑)
* @param signature
* @param timestamp
* @param nonce
* @param echostr
* @return
*/
@RequestMapping(value = "/wechat/check.do", method = RequestMethod.GET, produces = "text/plain;charset=utf-8")
public
String authGet(@RequestParam("signature") String signature,
@RequestParam("timestamp") String timestamp, @RequestParam("nonce") String nonce,
@RequestParam("echostr") String echostr) {
logger.info("接收到來自微信服務器的認證消息:[{},{},{},{}]", signature, timestamp, nonce, echostr);
if (weixinService.checkSignature(timestamp, nonce, signature)) {
return echostr;
}
return "非法請求";
}
2、配置公衆號的appId、secretKey等參數
wechat.AppID=wx28xxxcf239xx wechat.AppSecret=938b579878798619542d6xxxxxf03000 wechat.ybyc.token=自定義的token,copy過來 wechat.ybyc.EncodingAESKey=隨機生成的AESKey
3、獲取微信JSAPI初始化所需信息
Controller代碼
@RequestMapping(value = "/wechat/config.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
public String getWXConfig(HttpServletRequest request) throws Exception {
Map map = new HashMap<>();
Map resultMap = new HashMap<>();
try {
map.put("clientUrl", request.getParameter("clientUrl"));//當前頁面所在的瀏覽器URL全路徑,由於該支付爲jssdk支付,所以需要url地址.參與後臺sign簽名
/** 獲取用戶的微信客戶端版本號,用於前端支付之前進行版本判斷,微信版本低於5.0無法使用微信支付 */
/*String userAgent = request.getHeader("user-agent");
if (StringUtils.isNotBlank(userAgent)){
char agent = userAgent.charAt(userAgent.indexOf("MicroMessenger") + 15);
map.put("agent", new String(new char[]{agent}));
}*/
resultMap = weixinService.getConfig(map);
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage(), e);
}
return new Gson().toJson(resultMap);
}
service代碼
/**
* 獲取微信JSAPI初始化所需信息
*/
public Map getConfig(Map requestMap) {
String clientUrl = (String) requestMap.get("clientUrl");
String jsapiTicket = "";
try {
jsapiTicket = this.getJsapiTicket();
} catch (WxErrorException e) {
e.printStackTrace();
}
String nonceStr = 生成一個UUID;
String timeStamp = Long.toString(System.currentTimeMillis() / 1000);
String string1 = "jsapi_ticket=" + jsapiTicket +
"&noncestr=" + nonceStr +
"×tamp=" + timeStamp +
"&url=" + clientUrl;
String signature = "";
signature = SHA1.gen(string1);
//logger.info("待簽名的字符串爲:{}, 簽名後: {}", string1, signature);
Map<String, Object> reponseMap = new HashMap<>();
reponseMap.put("appId", 注意自己公衆號的appId);
reponseMap.put("timeStamp", timeStamp);
reponseMap.put("nonceStr", nonceStr);
reponseMap.put("signature", signature);
reponseMap.put("agent", requestMap.get("agent"));
//微信分享相關
reponseMap.put("imgUrl", "https://www.baidu.com/img/bd_logo1.png");
reponseMap.put("shareTitle", "來自……爸爸的測試");
reponseMap.put("descContent", "第一次測試有點緊張,不要慌");
reponseMap.put("lineLink", "http://www.xxx.com/jxq/index.html");
return reponseMap;
}
4、前端wechat.js工具封裝的分享
var timeStamp,nonceStr,appId,agent;
var imgUrl,lineLink,shareTitle,descContent;
var shareType,shareId;
$(function(){
//當前完整路徑(請求後臺,獲取jssdk支付所需的參數,應該可以不要)
var clientUrl = window.location.href.split('#')[0];
$.ajax({
type: 'get',
url: 'http://www.ybycedu.com/core/wechat/config.do',
dataType: 'json',
data: {
"clientUrl": clientUrl //當前頁面所在的瀏覽器URL全路徑,由於該支付爲jssdk支付,所以需要url地址.參與後臺sign簽名
},
cache: false,
error: function () {
alert("系統錯誤,請稍後重試");
return false;
},
success: function (data) {
timeStamp = data.obj.timeStamp;
nonceStr = data.obj.nonceStr;
appId = data.obj.appId;
agent = data.obj.agent;
imgUrl = data.obj.imgUrl;
lineLink = data.obj.lineLink;
shareTitle = data.obj.shareTitle;
descContent = data.obj.descContent;
//JSSDK支付所需的配置參數,首先會檢查signature是否合法。
wx.config({
debug: false, //開啓debug模式,測試的時候會有alert提示
appId: appId, //公衆平臺中-開發者中心-appid
timestamp: timeStamp, //時間戳
nonceStr: nonceStr, //隨機字符串,不長於32位
signature: data.obj.signature, //這裏的signature是後臺使用SHA1簽名算法得出,不是MD5,與下面的wx.chooseWXPay中的paySign不同,下面的paySign是後臺使用MD5加密得出
jsApiList: [ //指定哪些JS接口有權限訪問
'chooseWXPay','onMenuShareTimeline','onMenuShareAppMessage','getLocation','startRecord','stopRecord','onVoiceRecordEnd','playVoice','pauseVoice','stopVoice','onVoicePlayEnd','uploadVoice','downloadVoice'
]
});
//上方的config檢測通過後,會執行ready方法
wx.ready(function () {
if (typeof WeixinJSBridge == "undefined"){
if( document.addEventListener ){
document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
}else if (document.attachEvent){
document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
}
}else{
onBridgeReady();
}
});
wx.error(function (res) {
alert("檢測出問題:" + res.errMsg);
});
}
});
});
function onBridgeReady() {
// 發送給好友
WeixinJSBridge.on('menu:share:appmessage', shareFriend);
// 分享到朋友圈
WeixinJSBridge.on('menu:share:timeline', shareTimeline);
// 分享到微博
WeixinJSBridge.on('menu:share:weibo', shareWeibo);
}
//分享給好友
function shareFriend() {
WeixinJSBridge.invoke('sendAppMessage',{
"appid": appId,
"img_url": imgUrl,
"img_width": "200",
"img_height": "200",
"link": lineLink,
"desc": descContent,
"title": shareTitle
}, function(res) {
if(res.err_msg=="send_app_msg:ok"){
// alert("發送給好友成功");
}
})
}
//分享到朋友圈
function shareTimeline() {
WeixinJSBridge.invoke('shareTimeline',{
"img_url": imgUrl,
"img_width": "200",
"img_height": "200",
"link": lineLink,
"desc": descContent,
"title": shareTitle
}, function(res) {
if(res.err_msg == 'share_timeline:ok'){
// alert("分享成功");
}
});
}
//分享到微博
function shareWeibo() {
WeixinJSBridge.invoke('shareWeibo',{
"content": descContent,
"url": lineLink
}, function(res) {
if(res.err_msg == "share_weibo:ok"){
alert("分享到微博成功");
}
});
}
.
.
.
.
注意:記得在【基本設置】中【ip白名單】添加自己服務器IP
不然報錯:{"errcode":40164,"errmsg":"invalid ip 120.11.26.205, not in whitelist hint: [WJWUwa08642790]"}
好的,遛遛
|
|
|
完美。