目前微信官網接口文檔給的一些信息比較精簡,當初做微信分享踩了不少坑。在項目完結後,對一些踩坑做一些總結。順便分享自己一個完整的案例。希望能對以後涉足這一塊的能有所幫助。
1、登入微信公衆平臺
(1)獲取appid和appSecret
(2)設置JS接口安全域名(需要有一個合法、可以訪問的域名)
2.引入JS文件
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
3、前端代碼(由於我的前端使用Vue開發,爲了能失識別微信接口函數,所以函數名開頭加window)
let links= 分享出去的鏈接 ;
let title= 分享的標題 ;
let desc= 分享的詳情介紹 ;
let imgUrl=分享的縮略圖展示;
window.wx.config({
debug: false,
appId: 你的appid,
timestamp: 時間戳,
nonceStr: 隨機字符串,
signature: 簽名,
jsApiList: [
'onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','onMenuShareQZone'
]
})
window.wx.ready(function () {
window.wx.onMenuShareTimeline({
title: title, // 分享標題
desc: desc, // 分享描述
link:links, // 分享鏈接
imgUrl: imgUrl, // 分享圖標
success: function () {
alert("分享到朋友圈成功")
},
cancel: function () {
alert("分享失敗,您取消了分享!")
}
});
//微信分享菜單測試
window.wx.onMenuShareAppMessage({
title:title, // 分享標題
desc: desc, // 分享描述
link: links, // 分享鏈接
imgUrl: imgUrl, // 分享圖標
success: function () {
alert("成功分享給朋友")
},
cancel: function () {
alert("分享失敗,您取消了分享!")
}
});
window.wx.onMenuShareQQ({
title:title, // 分享標題
desc: desc, // 分享描述
link:links, // 分享鏈接
imgUrl: imgUrl, // 分享圖標
success: function () {
alert("成功分享給QQ")
},
cancel: function () {
alert("分享失敗,您取消了分享!")
}
});
window.wx.onMenuShareWeibo({
title:title, // 分享標題
desc: desc, // 分享描述
link: links, // 分享鏈接
imgUrl: imgUrl, // 分享圖標
success: function () {
alert("成功分享給朋友")
},
cancel: function () {
alert("分享失敗,您取消了分享!")
}
});
window.wx.onMenuShareQZone({
title:title, // 分享標題
desc: desc, // 分享描述
link: links, // 分享鏈接
imgUrl: imgUrl, // 分享圖標
success: function () {
alert("成功分享給朋友")
},
cancel: function () {
alert("分享失敗,您取消了分享!")
}
});
});
window.wx.error(function(res){
alert(res)
// config信息驗證失敗會執行error函數,如簽名過期導致驗證失敗,具體錯誤信息可以打開config的debug模式查看,也可以在返回的res參數中查看,對於SPA可以在這裏更新簽名。
});
4、後臺代碼 (目前官網給出access_token每日請求次數上限爲2000,每次請求值得有效時間爲7200s,即2個小時。當7200有效時間並不一定可靠。我這裏是每隔一個小時進行一次存儲。)
/**
*
* 功能描述: 獲取微信分享簽名
*
* @param:
* @return:
*/
@RequestMapping(value = "getSign", method = RequestMethod.POST)
@ResponseBody
@RestAuth(isPublic = true)
public APIResult<WinXinEntity> getSign(HttpServletRequest request,HttpServletResponse response,@RequestBody Map<String,String> map) throws IOException {
APIResult<WinXinEntity> result = new APIResult<>();
String accessToken = null;
SysInfo sysInfo = null;
sysInfo = sysInfoService.selectInfo();
if(sysInfo==null){
String grant_type = "client_credential";// 獲取access_token填寫client_credential
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=你的&secret=你的";
//獲取accessToken信息
String data = HttpUtils.loadJSON(url);
//string轉Map
Map<String,String> accessTokenMap = strToMap(data);
accessToken = accessTokenMap.get("access_token");
System.out.print("項目地址accessToken:"+accessToken);
System.out.print("地址返回結果:"+data);
sysInfoService.saveInfo(accessToken);
}else {
accessToken = sysInfo.getAccessToken();
}
String ticketurl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+accessToken+"&type=jsapi";// 獲取ticketurl
//獲取ticket信息
String ticketData = HttpUtils.loadJSON(ticketurl);
//string轉Map
Map<String,String> ticketMap = strToMap(ticketData);
String ticket = ticketMap.get("ticket");
String strUrl = map.get("url");
//獲取參數
WinXinEntity wx = new WinXinEntity();
Map<String, String> ret = Sign.sign(ticket, strUrl);
wx.setTicket(ret.get("jsapi_ticket"));
wx.setSignature(ret.get("signature"));
wx.setNoncestr(ret.get("nonceStr"));
wx.setTimestamp(ret.get("timestamp"));
System.out.println("\n\n" + ret.toString() + "\n\n");
result.setResult(wx);
result.setCode(ResultPacketCode.APIResultCode.Success.getCode());
return result;
}
5、HttpUtils請求類
package com.gd.common.serviceImpl;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.X509TrustManager;
import org.apache.log4j.Logger;
/**
* @Description:
*/
public class HttpUtils {
public static String loadJSON (String url) {
StringBuilder json = new StringBuilder();
try {
URL oracle = new URL(url);
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine = null;
while ( (inputLine = in.readLine()) != null) {
json.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
return json.toString();
}
}
6、簽名類
package com.gd.common.config;
import java.util.UUID;
import java.util.Map;
import java.util.HashMap;
import java.util.Formatter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;
public class Sign {
public static Map<String, String> sign(String jsapi_ticket, String url) {
Map<String, String> ret = new HashMap<String, String>();
String nonce_str = create_nonce_str();
String timestamp = create_timestamp();
String string1;
String signature = "";
string1 = "jsapi_ticket=" + jsapi_ticket +
"&noncestr=" + nonce_str +
"×tamp=" + timestamp +
"&url=" + url;
System.out.println(string1);
try
{
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(string1.getBytes("UTF-8"));
signature = byteToHex(crypt.digest());
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
ret.put("url", url);
ret.put("jsapi_ticket", jsapi_ticket);
ret.put("nonceStr", nonce_str);
ret.put("timestamp", timestamp);
ret.put("signature", signature);
return ret;
}
// 生成簽名
private static String byteToHex(final byte[] hash) {
Formatter formatter = new Formatter();
for (byte b : hash)
{
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
// 生成nonceStr
private static String create_nonce_str() {
return UUID.randomUUID().toString();
}
// 生成timestamp
private static String create_timestamp() {
return Long.toString(System.currentTimeMillis() / 1000);
}
}
如仍有疑問,可以私信我。或在下方留言