微信卡券开发-卡券领取config包装(附:卡券签名错误解决方案)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cl11992/article/details/86574656

一、介绍

微信卡券领取的时候,调用js领取接口,需要给包装一个config,给js使用

开发的时候遇到了很多坑,在这里面记录一下

二、注意

1.卡券使用的jsapi_ticket,比较特殊,具体获取方法:

https://blog.csdn.net/cl11992/article/details/86300079

2.下面类CardSignature.java签名signature的时候,注意要使用值进行签名(需要排序一下)

如果没有这样做会出现“签名错误”

三、代码实例

WechatConfig.java

package com.panpass.common.tool;

public class WechatConfig {
	
	private String appId;
	private String timestamp;
	private String nonceStr;
	private String signature;
	private String url;

	public String getAppId() {
		return appId;
	}

	public void setAppId(String appId) {
		this.appId = appId;
	}

	public String getTimestamp() {
		return timestamp;
	}

	public void setTimestamp(String timestamp) {
		this.timestamp = timestamp;
	}

	public String getNonceStr() {
		return nonceStr;
	}

	public void setNonceStr(String nonceStr) {
		this.nonceStr = nonceStr;
	}

	public String getSignature() {
		return signature;
	}

	public void setSignature(String signature) {
		this.signature = signature;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}
	
}

CardSignature.java

下面所需要的类

JsApiTicketUtils:https://blog.csdn.net/cl11992/article/details/86300079

public class CardSignature {

	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;
	}

	/**
	 * 卡券签名
	 * @param request
	 * @param cardId	卡券第三方id
	 * @param appid		appid
	 * @return
	 * @throws Exception
	 */
	public static WechatConfig getCardSignature(HttpServletRequest request,String cardId,String appid) throws Exception {
		WechatConfig config = new WechatConfig();
		config.setNonceStr(UUID.randomUUID().toString().replaceAll("-", ""));
		// 时间戳
		config.setTimestamp(Long.toString(System.currentTimeMillis() / 1000));
		// 当前网页的URL,不包含#及其后面部分 主微信appid
		config.setAppId(appid);

		StringBuffer curUrl = request.getRequestURL();
		String params = request.getQueryString();
		if (!StringUtil.isBlank(params)) {
			curUrl = curUrl.append("?").append(params);
		}
		config.setUrl(curUrl.toString());

		//获取jsapi_ticket
		Map<String, String> jsApiTicketMap = JsApiTicketUtils.getWxCardJsApiTicket();
		String jsapiTicket = jsApiTicketMap.get("wx_card_jsapi_ticket");
		
		List<String> list = new ArrayList<>();
		list.add(jsapiTicket);
		list.add(config.getNonceStr());
		list.add(config.getTimestamp());
		list.add(cardId);
		Collections.sort(list);
		StringBuffer sBuffer = new StringBuffer();
		for (int i = 0; i < list.size(); i++) {
			sBuffer.append(list.get(i));
		}
		MessageDigest crypt = MessageDigest.getInstance("SHA-1");
		crypt.reset();
		crypt.update(sBuffer.toString().getBytes("UTF-8"));
		
		config.setSignature(byteToHex(crypt.digest()));
		return config;
	}

}

 

展开阅读全文

没有更多推荐了,返回首页