OrderNotifyController.java 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package com.izouma.nineth.web;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.alipay.api.AlipayApiException;
  5. import com.alipay.api.internal.util.AlipaySignature;
  6. import com.izouma.nineth.config.AlipayProperties;
  7. import com.izouma.nineth.service.OrderService;
  8. import lombok.AllArgsConstructor;
  9. import lombok.extern.slf4j.Slf4j;
  10. import org.apache.commons.collections.MapUtils;
  11. import org.springframework.stereotype.Controller;
  12. import org.springframework.web.bind.annotation.PostMapping;
  13. import org.springframework.web.bind.annotation.RequestMapping;
  14. import org.springframework.web.bind.annotation.ResponseBody;
  15. import javax.servlet.http.HttpServletRequest;
  16. import java.util.HashMap;
  17. import java.util.Map;
  18. import java.util.Set;
  19. import static com.alibaba.fastjson.serializer.SerializerFeature.PrettyFormat;
  20. @Slf4j
  21. @Controller
  22. @RequestMapping("/notify")
  23. @AllArgsConstructor
  24. public class OrderNotifyController {
  25. private final AlipayProperties alipayProperties;
  26. private final OrderService orderService;
  27. @PostMapping("/order/alipay")
  28. @ResponseBody
  29. public String notify(HttpServletRequest request) throws AlipayApiException {
  30. Map<String, String> params = new HashMap<>();
  31. Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();
  32. for (Map.Entry<String, String[]> entry : entrySet) {
  33. String name = entry.getKey();
  34. String[] values = entry.getValue();
  35. int valLen = values.length;
  36. if (valLen == 1) {
  37. params.put(name, values[0]);
  38. } else if (valLen > 1) {
  39. StringBuilder sb = new StringBuilder();
  40. for (String val : values) {
  41. sb.append(",").append(val);
  42. }
  43. params.put(name, sb.substring(1));
  44. } else {
  45. params.put(name, "");
  46. }
  47. }
  48. log.info("支付宝回调 {}", JSON.toJSONString(params, PrettyFormat));
  49. AlipaySignature.rsaCheckV1(params, alipayProperties.getAliPublicKey(), "UTF-8", "RSA2");
  50. if (MapUtils.getString(params, "trade_status").equals("TRADE_SUCCESS")) {
  51. JSONObject body = JSON.parseObject(params.get("body"));
  52. String action = body.getString("action");
  53. switch (action) {
  54. case "payOrder":
  55. Long orderId = body.getLong("orderId");
  56. orderService.notifyAlipay(orderId, params);
  57. break;
  58. }
  59. return "success";
  60. }
  61. return "error";
  62. }
  63. }