为了账号安全,请及时绑定邮箱和手机立即绑定

Java 支付宝之APP支付服务端 (一)

标签:
Java
Java 支付宝之APP支付服务端 (二)

Entrance 支付宝的API文档
在上一篇中,集成第三方支付的流程:下单,异步通知,查询,还涉及到提现,退款,关闭订单等,我们以后在介绍。目前先介绍前三个。

图片描述图片描述图片描述

一、支付宝统一下单请求交易

/**
       * 支付宝请求交易
       *
       * @param bean
       * @return
       */
      @RequestMapping(value=Route.Payment.ALI_PAY,method=RequestMethod.POST)
      @ResponseBody
      public Response pay(@PathVariable("userId") int userId,@PathVariable("amount") String amount) {
            log.info("infoMsg:--- 支付宝请求交易开始");
            Response resp = this.getReponse();
            try {
                  //----------------请求参数------------------//
                  ThirdPayBean payBean = thirdPayService.findByPayId(18);
                  Assert.notNull(payBean);
                  String notify_url = payBean.getReturn_url();
                  String APP_ID = payBean.getMer_no();      //支付宝商戶号
                  String mer_key = payBean.getMer_key();    //支付宝公钥|商户私钥
                  String public_key = mer_key.split("|")[0];
                  String private_key = mer_key.split("|")[1];
                  String ALIPAY_PUBLIC_KEY = MD5_UTIL.convertMD5(MD5_UTIL.convertMD5(public_key));
                  String APP_PRIVATE_KEY = MD5_UTIL.convertMD5(MD5_UTIL.convertMD5(private_key));
                  String passbackParams = userId + "|" + "18";    //拓展参数

                  //实例化客户端
                  AlipayClient alipayClient = new DefaultAlipayClient(alipay_Url, APP_ID, APP_PRIVATE_KEY, "JSON", "UTF-8", ALIPAY_PUBLIC_KEY, "RSA2");
                  //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称:alipay.trade.app.pay
                  AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
                  //SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
                  AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
                  model.setSubject("循心科技");
                  model.setOutTradeNo(OrderGeneratedUtils.getOrderNo());
                  model.setTimeoutExpress("30m");
                  model.setTotalAmount(amount);
                  model.setProductCode("QUICK_MSECURITY_PAY");
                  model.setPassbackParams(passbackParams);
                  request.setBizModel(model);
                  request.setNotifyUrl(notify_url);
              //这里和普通的接口调用不同,使用的是sdkExecute
              AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
//            System.out.println(response.getBody());//就是orderString 可以直接给客户端请求,无需再做处理。
              //生成账单
              boolean result = rechargeRecordService.generatedBills(response.getBody(),passbackParams);
              if(!result) {
                  log.error("订单生成失败");
              }
              log.info("infoMsg:--- 支付宝请求交易结束");
              return resp.success(response.getBody());
          } catch (AlipayApiException e) {
            log.error("errorMsg:--- 支付宝请求交易失败" + e.getMessage());
            return resp.failure(e.getMessage());
            }
      }

二、支付宝支付通知地址

/**
       * 支付宝支付通知地址
       *
       * @param request
       * @return
       */
      @RequestMapping(value=Route.Payment.ALI_PAY_NOTIFY,method=RequestMethod.POST)
      @ResponseBody
      public Response alipay_notify(HttpServletRequest request) {
            log.info("infoMsg:--- 支付宝验证异步通知信息开始");
            Response resp = this.getReponse();
            try {
            //----------------请求参数------------------//
                  ThirdPayBean payBean = thirdPayService.findByPayId(18);
                  Assert.notNull(payBean);
                  String mer_key = payBean.getMer_key();    //支付宝公钥|商户私钥
                  String public_key = mer_key.split("|")[0];
                  String ALIPAY_PUBLIC_KEY = MD5_UTIL.convertMD5(MD5_UTIL.convertMD5(public_key));

                  //获取支付宝POST过来反馈信息
                  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] + ",";
                        }
                      //乱码解决,这段代码在出现乱码时使用。
                        //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                        params.put(name, valueStr);
                  }
            //切记alipaypublickey是支付宝的公钥,请去open.alipay.com对应应用下查看。
            //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
                  boolean flag = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, "utf-8","RSA2");
                  if(flag) {
                        //TODO 账变,修改状态,到账提醒
                        Double amount = Double.parseDouble(params.get("amount"));
                        String passbackParams = params.get("passbackParams");
                        String order_no = params.get("out_trade_no");
                        boolean result = rechargeRecordService.updateBill(amount,passbackParams,order_no);
                        if(result) {
                              System.out.println("订单更新成功");
                        }
                  }
                  log.info("infoMsg:--- 支付宝验证异步通知信息结束");
                  return resp.success();
            } catch (AlipayApiException e) {
                  log.info("infoMsg:--- 支付宝验证异步通知信息结束" + e.getMessage());
                  return resp.failure(e.getMessage());
            }
      }

