一、支付宝接入实现
1、流程
step1 : 用户在浏览器中访问商家网页应用,选择商品下单,确认购买,接口会调起支付宝客户端内的支付模块,此时会从商家网页应用跳转到支付宝客户端中并开始支付,支付完成后会跳转回商家网页应用内,最后商家展示支付结构
step2:进入到支付宝支付路由页面,支付宝处理支付请求,并尝试唤起支付宝客户端
step3:用户确认收款方和金额,点击立即支付后出现输入密码界面
step4:输入正确密码后,支付宝端显示支付结果
step5:自动回调到浏览器中,商家根据付款结果个性化展示订单处理结果
1.1 配置支付宝沙箱环境
- 注册开放平台账号
配置秘钥
沙箱账号
安装沙箱版支付宝
1.2 下单接口定义
接口定义:外部客户请求支付宝创建订单并支付
请求url
- 沙箱地址:https://openapi.alipaydev.com/gateway.do
- 正式环境:https://openapi.alipay.com/gateway.do
公共请求参数- https://opendocs.alipay.com/apis/api_1/alipay.trade.wap.pay
1.3 下单接口测试
- 依赖
<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>4.16.2.ALL</version>
</dependency>
- 代码
/**
* 支付宝接口对接测试类
*/
@Controller
public class PayTestController {
@RequestMapping("/")
public String getLogin(Model model) {
model.addAttribute("url", "/codelogin/");
return "login";
}
private static final Logger log = LoggerFactory.getLogger(PayTestController.class);
String serverUtl = "https://openapi.alipaydev.com/gateway.do";
//正式环境 String serverUtl = "https://openapi.alipay.com/gateway.do";
String APP_ID = "2021000117698452";
String APP_PRIVATE_KEY = “”;
String APP_ALIPAY_PUBLIC_KEY =“”
String CHARSET = "UTF-8";
String FORMAT = "json";
String SIGN_TYPE = "RSA2"; //签名的算法类型
@RequestMapping("/aliPayTest")
public void aliPayTest(HttpServletRequest req, HttpServletResponse resp) throws AlipayApiException, IOException {
// 构造sdk的客户端对象
AlipayClient alipayClient = new DefaultAlipayClient(
serverUtl,
APP_ID,
APP_PRIVATE_KEY,
FORMAT,
CHARSET,
APP_ALIPAY_PUBLIC_KEY,
SIGN_TYPE);
//创建API对应的request
AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
/**
*请求查询接口
AlipayAcquireQueryRequest alipayAcquireQueryRequest = new AlipayAcquireQueryRequest();
*/
// 设置
/* alipayRequest.setReturnUrl("");
alipayRequest.setNotifyUrl("");*/
// 填充业务参数
alipayRequest.setBizContent("{" +
" \"out_trade_no\":\"20150320010101003\"," +
"\"total_amount\":\"88.88\"," +
"\"subject\":\"Iphone12 16G by weixingyu\"," +
"\"product_code\":\"QUICK_WAP_PAY\"" +
"}"
);
//请求支付宝下单接口
AlipayTradeWapPayResponse response = alipayClient.pageExecute(alipayRequest);
if (response.isSuccess()) {
System.out.println("调用成功");
// 调用sdk生成表单
String form = response.getBody();
resp.setContentType("text/html;charset=" + CHARSET);
resp.getWriter().write(form);
resp.getWriter().flush();
resp.getWriter().close();
} else {
System.out.println("调用失败");
}
}
@RequestMapping("/codelogin")
public void getQrCode(HttpServletResponse response) {
try {
String path = "http://192.168.8.125/aliPayTest";
QrCodeUtil.generate(path, initQrConfig(), "png", response.getOutputStream());
} catch (IOException e) {
log.error("发生错误! {}!", e.getMessage());
}
}
// 自定义参数,这部分是Hutool工具封装的
private static QrConfig initQrConfig() {
QrConfig config = new QrConfig(300, 300);
// 设置边距,既二维码和背景之间的边距
config.setMargin(3);
// 设置前景色,既二维码颜色(青色)
config.setForeColor(Color.CYAN.getRGB());
// 设置背景色(灰色)
config.setBackColor(Color.GRAY.getRGB());
return config;
}
}