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 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
| package com.example.alipay;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.*; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.*;
@SpringBootApplication @RestController @RequestMapping("/alipay") public class AlipayApplication {
private static final String APP_ID = "你的AppID"; private static final String ALIPAY_PUBLIC_KEY = "支付宝公钥"; private static final String MERCHANT_PRIVATE_KEY = "应用私钥"; private static final String GATEWAY_URL = "https://openapi.alipay.com/gateway.do"; private static final String SIGN_TYPE = "RSA2"; private static final String CHARSET = "UTF-8"; private static final String FORMAT = "JSON";
public static void main(String[] args) { SpringApplication.run(AlipayApplication.class, args); }
@PostMapping("/createOrder") public String createOrder(@RequestParam String amount) throws UnsupportedEncodingException { String outTradeNo = "ORDER_" + System.currentTimeMillis(); Map<String, String> params = new HashMap<>(); params.put("app_id", APP_ID); params.put("method", "alipay.trade.page.pay"); params.put("format", FORMAT); params.put("charset", CHARSET); params.put("sign_type", SIGN_TYPE); params.put("timestamp", getCurrentTime()); params.put("version", "1.0"); params.put("notify_url", "https://your-domain.com/alipay/notify"); params.put("return_url", "https://your-domain.com/alipay/return"); Map<String, String> bizContent = new HashMap<>(); bizContent.put("out_trade_no", outTradeNo); bizContent.put("total_amount", amount); bizContent.put("subject", "商品名称"); bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY"); params.put("biz_content", toJsonString(bizContent)); String sign = generateSign(params, MERCHANT_PRIVATE_KEY); params.put("sign", sign); String payUrl = buildRequestUrl(params); return "<script>window.location.href='" + payUrl + "';</script>"; }
@GetMapping("/return") public String alipayReturn(HttpServletRequest request) { Map<String, String> params = getRequestParams(request); if (verifySign(params, ALIPAY_PUBLIC_KEY)) { String tradeStatus = params.get("trade_status"); if ("TRADE_SUCCESS".equals(tradeStatus)) { return "支付成功"; } } return "支付失败或签名验证失败"; }
@PostMapping("/notify") public String alipayNotify(HttpServletRequest request) { Map<String, String> params = getRequestParams(request); if (verifySign(params, ALIPAY_PUBLIC_KEY)) { String tradeStatus = params.get("trade_status"); String outTradeNo = params.get("out_trade_no"); if ("TRADE_SUCCESS".equals(tradeStatus)) { return "success"; } } return "fail"; }
private String generateSign(Map<String, String> params, String privateKey) { String stringToSign = getSignContent(params); try { PrivateKey priKey = getPrivateKeyFromPKCS8("RSA", privateKey); Signature signature = Signature.getInstance("SHA256withRSA"); signature.initSign(priKey); signature.update(stringToSign.getBytes(CHARSET)); byte[] signed = signature.sign(); return Base64.getEncoder().encodeToString(signed); } catch (Exception e) { throw new RuntimeException("生成签名失败", e); } }
private boolean verifySign(Map<String, String> params, String publicKey) { String sign = params.remove("sign"); String stringToVerify = getSignContent(params); try { PublicKey pubKey = getPublicKeyFromX509("RSA", publicKey); Signature signature = Signature.getInstance("SHA256withRSA"); signature.initVerify(pubKey); signature.update(stringToVerify.getBytes(CHARSET)); return signature.verify(Base64.getDecoder().decode(sign)); } catch (Exception e) { throw new RuntimeException("验证签名失败", e); } }
private String getCurrentTime() { return new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date()); }
private String toJsonString(Map<String, String> map) { StringBuilder sb = new StringBuilder(); sb.append("{"); boolean first = true; for (Map.Entry<String, String> entry : map.entrySet()) { if (!first) { sb.append(","); } sb.append("\"").append(entry.getKey()).append("\":\"").append(entry.getValue()).append("\""); first = false; } sb.append("}"); return sb.toString(); }
private String buildRequestUrl(Map<String, String> params) throws UnsupportedEncodingException { StringBuilder sb = new StringBuilder(GATEWAY_URL); sb.append("?"); boolean first = true; for (Map.Entry<String, String> entry : params.entrySet()) { if (!first) { sb.append("&"); } sb.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), CHARSET)); first = false; } return sb.toString(); }
private Map<String, String> getRequestParams(HttpServletRequest request) { Map<String, String> params = new HashMap<>(); Map<String, String[]> requestParams = request.getParameterMap(); for (String name : requestParams.keySet()) { String[] values = requestParams.get(name); String valueStr = ""; for (int i = 0; i < values.length; i++) { valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ","; } params.put(name, valueStr); } return params; }
private String getSignContent(Map<String, String> params) { List<String> keys = new ArrayList<>(params.keySet()); Collections.sort(keys); StringBuilder content = new StringBuilder(); for (int i = 0; i < keys.size(); i++) { String key = keys.get(i); String value = params.get(key); if (i != 0) { content.append("&"); } content.append(key).append("=").append(value); } return content.toString(); }
private PrivateKey getPrivateKeyFromPKCS8(String algorithm, String privateKey) throws Exception { if (privateKey == null || "".equals(privateKey)) { return null; } KeyFactory keyFactory = KeyFactory.getInstance(algorithm); byte[] encodedKey = Base64.getDecoder().decode(privateKey); return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodedKey)); }
private PublicKey getPublicKeyFromX509(String algorithm, String publicKey) throws Exception { KeyFactory keyFactory = KeyFactory.getInstance(algorithm); byte[] encodedKey = Base64.getDecoder().decode(publicKey); return keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey)); } }
|