三、支付宝单笔提现

/**
       * 支付宝单笔提现
       *
       * @param userId
       * @param amount
       * @return
       */
      @RequestMapping(value=Router.Payment.ALI_PAY_TRANSFER,method=RequestMethod.POST)
      @ResponseBody
      public Response alipay_transfer(@PathVariable("userId") int userId,@PathVariable("amount") String amount) {
            String message = "";
            log.info("infoMsg:--- 支付宝提现开始");
            Response resp = this.getReponse();
            try {
                  //----------------请求参数------------------//
                  ThirdPayBean payBean = thirdPayService.findByPayId(18);
                  Assert.notNull(payBean);
                  String APP_ID = payBean.getMer_no();      //支付宝商戶号
                  String mer_key = payBean.getMer_key();    //支付宝公钥|商户私钥
                  String public_key = mer_key.split("|")[0];
                  String private_key = mer_key.split("|")[1];
                  String ALIPAY_PUBLIC_KEY = MD5_UTIL.convertMD5(MD5_UTIL.convertMD5(public_key));
                  String APP_PRIVATE_KEY = MD5_UTIL.convertMD5(MD5_UTIL.convertMD5(private_key));
                  String passbackParams = userId + "|" + "18";    //拓展参数
                  String orderNo = OrderGeneratedUtils.getOrderNo();

                  AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do";,APP_ID,APP_PRIVATE_KEY,"JSON","utf-8",ALIPAY_PUBLIC_KEY,"RSA2");
                  AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
                  AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
                  //转账参数拼装 TODO
                  model.setSubject("循心科技");
                  model.setOutTradeNo(orderNo);
                  model.setTimeoutExpress("30m");
                  model.setProductCode("QUICK_MSECURITY_PAY");
                  request.setBizModel(model);
                  AlipayFundTransToaccountTransferResponse response = alipayClient.execute(request);
                  String body = response.getBody();
                  //解析返回值
                  message = rechargeRecordService.createTransfer(body,passbackParams);
                  if(message.equalsIgnoreCase("Success")) {
                        boolean result = transferRecordService.saveTransRecord(body,amount,passbackParams);
                        if(result) {
                              log.info("infoMsg:--- 支付宝提现成功");
                        }
                  }else {
                        log.error("errorMsg:--- 支付宝提现失败" + message);
                  }
                  log.info("infoMsg:--- 支付宝提现结束");
                  return resp.success();
            } catch (AlipayApiException e) {
                  log.error("errorMsg:--- 支付宝提现失败" + e.getMessage());
                  return resp.failure(message + e.getMessage());
            }
      }

四、支付宝订单查询

/**
       * 支付宝支付订单查询
       *
       * @param request
       * @return
       */
      @RequestMapping(value=Route.Payment.ALI_PAY_QUERY,method=RequestMethod.POST)
      @ResponseBody
      public Response alipay_query(HttpServletRequest req) {
            log.info("infoMsg:--- 支付宝订单查询开始");
            Response resp = this.getReponse();
            try {
                  AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do";,"app_id","your private_key","json","GBK","alipay_public_key","RSA2");
                  AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
                  request.setBizContent("{" +
                  "\"out_trade_no\":\"20150320010101001\"," +
                  "\"trade_no\":\"2014112611001004680 073956707\"" +
                  "  }");
                  AlipayTradeQueryResponse response;
                        response = alipayClient.execute(request);
                        if(response.isSuccess()){
                              System.out.println("调用成功");
                        } else {
                              System.out.println("调用失败");
                        }
                        log.info("infoMsg:--- 支付宝订单查询结束");
                        return resp.success();
                  } catch (AlipayApiException e) {
                        log.error("errorMsg:--- 支付宝订单查询失败");
                        return resp.failure(e.getMessage());
                  }
      }

ps: 总结,作为IT巨头,支付宝的文档总结得是很给力的。在开放平台下载相关jar宝 友情链接

点击查看更多内容
6人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
JAVA开发工程师
手记
粉丝
7112
获赞与收藏
545

关注作者,订阅最新文章

阅读免费教程

感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消