支付宝扫码支付需要开通当面付权限,具体请在支付宝开放平台上线应用中申请。
扫码支付服务端的代码:
/**
* 支付宝扫码支付
* @return 支付宝生成的订单信息
*/
@RequestMapping(value = "/scancodepay")
public String scancodepay(
) throws AlipayApiException {
final String APPID = "你的appid";
String PID = "你的商户id";
String TARGET_ID = "你的商家账号";
String RSA2_PRIVATE = "你的本地私钥";
String RSA_PRIVATE = "";
String ALIPAY_PUBLIC_KEY = "你的支付宝公钥";
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");//可以方便地修改日期格式
String hehe = dateFormat.format(now);
String order_no=hehe+"scancodealipay"; //77777777
String body = "";
String total_fee="0.01"; //真实金钱
AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", APPID, RSA2_PRIVATE, "json",
"UTF-8", ALIPAY_PUBLIC_KEY, "RSA2"); //获得初始化的AlipayClient
AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();//创建API对应的request类
request.setBizContent("{" +
" \"out_trade_no\":\"" + order_no + "\"," +
" \"total_amount\":\"" + total_fee + "\"," +
" \"body\":\"" + body + "\"," +
" \"subject\":\"扫码支付\"," +
" \"timeout_express\":\"90m\"}");//设置业务参数
request.setNotifyUrl("你的外网异步通知地址");
AlipayTradePrecreateResponse response = alipayClient.execute(request);//通过alipayClient调用API,获得对应的response类
System.err.print(response.getBody());
//根据response中的结果继续业务逻辑处理
if (response.getMsg().equals("Success")) {
String qrcode = response.getQrCode();
return qrcode);
// return qrcode;
} else return "请求失败";
}
最后得到的qrcode,就是要生成二维码的字符串。用生成二维码的工具来对此字符串进行处理即可。
顺便把处理异步通知的代码一起贴了:
@SuppressWarnings("rawtypes")
@RequestMapping(value = "/notify", method = RequestMethod.POST)
public String notify(HttpServletRequest request,
HttpServletResponse response) throws AlipayApiException {
Map<String, String> params = new HashMap<String, String>();
Map requestParams = request.getParameterMap();
for (Iterator 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] + ",";
}
params.put(name, valueStr);
}
System.err.println(params);
String CHARSET = "UTF-8";
//支付宝公钥
String ALIPAY_PUBLIC_KEY = "你的支付宝公钥";
String tradeStatus = request.getParameter("trade_status");
boolean flag = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, "RSA2");
if (flag) {//验证成功
if (tradeStatus.equals("TRADE_FINISHED") || tradeStatus.equals("TRADE_SUCCESS")) {
//要写的逻辑。自己按自己的要求写
}
return "success";
} else {//验证失败
System.out.println("fail yanzheng");
return "fail";
}
}