調用微信公衆號掃一掃功能

第一步,JS接口安全域設置

注:公衆號菜單鏈接,得配置成域名的,不能用ip

第二步,配置ip白名單

第三步、代碼

頁面代碼

<!doctype html>
<html>
<head>
<meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>demo</title>

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>

<!-- 微信 -->
<script src="http://res.wx.qq.com/open/js/jweixin-1.1.0.js"></script>
</head>
<body>
<script type="text/javascript">

    $(document).ready(function () {
		getWeixinParams();
	});

	var appId ;
	var nonceStr ;
	var signature ;
	var timestamp ;
	
	//微信JS—SDK驗證
	function getWeixinParams() {
		//帶參數URL
		var WX_url = location.href.split('#')[0];
		$.ajax({
			type: "post",
			url: "<%=request.getContextPath()%>/test/getwechatscan",
			data: {"URL": WX_url},
			datatype: "json",
			async:false,
			success: function (data) {
				var data = JSON.parse(data);
				appId = data.appId;
				nonceStr = data.nonceStr;
				signature = data.signature;
				timestamp = data.timestamp;
				getWeixinParamsCallBack(data.appId, data.timestamp, data.nonceStr, data.signature);
			},
			error: function () {
				alert("出錯了");
			}
		});
	}
	
	//選擇要調用的接口 接口名稱
	function getWeixinParamsCallBack(appId, timestamp, nonceStr, signature) {
		//步驟三:通過config接口注入權限驗證配置       
 		wx.config({
			debug: true, // 開啓調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時纔會打印。
			appId: appId, // 必填,公衆號的唯一標識
			timestamp: timestamp, // 必填,生成簽名的時間戳
			nonceStr: nonceStr, // 必填,生成簽名的隨機串
			signature: signature, // 必填,簽名
			jsApiList: ['scanQRCode'] // 必填,需要使用的JS接口列表
		});
		//步驟四:通過ready接口處理成功驗證(可不寫 這裏只是跟你說配置成功而已)
		wx.ready(function () {
			
		});
		//步驟五:通過error接口處理失敗驗證
		wx.error(function (res) {
			alert("獲取數據出錯了:" + res.errMsg);
		});
	}
	
	function getWeixinResult() {
		//調取接口
		wx.scanQRCode({
		needResult: 1, // 默認爲0,掃描結果由微信處理,1則直接返回掃描結果,
		//desc: 'scanQRCode desc',
			scanType: ["qrCode", "barCode"], // 可以指定掃二維碼還是一維碼,默認二者都有
			success: function (res) {
				var result = res.resultStr; // 當needResult 爲 1 時,掃碼返回的結果
				if (result.indexOf("=") != -1) {
					result = result.split("=")[1];
				} else if (result.indexOf(",") != -1) {
					result = result.split(",")[1];
				}
				alert(res.resultStr);//解析結果
				//alert("掃描成功::掃描碼=" + result);
			}
		});
	}
</script>
</body>
</html>

後臺代碼

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.gxaysoft.healthDetection.util.SignUtil;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("test")
public class TestController {
	
	@RequestMapping("/getwechatscan")
	@ResponseBody
	public String wechatscan(@RequestParam String URL) throws UnsupportedEncodingException {
		//轉義
		String urlDecode = URLDecoder.decode(URL);
		System.out.println("urlDecode::"+urlDecode);
		String decode = java.net.URLDecoder.decode(URL,"UTF-8");
		System.out.println("decode::"+decode);
		Map<String, String> map = SignUtil.sign(urlDecode);
		JSONObject jsonObject = JSONObject.fromObject(map);
		return jsonObject.toString();
	}

}

 

APPID、APPSECRET 微信公衆平臺可查,換成自己的。


import net.sf.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class SignUtil {
	public static final String APPID = "111";//公衆號的appid
	public static final String APPSECRET = "111";//公衆號的appsecret
	
	public static String ACCESTOKEN = "";
	public static String JSAPI_TICKET = "";
	public static String TIMESTAMP = "";//獲取ACCESTOKEN、JSAPI_TICKET的時間戳
	
	public static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
			+ SignUtil.APPID + "&secret=" + SignUtil.APPSECRET + "";

	public static Map<String, String> sign(String url) {
		
		
/*第一次獲取,或者上次獲取時間超過一小時,則再次獲取。否則不獲取(因爲每天獲取access_token、ticket的次數爲2000次 */
if(("").equals(TIMESTAMP)||compare(Long.valueOf(TIMESTAMP),System.currentTimeMillis())) {
			
			// 獲取JS-SDK的 accesstoken 注意:其與獲取網頁授權的accesstoken不同
			JSONObject accesTokenObject = JSONObject.fromObject(Doget.get(ACCESS_TOKEN_URL));
			ACCESTOKEN = (String) accesTokenObject.get("access_token");
			System.out.println("微信返回accesToken" + ACCESTOKEN);

			// 獲取ticket
			JSONObject jsapiTicketObject = JSONObject.fromObject(Doget.get("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + ACCESTOKEN + "&type=jsapi"));
			JSAPI_TICKET = (String) jsapiTicketObject.get("ticket");
			System.out.println("微信返回jsapiTicket" + JSAPI_TICKET);
			
			TIMESTAMP = Long.toString(System.currentTimeMillis());
		}

		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 + "&timestamp=" + timestamp + "&url=" + url;
		System.out.println("string1=" + 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();
		} catch (Exception 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); 
		ret.put("appId", "wx4633767d26ee5a31");
		// 此時可通過配置引入

		System.out.println("1.ticket(原始)=" + JSAPI_TICKET);
		System.out.println("2.url=" + ret.get("url"));
		System.out.println("3.jsapi_ticket(處理後)=" + ret.get("jsapi_ticket"));
		System.out.println("4.nonceStr=" + ret.get("nonceStr"));
		System.out.println("5.signature=" + ret.get("signature"));
		System.out.println("6.timestamp=" + ret.get("timestamp"));

		return ret;
	}

	/**
	 * 隨機加密
	 *
	 * @param hash
	 * @return
	 */
	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;
	}

	/**
	 * 產生隨機串--由程序自己隨機產生
	 *
	 * @return
	 */
	private static String create_nonce_str() {
		return UUID.randomUUID().toString();
	}

	/**
	 * 由程序自己獲取當前時間
	 *
	 * @return
	 */
	private static String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}
	
	/**
	 * 
	 * @param l1原時間戳
	 * @param l2當前時間戳
	 * @return
	 */
	private static Boolean compare(Long l1,Long l2) {
		Boolean flag = false;
		Long s = (l2 - l1) / 3600/1000;
		if(s>1)
			flag = true;
		return flag;
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章