当前位置:网站首页>Alipay payment interface sandbox environment test and integration into an SSM e-commerce project
Alipay payment interface sandbox environment test and integration into an SSM e-commerce project
2022-06-25 23:50:00 【Program diary】
preparation
- official demo
- Alipay account
- eclipse/idea
- tomcat
Specific steps
- First download the official demo
https://docs.open.alipay.com/270/106291/ - Import to eclipse in
Be careful : Because of this demo No maven The project has to be configured locally tomcat - Register a developer account on the Alipay open platform , Enter sandbox
- Enter the sandbox and you will see a appid And Alipay gateway for testing , This configuration file is used to configure our project , We'll use that later
- Generate application key and application public key
Download the Alipay open platform development assistant according to the steps described , Generate application key and application public key
And configure and apply the public key in the sandbox environment
After configuration, there will be a Alipay public key , This also needs to be configured in the configuration file - About demo
There is a pile of jsp Documents and a config class , Actually jsp It is also written in the document java Code
config class : Parameters to be configured
app_id: It's in your sandbox appid, If the application is formal, there will also be one appid
merchant_private_key: Application of the private key , The application private key just generated
alipay_public_key: Alipay public key , This is the Alipay public key generated after the application public key just configured in the sandbox is configured , Note that the application public key is not configured here !
notify_url: This is the path of the asynchronous notification page of the Alipay server , The details of how to handle the code are in notify_url.jsp in
return_url: This is the path to the synchronization notification page of Alipay server , After the payment is completed, you will be prompted to jump to the merchant page, that is, this page , The specific code can be seen demo Medium return_url.jsp
gatewayUrl: This is very important , It is the gateway of Alipay , Because we are a sandbox environment, we must configure the gateway for testing - Run the test
function index.jsp
Click pay , You will successfully jump to the code scanning page ( If prompted phishing sites , It is recommended to change the browser or close the browser page about Alipay before paying )
How to pay ?
At this time, note that the sandbox provides a test account number , You can download the sandbox version of Alipay app Log in to the test account for payment , It's fine too , Click the login account payment on the right to make payment
Sandbox account :
After payment
It also jumps to the synchronization notification page
The same is true of the basic process .
Integrate to ssm In the project
General train of thought : There is a shopping cart settlement page in the project , Click submit order ,controller In dealing with , View the payment method for this order , If it is online payment, jump to another controller in , This controller That is to say demo Process payment jump in jsp The code in , And one more return_url Used to synchronize page notifications , This configuration is also a controller To handle jump to a success.jsp Page of successful payment , This controller In addition to jumping to the payment success page, you can also process the business logic of changing the order status to paid
First, click submit order , You need to create an order , Then determine the order status , Cash on delivery or online payment
@RequestMapping("/create")
public String orderCreate(Order order, Model model,HttpServletRequest request){
try {
System.out.println(" The payment method is :"+order.getPaymentType());
// Get user information , because order The following are intercepted by interceptors , The interceptor stores the user information in the request
TbUser user = (TbUser) request.getAttribute("user");
// Set user information , Complete the user information before submitting the order
order.setBuyerNick(user.getUsername());
order.setUserId(user.getId());
String orderId = orderService.createOrder(order);
// After creating the order , If the payment method of the order is 4, On behalf of online payment , We want to jump to the online payment page
if(order.getPaymentType() == 4){
return "redirect:/order/goAliPay/"+orderId+".html";
}
model.addAttribute("paymentType",order.getPaymentType());
model.addAttribute("orderId",orderId);
model.addAttribute("payment",order.getPayment());
model.addAttribute("date",new DateTime().plusDays(3).toString("yyyy-MM-dd"));
return "success";
} catch (Exception e) {
e.printStackTrace();
model.addAttribute("message"," There's a problem ...");
return "/error/exception";
}
}
Pay online , Jump to another controller, Note that there is a coding setting here , If not set to UTF-8 The signature verification will fail , And the interface css The problem of style disappearing .
@RequestMapping(value = "/goAliPay/{orderId}",produces = "text/html; charset=UTF-8")
@ResponseBody
public String goAlipay(@PathVariable String orderId, HttpServletRequest request, HttpServletRequest response) throws Exception {
// according to orderId Get order information
Order order = orderService.getOrderByOrderId(orderId);
// Get initialized AlipayClient
AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
// Set request parameters
AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
alipayRequest.setReturnUrl(AlipayConfig.return_url);
alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
// Merchant order number , The unique order number in the order system of the merchant website , Required
String out_trade_no = orderId;
// The payment amount , Required
String total_amount = order.getPayment();
// Name of the order , Required
String subject = order.getOrderItems().get(0).getTitle();
// Commodity Description , Can be empty
String body = order.getOrderItems().get(0).getTitle();
// Latest payment time allowed for this order , Transaction will be closed if overdue . Value range :1m~15d.m- minute ,h- Hours ,d- God ,1c- same day (1c- In the case of the day , Whenever a transaction is created , All in 0 Point closure ). Decimal point is not accepted for this parameter value , Such as 1.5h, Convertible to 90m.
String timeout_express = "1c";
alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
+ "\"total_amount\":\""+ total_amount +"\","
+ "\"subject\":\""+ subject +"\","
+ "\"body\":\""+ body +"\","
+ "\"timeout_express\":\""+ timeout_express +"\","
+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
// request
String result = alipayClient.pageExecute(alipayRequest).getBody();
return result;
}
Payment success synchronization notification page controller
@RequestMapping("/paySuccess")
public String paySuccess(HttpServletRequest request, HttpServletResponse response,Model model) throws Exception {
// Access to alipay GET Come and give me feedback
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] + ",";
}
// The code to solve , This code is used in case of garbled code
valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
params.put(name, valueStr);
}
boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); // call SDK Verify the signature
if(signVerified) {
// Merchant order number
String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
// Alipay transaction number
String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
// The payment amount
String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
Order order = orderService.getOrderByOrderId(out_trade_no);
order.setStatus(2);
// Modify order status
Integer integer = orderService.changeStatus(order);
// Return to normal modification success
if (integer == 200){
// There is also an additional payment method for the order
model.addAttribute("paymentType",order.getPaymentType());
model.addAttribute("orderId",order.getOrderId());
model.addAttribute("payment",order.getPayment());
model.addAttribute("date",new DateTime().plusDays(3).toString("yyyy-MM-dd"));
return "success";
}else{
return "/error/exception";
}
}else {
System.out.println(" Attestation of failure ");
}
return "/error/exception";
}
This is also copied demo The code in can be slightly modified
The overall integration process is like this , The key to integration is to analyze demo Medium alipay.trade.page.pay.jsp and return_url.jsp and notify_url.jsp, There are very detailed instructions in it !
The integration of payment interface and project is over
边栏推荐
猜你喜欢
Uniapp -- the use of document collation and push of unipush
Architecture part -- the use of UMI framework and DVA
Online customer service - charging standards and service provision of third parties
Wireshark对IMAP抓包分析
解析產品開發失敗的5個根本原因
C# IO Stream 流(二)扩展类_封装器
Database - mongodb
SSM整合学习笔记(主要是思路)
DPVS-FullNAT模式管理篇
mysql版本升级+数据迁移
随机推荐
使用npm创建并发布包时遇到的常见问题
On the quantity control mechanism of swoole collaboration creation in production environment
Tree class query component
聊聊swoole或者php cli 进程如何热重启
Leetcode 513. 找树左下角的值
登录拦截器
支付宝支付接口沙箱环境测试以及整合到一个ssm电商项目中
对伪类的理解
数据同步
一文讲透研发效能!您关心的问题都在
MySQL InnoDB lock knowledge points
MySQL InnoDB锁知识点
推荐系统设计
18亿像素火星全景超高清NASA放出,非常震撼
Kylin
解析产品开发失败的5个根本原因
CXF
InputStream流已经关闭了,但是依旧无法delete文件或者文件夹,提示被JVM占用等
final和static
使用百度地图API在地图中设置一个覆盖物(InfoWindow),可自定义窗口内容