JAVA實現呼叫微信js-sdk掃一掃
阿新 • • 發佈:2018-12-11
喜歡的朋友可以關注下。
已經很久沒有給大家分享一片技術文章了,今天抽了點時間來,給大家說一說如何呼叫微信提供的掃一掃介面。
前提:
需要申請一個公眾號:申請公眾號需要的資料我就不說了,去申請微信會提示需要哪些。
準備appid(公眾號的id)
AppSecret (公眾號的金鑰)
正文:
首先,我們先來簡單瞭解一下流程,詳細的微信文件有說明。
獲取Token→根據token獲取Ticket→根據ticket簽名→反會引數給前端→前端調起掃一掃介面
下面直接上程式碼
1.獲取token
/** * Description: 獲取微信公眾號token<BR> * * @author dsn * @date 2018年9月21日 上午9:53:26 * @param appid * @param secret * @return * @version 1.0 */ public static String getAccessToken(String appid, String secret) { String token = ""; String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret; JSONObject result = PayCommonUtil.httpsRequest(token_url, "POST"); if (result.get("access_token") != null) { token = result.get("access_token").toString(); } return token; }
2.獲取ticket
/** * Description: 獲取微信ticket<BR> * * @author dsn * @date 2018年9月21日 上午9:54:03 * @param token * @return * @version 1.0 */ public static String getTicket(String token) { if ("".equalsIgnoreCase(token) || null == token) { return ""; } String ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token + "&type=jsapi"; JSONObject result = PayCommonUtil.httpsRequest(ticket_url, "POST"); return result.get("ticket").toString(); }
3.簽名
public static String getSign(String jsapi_ticket, String noncestr, Long timestamp, String url) throws NoSuchAlgorithmException { String shaStr = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "×tamp=" + timestamp + "&url=" + url; MessageDigest mDigest = MessageDigest.getInstance("SHA1"); byte[] result = mDigest.digest(shaStr.getBytes()); StringBuffer signature = new StringBuffer(); for (int i = 0; i < result.length; i++) { signature.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1)); } return signature.toString(); }
4.action中呼叫
/**
* Description:微信掃一掃介面 <BR>
*
* @author ran.chunlin
* @date 2017年4月11日 上午10:07:35
* @param request
* @return
* @throws Exception
* @version 1.0
*/
@RequestMapping(params = "method=getWechatSign", method = RequestMethod.GET)
public @ResponseBody Map<String, Object> getWechatSign(HttpServletRequest request) throws Exception {
/* 返回的json資料 */
Map<String, Object> jsonMap = new HashMap<>();
// 構成子資料map
Map<String, Object> subJsonMap = new HashMap<>();
// 1.獲取引數
String url = showNull(request.getParameter("url"));
String t = showNull(request.getParameter("t"));
String appId = showNull(request.getParameter("appId"));
String appSecret = showNull(request.getParameter("appSecret"));
if (url == null || t == null || appId == null || appSecret == null) {
return json4Map(jsonMap, subJsonMap, "引數為空", STATUSCODE_FAILED_BADINPUT_PARAM);
} else {
String accessToken = WeiXinUtils.getAccessToken(appId, appSecret);
String ticket = WeiXinUtils.getTicket(accessToken);
Long timestamp = System.currentTimeMillis() / 1000;
String nonceStr = RandomStringUtils.randomAlphanumeric(16);
String sign = getSign(ticket, nonceStr, timestamp, url);
subJsonMap.put("result", "1");
subJsonMap.put("timestamp", timestamp);
subJsonMap.put("nonceStr", nonceStr);
subJsonMap.put("appId", appId);
subJsonMap.put("sign", sign);
}
return json4Map(jsonMap, subJsonMap, "獲取sign成功", STATUSCODE_SUCCESS);
}
5.前端程式碼
// 掃一掃 進入頁面時去呼叫
$.ajax({
type : 'GET',
url : "你action的url",
data : {
appId : "",
appSecret : "",
url : location.href,
t : Math.random()
},
success : function(json) {
if (json.data.result == "1") {
wxConfig(json.data.timestamp, json.data.nonceStr,
json.data.sign, json.data.appId);
}
}
});
function wxConfig(_timestamp, _nonceStr, _signature, _appId) {
wx.config({
// debug : false, // 開啟除錯模式,呼叫的所有api的返回值會在客戶端alert出來,若要檢視傳入的引數,可以在pc端開啟,引數資訊會通過log打出,僅在pc端時才會列印。
appId : _appId, // 必填,公眾號的唯一標識
timestamp : _timestamp, // 必填,生成簽名的時間戳
nonceStr : _nonceStr, // 必填,生成簽名的隨機串
signature : _signature,// 必填,簽名,見附錄1
jsApiList : [ 'onMenuShareTimeline', 'onMenuShareAppMessage',
'onMenuShareQQ', 'onMenuShareWeibo', 'scanQRCode' ]
// 必填,需要使用的JS介面列表,所有JS介面列表見附錄2
});
}
//掃碼呼叫
function scanCode() {
wx.scanQRCode({
needResult : 1,
scanType : [ "qrCode", "barCode" ],
success : function(res) {
console.log(res)
//掃描返回的資料
var result = res.resultStr;
},
fail : function(res) {
layer.open({
content : '請稍後再試',
skin : 'msg',
time : 2
//2秒後自動關閉
});
}
});
}
其實就是這麼的簡單
這裡需要提醒大家 頁面一定要引入
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
不然會調用不了微信的函式
如有需要可以加我Q群【308742428】大家一起討論技術。
後面會不定時為大家更新文章,敬請期待。