调用微信公众号扫一扫功能

第一步,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;
	}
}

 

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页