支付宝支付
程序员文章站
2022-04-11 13:47:21
...
支付宝支付
支付宝支付接入流程
入驻开放平台
打开支付宝开放平台https://open.alipay.com/platform/home.htm
入驻成*开发者
获取沙箱账号
点击 开发中心 -> 研发服务
复制出来到文本文件备用,点击沙箱工具,下载沙箱版钱包,分别用商家、卖家账号进行登录
设置应用公钥
设置回调地址
利用ngrok进行内网穿透
点击下载:ngrok下载地址
运行ngrok:
ngrok http 8080 #转发请求到本机8080端口
代码实现
POM
<!-- https://mvnrepository.com/artifact/com.alipay.sdk/alipay-sdk-java -->
<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>3.4.27.ALL</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
配置文件application.yml:
alipay:
gatewayUrl: https://openapi.alipaydev.com/gateway.do
appid: 2016092800614971
privateKey: MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDTRiTjtaJCBjGtRTMnqjLu2PEXs/4ZHbW6bNSqO6ScmbUdPcn+nNIcjGZKwhXeuVDXjqRDGuwCw9EVY2rI/rA0Qz7QX9fbsGzA4GQ4JK0cerHJjp386hRtKSEj6Gp/JMa34KPlbLtLLg9oxz/dA5e+tqIciNwi4b7ln5pH0bhGpcUxbjcwsKq7GBdMp+FtfhavuyOxwa4+w17jI9idTrAq6M+f/AngDngyJOMA7xSkpKfr+tB3iI56ZhD1ngh0zoFg9I3hksUuTHxhe4UWxCD7aYGX15qb8Hc2/3hWK3m2drCl7l6z/RhVmwaqsv5bzBfGzQmucatBjkIcjqpefzS1AgMBAAECggEAPBmhFtGthaCjcwnTYn4tHPrDop2GM/jaoFyjJoXu7sle1yGjm3Va49ogozWQ6RnIYHloStqWtrajfLUaRHEHCOb0MGyDSDBoz3lFqR7ty8MvXgne8XpZM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UHJYoFikDyk+Rgk/aEUi4EImR
alipayPublicKey: MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA00Yk47WiQgYxrUUzJ6oy7tjxF7P+GR21umzUqjuknJm1HT3J/pzSHIxmSsIV3rlQ146kQxrsAsPRFWNqyP6wNEM+0F/X27BswOBkOCStHHqxyY6d/OoUbSkhI+hqfyTGt+Cj5Wy7Sy4PaMc/3QOXvraiHIjcIuG+5Z+aR9G4RqXFMW43MLCquxgXTKfhbX4Wr7sjscGuPsNe4yPYnU6wKujPn/wJ4A54MiTjAO8UpKSn6/rQd4iOemYQ9Z4IdM6BYPSN4ZLFLkx8YXuFFsQg+2mBl9eam/B3Nv94Vit5tnawpe5es/0YVZsGqrL+W8wXxs0JrnGrQY5CHI6qXn80tQIDAQAB
#支付成功跳转的商家url
returnUrl: http://localhost:8080/callback
#异常跳转页面
notifyUrl: https://354c9624.ngrok.io/callback_nsync
Java配置文件
- AlipayConfig.java
package com.suoron.springboot.config;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties(AlipayProperties.class)
public class AlipayConfig {
@Resource
private AlipayProperties properties;
/**
* alipay-sdk-java
* @return
*/
@Bean
public AlipayClient alipayClient(){
return new DefaultAlipayClient(properties.getGatewayUrl(),
properties.getAppid(),
properties.getPrivateKey(),
properties.getFormate(),
properties.getCharset(),
properties.getAlipayPublicKey(),
properties.getSignType());
}
}
- AlipayProperties.java
package com.suoron.springboot.config;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
/**
* 支付宝支付的参数配置
*
* @author Suoron
*/
@Data
@Slf4j
@ConfigurationProperties(prefix = "alipay")
public class AlipayProperties {
/** 支付宝gatewayUrl */
private String gatewayUrl;
/** 商户应用id */
private String appid;
/** RSA私钥,用于对商户请求报文加签 */
private String privateKey;
/** 支付宝RSA公钥,用于验签支付宝应答 */
private String alipayPublicKey;
/** 签名类型 */
private String signType = "RSA2";
/** 格式 */
private String formate = "json";
/** 编码 */
private String charset = "UTF-8";
/** 同步地址 */
private String returnUrl;
/** 异步地址 */
private String notifyUrl;
/** 最大查询次数 */
private static int maxQueryRetry = 5;
/** 查询间隔(毫秒) */
private static long queryDuration = 5000;
/** 最大撤销次数 */
private static int maxCancelRetry = 3;
/** 撤销间隔(毫秒) */
private static long cancelDuration = 3000;
private AlipayProperties() {}
/**
* PostContruct是spring框架的注解,在方法上加该注解会在项目启动的时候执行该方法,也可以理解为在spring容器初始化的时候执行该方法。
*/
@PostConstruct
public void init() {
log.info(description());
}
public String description() {
StringBuilder sb = new StringBuilder("\nConfigs{");
sb.append("支付宝网关: ").append(gatewayUrl).append("\n");
sb.append(", appid: ").append(appid).append("\n");
sb.append(", 商户RSA私钥: ").append(getKeyDescription(privateKey)).append("\n");
sb.append(", 支付宝RSA公钥: ").append(getKeyDescription(alipayPublicKey)).append("\n");
sb.append(", 签名类型: ").append(signType).append("\n");
sb.append(", 查询重试次数: ").append(maxQueryRetry).append("\n");
sb.append(", 查询间隔(毫秒): ").append(queryDuration).append("\n");
sb.append(", 撤销尝试次数: ").append(maxCancelRetry).append("\n");
sb.append(", 撤销重试间隔(毫秒): ").append(cancelDuration).append("\n");
sb.append("}");
return sb.toString();
}
private String getKeyDescription(String key) {
int showLength = 6;
if (!StringUtils.isEmpty(key) && key.length() > showLength) {
return new StringBuilder(key.substring(0, showLength)).append("******")
.append(key.substring(key.length() - showLength)).toString();
}
return null;
}
}
请求Service
- AlipayService.java
package com.suoron.springboot.service;
public interface AlipayService {
public String getwayPay();
}
- AlipayServiceImpl.java
package com.suoron.springboot.service.impl;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayResponse;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.suoron.springboot.config.AlipayProperties;
import com.suoron.springboot.service.AlipayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.UUID;
@Service
public class AlipayServiceImpl implements AlipayService {
@Resource
private AlipayClient alipayClient;
@Resource
private AlipayProperties aliPayProperties;
@Override
public String getwayPay() {
String productCode = "FAST_INSTANT_TRADE_PAY";
AlipayTradePagePayModel model = new AlipayTradePagePayModel();
model.setOutTradeNo(UUID.randomUUID().toString());
model.setSubject("支付测试");
model.setTotalAmount("10");
model.setBody("支付测试,共10元");
model.setProductCode(productCode);
AlipayTradePagePayRequest pagePayRequest = new AlipayTradePagePayRequest();
pagePayRequest.setReturnUrl(aliPayProperties.getReturnUrl());
pagePayRequest.setNotifyUrl(aliPayProperties.getNotifyUrl());
pagePayRequest.setBizModel(model);
// 调用SDK生成表单, 并直接将完整的表单html输出到页面
String retStr = null;
try {
retStr = alipayClient.pageExecute(pagePayRequest).getBody();
} catch (AlipayApiException e) {
e.printStackTrace();
}
return retStr;
}
}
支付请求Controller
package com.suoron.springboot.controller;
import com.sun.deploy.net.HttpResponse;
import com.suoron.springboot.service.AlipayService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
/**
* @author Suoron
*/
@Controller
public class TestController {
@Resource
AlipayService alipayService;
@RequestMapping(value = "/test",method = RequestMethod.GET)
public void test(HttpServletResponse response){
try {
response.setContentType("text/html; charset=utf-8");
response.getWriter().write("<h1>支付测试</h1>");
response.getWriter().write("<br/><a href='paytest'>前往支付页面</a>");
response.getWriter().close();
} catch (IOException e) {
e.printStackTrace();
}
}
@RequestMapping(value = "/paytest",method = RequestMethod.GET)
public void testPay(HttpServletResponse response){
try {
response.setContentType("text/html; charset=utf-8");
response.getWriter().write(alipayService.getwayPay());
response.getWriter().close();
} catch (IOException e) {
e.printStackTrace();
}
}
@RequestMapping(value = "/callback",method = RequestMethod.GET)
public void callback(HttpServletRequest request,HttpServletResponse response){
try {
response.setContentType("text/html; charset=utf-8");
Enumeration enu = request.getParameterNames();
while(enu.hasMoreElements()){
String paraName=(String)enu.nextElement();
response.getWriter().write(paraName+": "+request.getParameter(paraName)+"<br>");
}
response.getWriter().close();
} catch (IOException e) {
e.printStackTrace();
}
}
@RequestMapping(value = "/callback_nsync")
public void callback_nsync(HttpServletRequest request,HttpServletResponse response){
System.out.println("1111111111111111111111111111");
try {
response.setContentType("text/html; charset=utf-8");
Enumeration enu = request.getParameterNames();
while(enu.hasMoreElements()){
String paraName=(String)enu.nextElement();
System.out.println(paraName+": "+request.getParameter(paraName));
}
response.getWriter().close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
上一篇: cakephp工作笔记42-3态旋钮效果
下一篇: 一个PHP SoapServer实例代码