java调用支付宝的实现

框架使用的是spring boot
我们集成支付宝支付 也就需要提供两个接口出来.一个是给前端 作用是拿到请求参数加签返回给前端

前端拿到我们返回的数据.进行调起支付就行了,第二个接口是提供给支付宝的服务器,支付成功或者失败的时候.支付宝的服务器会回调我们的这个接口.异步通知我们支付结果

服务端sdk地址:https://doc.open.alipay.com/doc2/detail?treeId=54&articleId=103419&docType=1

前端集成地址:https://doc.open.alipay.com/docs/doc.htm?spm=a219a.7629140.0.0.HwBhZv&treeId=193&articleId=105296&docType=1

公钥 私钥 生成地址:https://doc.open.alipay.com/docs/doc.htm?spm=a219a.7629140.0.0.STtXnL&treeId=193&articleId=105310&docType=1

好了.废话不哆嗦,直接上代码:(此时,公钥 私钥环境都已经配好)

[java]  view plain  copy
  1. @RestController  
  2. @RequestMapping("/payment")  
  3. public class PaymentController {  
  4.     // 支付宝重要参数  
  5.     private static String APP_ID = "";  
  6.     private static String APP_PRIVATE_KEY = "";  
  7.     private static String CHARSET = "utf-8";  
  8.     private static String ALIPAY_PUBLIC_KEY = "";  
  9.   
  10.     /** 
  11.      * 对支付宝支付信息进行签名 
  12.      *  
  13.      * @param info 
  14.      *            数据类 
  15.      * @return 
  16.      * @throws AlipayApiException 
  17.      * @throws UnsupportedEncodingException 
  18.      */  
  19.     @PostMapping("/sign")  
  20.     public Object sign(@RequestBody SignInfo info) throws AlipayApiException, UnsupportedEncodingException {  
  21.         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  22.         String appID = APP_ID;  
  23.         String bizContent = toJson(info.Content);  
  24.         String charset = CHARSET;  
  25.         String method = "alipay.trade.app.pay";  
  26.         String signType = "RSA";  
  27.         String timestamp = sdf.format(new Date());  
  28.         String version = "1.0";  
  29.         String notify_url = "https://pay.ytbapp.com/payment/notify";// 增加支付异步通知回调,记住上下notify_url的位置,全在sign_type之前,很重要,同样放在最后都不行  
  30.         String content = "app_id=" + appID + "&biz_content=" + bizContent + "&charset=" + charset + "&method=" + method  
  31.                 + "¬ify_url=" + (notify_url) + "&sign_type=" + signType + "×tamp=" + timestamp + "&version="  
  32.                 + version;  
  33.   
  34.         String sign = AlipaySignature.rsaSign(content, APP_PRIVATE_KEY, charset);  
  35.   
  36.         return "{\"Result\": \"app_id=" + encode(appID) + "&biz_content=" + encode(bizContent) + "&charset="  
  37.                 + encode(charset) + "&method=" + encode(method) + "¬ify_url=" + encode(notify_url) + "&sign_type="  
  38.                 + encode(signType) + "×tamp=" + encode(timestamp) + "&version=" + encode(version) + "&sign="  
  39.                 + encode(sign) + "\"}";  
  40.     }  
  41.   
  42.     private String encode(String sign) throws UnsupportedEncodingException {  
  43.         return URLEncoder.encode(sign, "utf-8").replace("+""%20");  
  44.     }  
  45.   
  46.     private String toJson(BizContent content) {  
  47.         String context = "";  
  48.         context += "{" + "\"timeout_express\":\"" + content.timeout_express + "\"," + "\"seller_id\":\""  
  49.                 + content.seller_id + "\"," + "\"product_code\":\"" + content.product_code + "\","  
  50.                 + "\"total_amount\":\"" + content.total_amount + "\"," + "\"subject\":\"" + content.subject + "\","  
  51.                 + "\"body\":\"" + content.body + "\"," + "\"out_trade_no\":\"" + content.out_trade_no + "\"}";  
  52.   
  53.         return context;  
  54.     }  
  55.   
  56.     /** 
  57.      * 支付宝支付成功后.会回调该接口 
  58.      *  
  59.      * @param request 
  60.      * @return 
  61.      * @throws UnsupportedEncodingException 
  62.      */  
  63.     @PostMapping("/notify")  
  64.     public String notify(HttpServletRequest request) throws UnsupportedEncodingException {  
  65.         Map<String, String> params = new HashMap<String, String>();  
  66.         Map<String, String[]> requestParams = request.getParameterMap();  
  67.         for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {  
  68.             String name = iter.next();  
  69.             String[] values = requestParams.get(name);  
  70.             String valueStr = "";  
  71.             for (int i = 0; i < values.length; i++) {  
  72.                 valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";  
  73.             }  
  74.             // 乱码解决,这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化  
  75.             // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");  
  76.             params.put(name, valueStr);  
  77.         }  
  78.         String out_trade_no = request.getParameter("out_trade_no");// 商户订单号  
  79.         boolean signVerified = false;  
  80.         try {  
  81.             signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET);  
  82.         } catch (AlipayApiException e) {  
  83.             // TODO Auto-generated catch block  
  84.             e.printStackTrace();  
  85.             return ("fail");// 验签发生异常,则直接返回失败  
  86.         }  
  87.         // 调用SDK验证签名  
  88.         if (signVerified) {  
  89.             // TODO 验签成功后  
  90.             // 按照支付结果异步通知中的描述,对支付结果中的业务内容进行1\2\3\4二次校验,校验成功后在response中返回success,校验失败返回failure  
  91.             String result = updateALiPayOrderStatus(out_trade_no);  
  92.             System.out.println("验证成功,去更新状态 \t订单号:" + out_trade_no + "来自支付宝支付,更新结果:" + result);  
  93.             BaseResponse baseResponse = GsonUtils.getGson().fromJson(result, BaseResponse.class);  
  94.             if (null != baseResponse && baseResponse.isSucceeded) {  
  95.                 return ("success");  
  96.             } else {  
  97.                 return ("fail");// 更新状态失败  
  98.             }  
  99.         } else {  
  100.             // TODO 验签失败则记录异常日志,并在response中返回failure.  
  101.             System.out.println("验证失败,不去更新状态");  
  102.             return ("fail");  
  103.         }  
  104.     }  
  105. }  
给两个相关model

SignInfo:

[java]  view plain  copy
  1. public class SignInfo  
  2. {  
  3.     public BizContent Content;  
  4. }  

BizContent:

[java]  view plain  copy
  1. public class BizContent  
  2. {  
  3.     public String body = "";  
  4.     public String subject = "";  
  5.     public String out_trade_no = "";  
  6.     public String timeout_express = "";  
  7.     public String total_amount = "";  
  8.     public String seller_id = "";  
  9.     public String product_code = "";  
  10. }  

猜你喜欢

转载自blog.csdn.net/qq_40588579/article/details/80076908
今日推荐