微信開放實戰--掃一掃功能(轉)
大概流程:
1.根據appId和appSecret獲取access_token(使用憑證)
public static JSONObject getTokenTool(String appId,String appSecret){
String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appSecret;
System.out.println(HttpRequestUtil.httpRequest(url, "GET", ""));
return HttpRequestUtil.httpRequest(url, "GET", "");
}
這是測試號獲取access_token的介面,普通公眾號介面地址請檢視微信官方文件。
2.根據access_token獲取jsapi_ticket
public static JSONObject getTicketTool(String access_token){
String url="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+access_token+"&type=jsapi";
System.out.println(HttpRequestUtil.httpRequest(url, "GET", ""));
return HttpRequestUtil.httpRequest(url, "GET", "");
}
3.在微信獲取簽名演算法(具體如下)
public static Map<String, String> sign(String url) {
String appId="wxcc42f613dbf7299f";
String appSecret="e59e10c74c70b1c042b5ecaf454052ac";
String access_token=getTokenTool(appId, appSecret).getString("access_token");
JSONObject ticketJson=getTicketTool(access_token);
System.out.println(ticketJson.toString());
String jsapi_ticket = ticketJson.getString("ticket");
Map<String, String> ret = new HashMap<String, String>();
//這裡的jsapi_ticket是獲取的jsapi_ticket。
String nonce_str = create_nonce_str();
String timestamp = create_timestamp();
String string1;
String signature = "";
System.out.println(2);
//注意這裡引數名必須全部小寫,且必須有序
string1 = "jsapi_ticket=" + jsapi_ticket +
"&noncestr=" + nonce_str +
"×tamp=" + timestamp +
"&url=" + url;
try
{
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(string1.getBytes("UTF-8"));
signature = byteToHex(crypt.digest());
System.out.println("crypt="+crypt.toString());
System.out.println("string1="+string1);
System.out.println("signature="+signature);
}
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;
}
private static String create_nonce_str() {
return UUID.randomUUID().toString();
}
private static String create_timestamp() {
return Long.toString(System.currentTimeMillis() / 1000);
}
4.獲取一個js安全域名介面(如:gstz.imwork.net)
一般使用花生殼進行內網穿透,使內網地址對映到一個花生殼提供的公網的地址,適合用來測試,花生殼內網穿透如何使用可到花生殼官網檢視。
5.把域名和action的地址拼接起來成url,放入簽名方法中
@Controller
@SuppressWarnings("serial")
public class WeixinAction{
/**
* 獲取簽名演算法
*/
@RequestMapping("getSign")
@ResponseBody
public JSONObject getSign(){
JSONObject jsonObject=new JSONObject();
String url="http://17j62137x0.imwork.net/ssm_d1/index.jsp";
Map<String, String> ret =WxJSUtil.sign(url);
System.out.println("map="+ret.toString());
jsonObject.put("weixin", ret);
System.out.println("json="+jsonObject.toString());
return jsonObject;
}
}
6.在JSP頁面初始化時非同步獲取簽名action傳來3個引數,JSP內容如下
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>微信掃一掃</title>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/weixin.js"></script>
</head>
<body>
<input id="timestamp" type="hidden" value="${timestamp}" />
<input id="noncestr" type="hidden" value="${nonceStr}" />
<input id="signature" type="hidden" value="${signature}" />
<input id="id_securityCode_input">
<button id="scanQRCode" onclick="getWeixinResult()">掃碼</button>
</body>
<script type="text/javascript">
</script>
</html>
7.通過簽名演算法獲取wx.config的4個重要引數:jsapi_ticket、noncestr、timestamp、url
wx.config({ debug: true,// 開啟除錯模式,呼叫的所有api的返回值會在客戶端alert出來,若要檢視傳入的引數,可以在pc端開啟,引數資訊會通過log打出,僅在pc端時才會列印。 appId:'',// 必填,公眾號的唯一標識 timestamp: ,// 必填,生成簽名的時間戳 nonceStr:'',// 必填,生成簽名的隨機串 signature:'',// 必填,簽名,見附錄1 jsApiList: []// 必填,需要使用的JS介面列表,所有JS介面列表見附錄2});
8.告訴微信選擇呼叫的介面名稱
9.把獲取的結果result進行處理getWeixinResultCallBack(param)
10.給按鈕新增 getWeixinResult事件,就可以通過按鈕呼叫掃一掃功能。(記得用微信瀏覽器點開)
這是DEMO的下載地址(博主本想免費分享這個資源的,無奈CSDN最少也要2點資源分才能下載):下載DEMO
如果域名沒有備案或者沒有公眾號或者不想交300塊錢每年的認證費可以呼叫別人的介面,簡單又方便,具體參考:https://blog.csdn.net/sysdzw/article/details/80810345