View Javadoc
1   package com.foxinmy.weixin4j.pay.sign;
2   
3   import com.foxinmy.weixin4j.exception.WeixinException;
4   import com.foxinmy.weixin4j.pay.type.SignType;
5   import com.foxinmy.weixin4j.util.DigestUtil;
6   
7   import java.security.InvalidKeyException;
8   
9   /**
10   * 微信支付签名实现
11   *
12   * @className WeixinPaymentSignature
13   * @author jinyu(foxinmy@gmail.com)
14   * @date 2016年3月26日
15   * @since JDK 1.6
16   * @see <a
17   *      href="https://pay.weixin.qq.com/wiki/doc/api/external/jsapi.php?chapter=4_3">支付签名说明</a>
18   */
19  public class WeixinPaymentSignature extends AbstractWeixinSignature {
20  	/**
21  	 * 支付密钥
22  	 */
23  	private final String paySignKey;
24  
25  	public WeixinPaymentSignature(String paySignKey) {
26  		this.paySignKey = paySignKey;
27  	}
28  
29  	@Override
30  	public String sign(Object obj) {
31  		StringBuilder sb = join(obj).append("&key=").append(paySignKey);
32  		return DigestUtil.MD5(sb.toString()).toUpperCase();
33  	}
34  
35  	@Override
36  	public String sign(Object obj, SignType signType) {
37  		if(signType==null){
38  			return sign(obj);
39  		}
40  		switch (signType){
41  			case HMAC$SHA256:
42  				StringBuilder sb = join(obj).append("&key=").append(paySignKey);
43  				try {
44  					return DigestUtil.HMACSHA256(sb.toString(), paySignKey).toUpperCase();
45  				}catch (InvalidKeyException e){
46  					throw new RuntimeException("商户支付密钥有误", e);
47  				}
48  			default:
49  				return sign(obj);
50  		}
51  	}
52  }