1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| public class WechatPay2ValidatorForReq { protected static final Logger log = LoggerFactory.getLogger(WechatPay2Validator.class); protected static final long RESPONSE_EXPIRED_MINUTES = 5L; protected final Verifier verifier; protected final String body; protected final String requestId;
public WechatPay2ValidatorForReq(Verifier verifier, String requestId, String body) { this.verifier = verifier; this.requestId = requestId; this.body = body; }
protected static IllegalArgumentException parameterError(String message, Object... args) { message = String.format(message, args); return new IllegalArgumentException("parameter error: " + message); }
protected static IllegalArgumentException verifyFail(String message, Object... args) { message = String.format(message, args); return new IllegalArgumentException("signature verify fail: " + message); }
public final boolean validate(HttpServletRequest request) throws IOException { try { this.validateParameters(request); String message = this.buildMessage(request); String serial = request.getHeader("Wechatpay-Serial"); String signature = request.getHeader("Wechatpay-Signature"); if (!this.verifier.verify(serial, message.getBytes(StandardCharsets.UTF_8), signature)) { throw verifyFail("serial=[%s] message=[%s] sign=[%s], request-id=[%s]", serial, message, signature, request.getHeader("Request-ID")); } else { return true; } } catch (IllegalArgumentException var5) { log.warn(var5.getMessage()); return false; } }
protected final void validateParameters(HttpServletRequest request) { String[] headers = new String[]{"Wechatpay-Serial", "Wechatpay-Signature", "Wechatpay-Nonce", "Wechatpay-Timestamp"}; String value = null; for (String headerName : headers) { value = request.getHeader(headerName); if (value == null) { throw parameterError("empty [%s], request-id=[%s]", headerName, requestId); } } String timestampStr = value; try { Instant responseTime = Instant.ofEpochSecond(Long.parseLong(timestampStr)); if (Duration.between(responseTime, Instant.now()).abs().toMinutes() >= 5L) { throw parameterError("timestamp=[%s] expires, request-id=[%s]", timestampStr, requestId); } } catch (NumberFormatException | DateTimeException var10) { throw parameterError("invalid timestamp=[%s], request-id=[%s]", timestampStr, requestId); } }
protected final String buildMessage(HttpServletRequest request) throws IOException { String timestamp = request.getHeader("Wechatpay-Timestamp"); String nonce = request.getHeader("Wechatpay-Nonce"); String body = this.body; return timestamp + "\n" + nonce + "\n" + body + "\n"; } }
|