-
支付流程图
-
对接支付宝的准备工作
一、申请条件
1.企业或个体工商户可申请;
2. 提供真实有效的营业执照,且支付宝账户名称需与营业执照主体一致;
3. 网站能正常访问且页面信息有完整商品内容;
4. 网站必须通过ICP备案,个体户备案需与账户主体一致。
(团购类网站不支持个体工商户签约)
- alipay.properties
#支付宝的接口地址
alipay_url=https://openapi.alipay.com/gateway.do
#企业与支付宝合作伙伴Id
app_id=2018020102122556
#企业自己的私钥
app_private_key=MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCdQeknhM2rhiGAH6V0ljxn3rAWIdzduTEQuteTfwjnZtvMhQPuuN1b/88D5yMuaZhZNFeUdWb+SmtP9DAzAWWgnT13T0YhJcxP6txm7JBRrjadCRt+LOFxPiPQk5t9fH7yXjw9i4uMDsNJeTncrVZ/AZYrk0ESC9anJR8XeuBc3HE8T4fqlKKl35jlumIWrPbPNQhKGXaGcOnpiaXO9qYYUSP/tnrjNYXHOso0yBs4YTl+LLX2TJ12p3n/oX6HnL4zQgtN5k4QasHP7CIig1ngcVQGfWsMm4djI9KXNXvGLQPfMQEmyb71mM5OCdl1MtAc6OaIAymhSv2hOLNIuyodAgMBAAECggEAe05/P5mGm4QlKI2n8u8KlneqovASe1kG/BNFjkYB+VBR8OAr4TfbepPvAyRuFap+5xN/yMz14VcBJkRWtufVhEdHNxJV7w/wUIncIGhGEYYFFMVbZWhTrbQH6TiUp6TC9dCmc6vD1CKPRkFj+YGBXT0lPy3LzBa0TYNyCbszyhthrgkpuFYbB0R93IPvvBh5NJFXQytwNb2oVopC9AQWviqnZUZcT0eJ087dQ1WLPa6blBD8DP1PUq0Ldr6pgKfObFxIj8+87DlJznRfdEsbqZlS7jagdw5tLr71WJpctIGPqKpgvajfePP/lj3eY82BKQB+aTw0zmAiB05Yes4LgQKBgQDq3EiQR8J1MEN2rpiLt1WvDYYvKVUgOY7Od//fRPgaMBstbe4TzGBpR8E+z267bHAWLaWtHkfX6muFHn1x68ozEUW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L+I4Cy9Mvw3rIkTwt3MBU+AqREXY4r5Bn6cmmX/9MAJbFqrofGiUAqG+qbjTcZAzgNPfuiD0zXgt/YYjMQMzck75BOmwnYOam2ajODUSQn8Xybsa7wQIDAQAB# 同步回调地址 重定向地址本地浏览器
return_payment_url=http://payment.gmall.com:8087/alipay/callback/return# 异步通知地址 公网接口(webService)
notify_payment_url=http://60.205.215.91/alipay/callback/notifyreturn_order_url=http://order.gmall.com:8086/orderList
- 类AlipayConfig整合到项目
@Configuration
@PropertySource("classpath:alipay.properties")
public class AlipayConfig {@Value("${alipay_url}")private String alipay_url;@Value("${app_private_key}")private String app_private_key;@Value("${app_id}")private String app_id;public final static String format="json";public final static String charset="utf-8";public final static String sign_type="RSA2";public static String return_payment_url;public static String notify_payment_url;public static String return_order_url;public static String alipay_public_key;@Value("${alipay_public_key}")public void setAlipay_public_key(String alipay_public_key) {AlipayConfig.alipay_public_key = alipay_public_key;}@Value("${return_payment_url}")public void setReturn_url(String return_payment_url) {AlipayConfig.return_payment_url = return_payment_url;}@Value("${notify_payment_url}")public void setNotify_url(String notify_payment_url) {AlipayConfig.notify_payment_url = notify_payment_url;}@Value("${return_order_url}")public void setReturn_order_url(String return_order_url) {AlipayConfig.return_order_url = return_order_url;}@Beanpublic AlipayClient alipayClient(){AlipayClient alipayClient=new DefaultAlipayClient(alipay_url,app_id,app_private_key,format,charset, alipay_public_key,sign_type );return alipayClient;}
- PaymentMapper.java
public interface PaymentMapper extends Mapper<PaymentInfo>{
}
- PaymentServiceImpl.java
@Service
public class PaymentServiceImpl implements PaymentService{@AutowiredPaymentMapper paymentMapper;@AutowiredActiveMQUtil activeMQUtil;@AutowiredAlipayClient alipayClient;@Overridepublic void savePaymentInfo(PaymentInfo paymentInfo) {paymentMapper.insert(paymentInfo);}@Overridepublic void updatePayment(PaymentInfo paymentInfo) {//幂等性检查PaymentInfo paymentInfoParam = new PaymentInfo();paymentInfoParam.setOrderSn(paymentInfo.getOrderSn());PaymentInfo paymentInfoResult=paymentMapper.selectOne(paymentInfoParam);if(StringUtils.isNotBlank(paymentInfoResult.getPaymentStatus())&&paymentInfoResult.getPaymentStatus().equals("已支付")){return;}else{String orderSn = paymentInfo.getOrderSn();Example example=new Example(PaymentInfo.class);example.createCriteria().andEqualTo("orderSn",orderSn);ConnectionFactory connectionFactory = activeMQUtil.getConnectionFactory();Session session=null;Connection connection=null;try {connection = connectionFactory.createConnection();session = connection.createSession(true, Session.SESSION_TRANSACTED);} catch (JMSException e) {e.printStackTrace();}try{paymentMapper.updateByExampleSelective(paymentInfo,example);//支付成功后,引起系统服务===》订单服务===》库存服务===》物流//调用mq发送支付成功的消息Queue payment_success_queue = session.createQueue("PAYMENT_SUCCESS_QUEUE");MessageProducer producer = session.createProducer(payment_success_queue);//字符串文本//TextMessage textMessage=new ActiveMQTextMessage();//hash结构MapMessage mapMessage=new ActiveMQMapMessage();mapMessage.setString("out_trade_no",paymentInfo.getOrderSn());producer.send(mapMessage);session.commit();}catch (Exception e){//消息回滚try {session.rollback();} catch (JMSException e1) {e1.printStackTrace();}}finally {try {connection.close();} catch (JMSException e) {e.printStackTrace();}}}}@Overridepublic void sendDelayPaymentResultCheckQueue(String outTrade,int count) {ConnectionFactory connectionFactory = activeMQUtil.getConnectionFactory();Session session=null;Connection connection=null;try {connection = connectionFactory.createConnection();session = connection.createSession(true, Session.SESSION_TRANSACTED);} catch (JMSException e) {e.printStackTrace();}try{Queue payment_success_queue = session.createQueue("PAYMENT_CHECK_QUEUE");MessageProducer producer = session.createProducer(payment_success_queue);//字符串文本//TextMessage textMessage=new ActiveMQTextMessage();//hash结构MapMessage mapMessage=new ActiveMQMapMessage();mapMessage.setString("out_trade_no",outTrade);mapMessage.setInt("count",count);//为消息加入延迟时间mapMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY,1000*60);producer.send(mapMessage);session.commit();}catch (Exception e){//消息回滚try {session.rollback();} catch (JMSException e1) {e1.printStackTrace();}}finally {try {connection.close();} catch (JMSException e) {e.printStackTrace();}}}@Overridepublic Map<String, Object> checkAlipayPayment(String out_trade_no) {AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();HashMap<String, Object> resultMap = new HashMap<>();resultMap.put("out_trade_no",out_trade_no);request.setBizContent(JSON.toJSONString(resultMap));AlipayTradeQueryResponse response = null;try {response = alipayClient.execute(request);} catch (AlipayApiException e) {e.printStackTrace();}if(response.isSuccess()){System.out.println("交易创建已创建,调用成功");resultMap.put("out_trade_no",response.getOutTradeNo());resultMap.put("trade_no",response.getTradeNo());resultMap.put("trade_status",response.getTradeStatus());resultMap.put("call_back_content",response.getMsg());} else {System.out.println("有可能交易创建未创建,调用失败");}return resultMap;}
}
8.PaymentController.java
@Controller
public class PaymentController {@AutowiredAlipayClient alipayClient;@AutowiredPaymentService paymentService;@ReferenceOrderService orderService;@RequestMapping("alipay/callback/return")@LoginRequired(loginSuccess = true)public String aliPaycallBackReturn(HttpServletRequest request, ModelMap modelMap){//更新用户的支付状态String sign = request.getParameter("sign");String trade_no=request.getParameter("trade_no");String out_trade_no = request.getParameter("out_trade_no");String trade_status = request.getParameter("trade_status");String total_amount = request.getParameter("total_amount");String subject = request.getParameter("subject");String call_back_content = request.getQueryString();//通过支付宝的paymentMap进行签名验证,2.0版本中将接口paymentMap参数去掉了,导致同步请求无法验签if(StringUtils.isNotBlank(sign)){//验签成功//进行支付更新的幂等性检查操作PaymentInfo paymentInfo = new PaymentInfo();paymentInfo.setOrderSn(out_trade_no);//支付宝的交易凭证号paymentInfo.setPaymentStatus("已支付");paymentInfo.setAlipayTradeNo(trade_no);paymentInfo.setCallbackTime(new Date());//回调请求字符串paymentInfo.setCallbackContent(call_back_content);//更新用户的支付状态paymentService.updatePayment(paymentInfo);}//支付成功后,引起系统服务===》订单服务===》库存服务===》物流//调用mq发送支付成功的消息return "finish";}@RequestMapping("wx/submit")@LoginRequired(loginSuccess = true)public String wxPay(String outTrade, BigDecimal totalAmount, HttpServletRequest request, ModelMap modelMap){return "";}@RequestMapping("alipay/submit")@LoginRequired(loginSuccess = true)@ResponseBodypublic String aliPay(String outTrade, BigDecimal totalAmount, HttpServletRequest request, ModelMap modelMap){//获得支付宝客户端,不是一个链接而是针对http的表单请求String form="";//创建API对应的requestAlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//同步回调地址alipayRequest.setReturnUrl(AlipayConfig.return_payment_url);alipayRequest.setNotifyUrl(AlipayConfig.notify_payment_url);Map<String,Object> map=new HashMap<>();map.put("out_trade_no",outTrade);map.put("product_code","FAST_INSTANT_TRADE_PAY");map.put("total_amount",0.01);map.put("subject","JD Apple 10 phone");String param = JSON.toJSONString(map);alipayRequest.setBizContent(param);try {form = alipayClient.pageExecute(alipayRequest).getBody();} catch (AlipayApiException e) {e.printStackTrace();}//生成用户的支付信息OmsOrder omsOrder=orderService.getOrderByOutTradeNo(outTrade);PaymentInfo paymentInfo = new PaymentInfo();paymentInfo.setCreateTime(new Date());paymentInfo.setOrderId(omsOrder.getId());paymentInfo.setOrderSn(outTrade);paymentInfo.setPaymentStatus("未付款");paymentInfo.setSubject("JD商品");paymentInfo.setTotalAmount(totalAmount);paymentService.savePaymentInfo(paymentInfo );//向消息中间件发送一个检查支付状态(支付服务的延迟消息队列)paymentService.sendDelayPaymentResultCheckQueue(outTrade,5);//提交请求到支付宝return form;}@RequestMapping("index")@LoginRequired(loginSuccess = true)public String index(String outTrade, BigDecimal totalAmount, HttpServletRequest request, ModelMap modelMap){String memberId = (String)request.getAttribute("memberId");String nickName = (String) request.getAttribute("nickName");modelMap.put("memberId",memberId);modelMap.put("outTrade",outTrade);modelMap.put("nickName",nickName);modelMap.put("totalAmount",totalAmount);return "index";}
}