1.进入支付宝开放者平台
https://openhome.alipay.com/platform/home.htm
注册并实名
下载并注册花生壳,将内网映射为外网可以访问的的工具
2.导入pom依赖
<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>3.7.110.ALL</version>
</dependency>
3.controller
@RestController
public class PayController {
@RequestMapping("/pay")
public void pay(HttpServletRequest httpRequest,
HttpServletResponse httpResponse) throws IOException {
AlipayClient alipayClient = new DefaultAlipayClient( "https://openapi.alipaydev.com/gateway.do" , "AppID", "自己的私钥", "json", "utf-8", "自己的公钥", "RSA2"); //获得初始化的AlipayClient
AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest(); //创建API对应的request
//支付成功后的回调地址
alipayRequest.setReturnUrl( "回调网址(花生壳)" );
alipayRequest.setNotifyUrl( "http://domain.com/CallBack/notify_url.jsp" ); //在公共参数中设置回跳和通知地址
alipayRequest.setBizContent("{" +
" \"out_trade_no\":\"12345678909875\"," +
" \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
" \"total_amount\":88.88," +
" \"subject\":\"Iphone6 16G\"," +
" \"body\":\"Iphone6 16G\"," +
" \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
" \"extend_params\":{" +
" \"sys_service_provider_id\":\"2088511833207846\"" +
" }" +
" }" ); //填充业务参数
String form= "" ;
try {
form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
} catch (AlipayApiException e) {
e.printStackTrace();
}
httpResponse.setContentType( "text/html;charset=" + "UTF-8");
httpResponse.getWriter().write(form); //直接将完整的表单html输出到页面
httpResponse.getWriter().flush();
httpResponse.getWriter().close();
}
@RequestMapping("/returnUrl")
public void returnUrl(HttpServletRequest request , HttpResponse httpResp) throws AlipayApiException {
Map<String, String> stringStringMap = convertRequestParamsToMap(request);
boolean signVerified = AlipaySignature.rsaCheckV1(stringStringMap, "公钥", "utf-8", "RSA2"); //调用SDK验证签名
if (signVerified){
// TODO 验签成功后,按照支付结果异步通知中的描述,对支付结果中的业务内容进行二次校验,校验成功后在response中返回success并继续商户自身业务处理,校验失败返回failure
System.out.println(stringStringMap);
} else {
// TODO 验签失败则记录异常日志,并在response中返回failure.
}
}
// 将request中的参数转换成Map
private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
Map<String, String> retMap = new HashMap<String, String>();
Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();
for (Map.Entry<String, String[]> entry : entrySet) {
String name = entry.getKey();
String[] values = entry.getValue();
int valLen = values.length;
if (valLen == 1) {
retMap.put(name, values[0]);
} else if (valLen > 1) {
StringBuilder sb = new StringBuilder();
for (String val : values) {
sb.append(",").append(val);
}
retMap.put(name, sb.toString().substring(1));
} else {
retMap.put(name, "");
}
}
return retMap;
}
}
4.访问
http://localhost:8088/pay