谷粒商城整合支付宝(四十五)
304-309
主要对支付宝的开放平台对接的使用,验签收单有了一定的连接。
视频中的nginx配置:
我没有动这块,还是走的阿里云:
代码具体如下:
@ConfigurationProperties(prefix = "alipay")
@Component
public class AlipayTemplate {
// 应用ID,您的APPID,收款账号既是您的APPID对应支付宝账号
public static String app_id = "2021000116667682";
// 商户私钥,您的PKCS8格式RSA2私钥
public static String merchant_private_key = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQClo7YKk8lnuHsKe4aOLmNd/vCRZ5ia8kpxvSR9iy1REkpfVV1cV1TqQlSj3OZ62PtoHDNbCbgp01gUxe/96PwObjpWudxtVklf8YifTFWPafed0q0blEBayzXt26tX8H/Uxd0oKFmdh+VYLDJ6or3qPfrhd8f298v1Ijrc1ituAgTsHybQ946WpnE+JhTAmCinzxeDrXAOZ96WDyaZB7hxPKu+AvLEU/RJIxKLXyVN51rEeI+kYDNQvscs/8WVXN0Qldkd1bXnB5RpOeEl7D7Q7ZasK4Q9vRnSw1Yu1vtWv5HlUgopfCweix+wkIWK/dFTfF5i5KW0etXJc38vCLw9AgMBAAECggEAOCtcABo9oj6c+uEIsA5rA+UAD07iISkotYk+ZpRbubJKJin8juPOl+IGccrnHaGXH6bwg164ZPaWV/UHfUMUtpAKmH5OkYVBPJfbjKmGGiwFHC/lJAUSDbf7gb2MTTXxI2Y1qPiF6zW6QDw8ofmuDVEXUn4cAVPmhiola930vEjGdCFvY1vTOFw64fECAnE8/zkEF98byluE3DqSFZmUQfMeuu0LYwMcVCiv+qXmBH/I5ojOfXCHkbzUPYCE0OIg4Agu1QMlkA6YXn0d4KW7nrME1BUC2UJTNFsJwP5wg5hWiNOEab8vlsYKIIiFPlO0+VFUWAXPz6IaEFjSMaFewQKBgQDmmZvrLP3QFF3HeE74yKymvM5OOjP1ovKde7jko2fZPUmJst6ef4/VI39BHLTWS/IHc9OpufPfFrObgf2vbaLvc+xzQcz5EeuH+haYYIF6PFLAvhpl6+nv8BNh8nlZjr7GCqOqKR+gfPfJHakA2q1H2if1c4HLsyTgUc2VurxcOwKBgQC34l05vgSK2vDlgj9haWohtJBSZl+iHuMb9+Df6Dhc81ugUKx1QjQApyYTAaxUDGWY6NxQ7NSWjO4qcXM5KDL/GJhFRRC5qZDNERQ2jPpieqIq0BiYWYGOn57V3wNOFU8xk8rKMVhiGATcHpPG9bHP6a7uQ65TlX7DTuImhfNZ5wKBgQCPtEBXQXV2m4qJiO7l2ODHE7gZReoldINvIq/pQ++ukKPoPODAs0vmDjX6VLJZLYDJpiPMjIZuiw4opcx6637zbDF47hOXT9SQq4gzM0jc7QTA+ncm9uqVTO43Rszaw7sdXXn6y5/a+qXL3kD4uE3uDgSC0JWdZKlhZXkRiwphCwKBgQC2GYii9yc+b0Vis5KaoC8HQ+4se883GIlmGBrtAeZXPnS9lUbENJSVFPJiniSPc1tliy0rQu3gTZ5KD+HAd6vQ7gVVi+jdRCvuuHwg7YnD3pgb98pzjSf9GtvMBrcaK4YqnaaUhzt0oT6m0e0cehHlyRCASiwoAALx3XueFMcCfwKBgQCrFBEOO04bWDX0pTrA2OU8FtvoXAUl2ji3FOXC4sUxgFnT9dFw/PlpGtx9DjYcspvHC+cNAYkxAUepePXkZbj8SSOgHjsdKouSM+Nwo9+93DGN29YUO6l6AIt6IPxXvSGUTQUCPlBQ2A1y4YFEjg5uxu85u3AYqa6a4qYTVMFKeQ==";
// 支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
public static String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkTof8EkrceHNaJcuqPx7aAUFPJ1X3WBwf9wDgPlQ2U/lnNCd6z196azAYpR9WJSqZv9iJY9TFVBIr+XHr4hFsdIgyb3ZkH6MIs3x2yahMij+3msUY34NQkrz3S90Fb1FfTFYoANOxwhP2Q7QyfNyJkZgcVvCnf66lsGt/E1eXxUP8xpVcHUgWVHp+orGlMXkGsC8XuHcTTFCAdhA+NHHjDCPLOJ1cWcqDjmSk8WqH+FGEvGt+HwiNxZvImoa4+4CIwlwAv+CayRgjvpqk6H50KNkTP54AVgR1DYCs6nqvoGuj6V+mlEisT9U1Rl5XJxX6JPg0ddGq1rDdFh+wGRM/wIDAQAB";
// 服务器异步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
public static String notify_url = "http://47.110.91.150/payed/notify";
// 页面跳转同步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
public static String return_url = "http://member.gulimall.com/memberOrder.html";
// 签名方式
public static String sign_type = "RSA2";
// 字符编码格式
public static String charset = "utf-8";
// 支付宝网关
public static String gatewayUrl = "https://openapi.alipaydev.com/gateway.do";
public String pay(PayVo vo) throws AlipayApiException {
//AlipayClient alipayClient = new DefaultAlipayClient(AlipayTemplate.gatewayUrl, AlipayTemplate.app_id, AlipayTemplate.merchant_private_key, "json", AlipayTemplate.charset, AlipayTemplate.alipay_public_key, AlipayTemplate.sign_type);
//1、根据支付宝的配置生成一个支付客户端
AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl,
app_id, merchant_private_key, "json",
charset, alipay_public_key, sign_type);
//2、创建一个支付请求 //设置请求参数
AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
alipayRequest.setReturnUrl(return_url);
alipayRequest.setNotifyUrl(notify_url);
//商户订单号,商户网站订单系统中唯一订单号,必填
String out_trade_no = vo.getOut_trade_no();
//付款金额,必填
String total_amount = vo.getTotal_amount();
//订单名称,必填
String subject = vo.getSubject();
//商品描述,可空
String body = vo.getBody();
alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
+ "\"total_amount\":\""+ total_amount +"\","
+ "\"subject\":\""+ subject +"\","
+ "\"body\":\""+ body +"\","
+ "\"timeout_express\":\"1m\","
+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
String result = alipayClient.pageExecute(alipayRequest).getBody();
//会收到支付宝的响应,响应的是一个页面,只要浏览器显示这个页面,就会自动来到支付宝的收银台页面
System.out.println("支付宝的响应:"+result);
return result;
}
}
进行验签:
/**
* @author WGR
* @create 2020/8/13 -- 0:03
*/
@RestController
public class OrderPayedListener {
@Autowired
OrderService orderService;
@PostMapping("/payed/notify")
@SneakyThrows
public String handleAlipayed(PayAsyncVo vo, HttpServletRequest request){
// Map<String, String[]> parameterMap = request.getParameterMap();
// for (String key : parameterMap.keySet()){
// String value = request.getParameter(key);
// System.out.println("参数名:"+key+"==>参数值:"+value);
// }
//获取支付宝GET过来反馈信息
Map<String,String> params = new HashMap<String,String>();
Map<String,String[]> requestParams = request.getParameterMap();
for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
String name = (String) iter.next();
String[] values = (String[]) requestParams.get(name);
String valueStr = "";
for (int i = 0; i < values.length; i++) {
valueStr = (i == values.length - 1) ? valueStr + values[i]
: valueStr + values[i] + ",";
}
//乱码解决,这段代码在出现乱码时使用
// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
params.put(name, valueStr);
}
boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayTemplate.alipay_public_key, AlipayTemplate.charset, AlipayTemplate.sign_type); //调用SDK验证签名
//——请在这里编写您的程序(以下代码仅作参考)——
if(signVerified) {
System.out.println("验签成功");
String reuslt = orderService.handlePayResult(vo);
return reuslt;
}else {
System.out.println("验签失败");
return "error";
}
}
}
需要放行:
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String uri = request.getRequestURI();
AntPathMatcher antPathMatcher = new AntPathMatcher();
boolean match = antPathMatcher.match("/order/order/status/**", uri);
boolean match1 = antPathMatcher.match("/payed/notify", uri);
if(match || match1){
return true;
}
MemberRespVo attribute = (MemberRespVo)request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
if(attribute !=null){
loginUser.set(attribute);
return true;
}else{
request.getSession().setAttribute("msg","请先进行登录");
response.sendRedirect("http://auth.gulimall.com/login.html");
return false;
}
}
@Override
public String handlePayResult(PayAsyncVo vo) {
//1.保存交易流水
PaymentInfoEntity infoEntity = new PaymentInfoEntity();
infoEntity.setAlipayTradeNo(vo.getTrade_no());
infoEntity.setOrderSn(vo.getOut_trade_no());
infoEntity.setPaymentStatus(vo.getTrade_status());
infoEntity.setCallbackTime(vo.getNotify_time());
paymentInfoService.save(infoEntity);
//2.修改订单的状态信息
if(vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")){
String outTradeNo = vo.getOut_trade_no();
this.baseMapper.updateOrderStatus(outTradeNo,OrderStatusEnum.PAYED.getCode());
}
return "success";
}
@Override
public PageUtils queryPageWithItem(Map<String, Object> params) {
MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
IPage<OrderEntity> page = this.page(
new Query<OrderEntity>().getPage(params),
new QueryWrapper<OrderEntity>().eq("member_id",memberRespVo.getId() ).orderByDesc("id")
);
List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
order.setItemEntities(itemEntities);
return order;
}).collect(Collectors.toList());
page.setRecords(order_sn);
return new PageUtils(page);
}