alipay Alipay mobile payment

Mobile payment function is achieved through Alipay's API.

One: Download related dependencies and tools

Ant financial services https://open.alipay.com/platform/home.htm

Mobile payment development document https://docs.open.alipay.com/203/105285/

Download SDK jar file https://docs.open.alipay.com/54/103419/

Alipay interface parameter description https://docs.open.alipay.com/api_1/alipay.trade.wap.pay

Online payment instance download https://docs.open.alipay.com/54/106682/

Generating Alipay public key and private key https://gw.alipayobjects.com/os/rmsportal/PpisHyUkzJnZltrPyfuD.zip

II. Build development environment

(1): download the SDK dependency package and import it into the lib directory alipay-sdk-java-3.4.49.ALL.jar

(2): Download jar through Maven dependency

<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>3.4.49.ALL</version>
</dependency>

III. mobile payment - global configuration

package com.svse.util;
/**
* Mobile payment - global configuration class
* @author lenovo
*
*/
public class AlipayConfig {

  // Merchant appid
  public static final String APPID="";
  // Request gateway address
  public static final String URL="https://openapi.alipay.com/gateway.do";
  // Return format
  public static final String FORMAT="json";
  // Code
  public static final String CHARSET="UTF-8";
  // RSA2
  public static final String SIGNTYPE="RSA2";

  // The path of the asynchronous notification page of the server requires a complete path in the format of http: / / or https: / /. You can't add such custom parameters as? id=123. You must be able to access the page from an external network
  public static final String notify_url="http://Merchant gateway address / alipay.trade.wap.pay-java-utf-8/notify'url.jsp";

  // The page Jump synchronization notification page path needs a complete path in the format of http: / / or https: / /, and can't add such user-defined parameters as? id=123. The merchant can be accessed normally through the Internet and can customize the synchronization jump address
  public static final String return_url="http://Merchant gateway address / alipay.trade.wap.pay-java-utf-8 / return ﹐ url.jsp";
  // Generate Alipay public key through RSA signature verification tool
  public static final String ALIPAY_PUBLIC_KEY="";
  // Generated by RSA signature verification tool, PKCS8 format private key
  public static final String RSA_PRIVATE_KEY="";

}

IV. write relevant business interface codes

1: Alipay online payment interface

@RequestMapping("payment")
public void payment(HttpServletRequest request,HttpServletResponse response) throws IOException{

  if(request.getParameter("WIDout_trade_no")!=null||request.getParameter("WIDtrade_no")!=null){
    //Merchant order number
    String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
    // Order name, required
    String subject = new String(request.getParameter("WIDsubject").getBytes("ISO-8859-1"),"UTF-8");
    System.out.println(subject);
    // Payment amount, required
    String total_amount=new String(request.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"),"UTF-8");
    // Product description, can be blank
    String body = new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"),"UTF-8");
    // Timeout can be empty
    String timeout_express="2m";
    // Sales product code is required
    String product_code="QUICK_WAP_WAY";
    /**********************/
    // SDK public request class contains public request parameters and encapsulates signature and signature verification. Developers do not need to pay attention to signature and signature verification
    //Call RSA signature method
    AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY,
               AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);

    AlipayTradeWapPayRequest alipay_request=new AlipayTradeWapPayRequest();

    // Package request payment information
    AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
    model.setOutTradeNo(out_trade_no);
    model.setSubject(subject);
    model.setTotalAmount(total_amount);
    model.setBody(body);
    model.setTimeoutExpress(timeout_express);
    model.setProductCode(product_code);
    alipay_request.setBizModel(model);
    // Set asynchronous notification address
    alipay_request.setNotifyUrl(AlipayConfig.notify_url);
    // Set synchronization address
    alipay_request.setReturnUrl(AlipayConfig.return_url);

    // Form form production
    String form = "";
    try {
      // Call SDK to generate form
      form = client.pageExecute(alipay_request).getBody();
      response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
      response.getWriter().write(form);//Directly output the complete form html to the page
      response.getWriter().flush();
      response.getWriter().close();
    } catch (AlipayApiException e) {
      e.printStackTrace();
    }

    }else{
      System.out.println("Problem with order,Failure to pay");
   }
}

 

2: Alipay online generated order interface

@RequestMapping("generateOrder")
public void generateOrder(HttpServletRequest request11,HttpServletResponse response11) throws UnsupportedEncodingException{
  if(request11.getParameter("WIDout_trade_no")!=null||request11.getParameter("WIDtrade_no")!=null){
  //Merchant order number
  String out_trade_no = new String(request11.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
  //Instantiate client
  AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY,
                 AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
  //Instantiate specific API corresponding to request class, class name and interface name corresponding, the current call interface name: alipay.trade.app.pay
  AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
  //The SDK has encapsulated the public parameters. Only the business parameters need to be passed in here. The following method is the model input method of the SDK (biz [content] is used when the model and biz [content] exist at the same time).
  AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
  model.setBody("I'm the test data");
  model.setSubject("App Payment test Java");
  model.setOutTradeNo(out_trade_no);
  model.setTimeoutExpress("30m");
  model.setTotalAmount("0.01");
  model.setProductCode("QUICK_MSECURITY_PAY");
  request.setBizModel(model);
  request.setNotifyUrl("Asynchronous address that can be accessed by merchant's extranet");
  try {
    //This is different from the normal interface call. SDK execute is used
    AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
    System.out.println(response.getBody());//That is, orderString can directly request to the client without further processing.
  } catch (AlipayApiException e) {
    e.printStackTrace();
  }
 }
}

3: Alipay online order inquiry interface

@RequestMapping("searchOrder")
public void searchOrder(HttpServletRequest request,HttpServletResponse response){
  if(request.getParameter("WIDout_trade_no")!=null||request.getParameter("WIDtrade_no")!=null){
  try {
    //Merchant order number, the only order number in the order system of merchant website, required
    String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
    //Alipay transaction number
    String trade_no = new String(request.getParameter("WIDtrade_no").getBytes("ISO-8859-1"),"UTF-8");
    /**********************/
    // SDK public request class contains public request parameters and encapsulates signature and signature verification. Developers do not need to pay attention to signature and signature verification
    AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY,
           AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);
    AlipayTradeQueryRequest alipay_request = new AlipayTradeQueryRequest();

    AlipayTradeQueryModel model=new AlipayTradeQueryModel();
    model.setOutTradeNo(out_trade_no);
    model.setTradeNo(trade_no);
    alipay_request.setBizModel(model);

    AlipayTradeQueryResponse alipay_response;
      try {
        alipay_response = client.execute(alipay_request);
        System.out.println(alipay_response.getBody());
      } catch (AlipayApiException e) {
        e.printStackTrace();
      }

   } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
   }
  }
}

4: Alipay online order refund interface

@RequestMapping("orderRefund")
public void orderRefund(HttpServletRequest request,HttpServletResponse response){
  if(request.getParameter("WIDout_trade_no")!=null||request.getParameter("WIDtrade_no")!=null){
    //Merchant order number and Alipay transaction number can not be empty at the same time. Trade no, out trade no if there is a priority trade no at the same time
    //Merchant order number and Alipay transaction number two are selected.
    String out_trade_no;
    try {
       out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
       //Alipay transaction number and merchant Order No. two are selected.
      String trade_no = new String(request.getParameter("WIDtrade_no").getBytes("ISO-8859-1"),"UTF-8");
      //Refund amount cannot be greater than the total order amount
      String refund_amount=new String(request.getParameter("WIDrefund_amount").getBytes("ISO-8859-1"),"UTF-8");
      //Reason for refund
      String refund_reason=new String(request.getParameter("WIDrefund_reason").getBytes("ISO-8859-1"),"UTF-8");
      //Identify a refund request. Multiple refunds of the same transaction need to be unique. If partial refund is required, this parameter must be passed.
      String out_request_no=new String(request.getParameter("WIDout_request_no").getBytes("ISO-8859-1"),"UTF-8");
      /**********************/
      // SDK public request class contains public request parameters and encapsulates signature and signature verification. Developers do not need to pay attention to signature and signature verification
      AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY,
               AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);
      AlipayTradeRefundRequest alipay_request = new AlipayTradeRefundRequest();
      AlipayTradeRefundModel model=new AlipayTradeRefundModel();
      model.setOutTradeNo(out_trade_no);
      model.setTradeNo(trade_no);
      model.setRefundAmount(refund_amount);
      model.setRefundReason(refund_reason);
      model.setOutRequestNo(out_request_no);
      alipay_request.setBizModel(model);

      AlipayTradeRefundResponse alipay_response;
        try {
           alipay_response = client.execute(alipay_request);
          System.out.println(alipay_response.getBody());
        } catch (AlipayApiException e) {
          e.printStackTrace();
        }

     } catch (UnsupportedEncodingException e1) {
          e1.printStackTrace();
     }
   }

}

5: order refund query interface

@RequestMapping("searchOrderRefund")
public void searchOrderRefund(HttpServletRequest request,HttpServletResponse response){
  if(request.getParameter("WIDout_trade_no")!=null||request.getParameter("WIDtrade_no")!=null && request.getParameter("WIDout_request_no")!=null){
      try {
          //Merchant order number and Alipay transaction number can not be empty at the same time. Trade no, out trade no if there is a priority trade no at the same time
         //Merchant order number and Alipay transaction number two are selected.
         String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
         //Alipay transaction number and merchant Order No. two are selected.
       String trade_no = new String(request.getParameter("WIDtrade_no").getBytes("ISO-8859-1"),"UTF-8");
       //When requesting the refund interface, the incoming refund request number. If it is not passed in at the time of refund request, the value is the external transaction number at the time of transaction creation
       String out_request_no = new String(request.getParameter("WIDout_request_no").getBytes("ISO-8859-1"),"UTF-8");
       /**********************/
       // SDK public request class contains public request parameters and encapsulates signature and signature verification. Developers do not need to pay attention to signature and signature verification
       AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY,
                  AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);
       AlipayTradeFastpayRefundQueryRequest alipay_request = new AlipayTradeFastpayRefundQueryRequest();

       AlipayTradeFastpayRefundQueryModel model=new AlipayTradeFastpayRefundQueryModel();
       model.setOutTradeNo(out_trade_no);
       model.setTradeNo(trade_no);
       model.setOutRequestNo(out_request_no);
       alipay_request.setBizModel(model);

       AlipayTradeFastpayRefundQueryResponse alipay_response=client.execute(alipay_request);
       System.out.println(alipay_response.getBody());

    } catch (Exception e) {
       e.printStackTrace();
   }
  }

}

6: Bill Download Interface

@RequestMapping("downloadBill")
public void downloadBill(HttpServletRequest request,HttpServletResponse response){
   if(request.getParameter("WIDbill_type")!=null&&request.getParameter("WIDbill_date")!=null){
   try {
    // Bill type: the merchant can obtain the following bill types through the interface or after the merchant is authorized by the open platform: trade, signcustomer;
    // trade refers to a business account receipts based on Alipay transactions; signcustomer refers to account receipts based on changes in the fund's Alipay balance income and expenditure.
    String bill_type = new String(request.getParameter("WIDbill_type").getBytes("ISO-8859-1"),"UTF-8");
    // Billing time: the format of daily bill is yyyy-MM-dd, and the format of monthly bill is yyyy-MM.
    String bill_date = new String(request.getParameter("WIDbill_date").getBytes("ISO-8859-1"),"UTF-8");
    /**********************/
    // SDK public request class contains public request parameters and encapsulates signature and signature verification. Developers do not need to pay attention to signature and signature verification
    AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY,
    AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);
    AlipayDataDataserviceBillDownloadurlQueryRequest alipay_request = new AlipayDataDataserviceBillDownloadurlQueryRequest();

    AlipayDataDataserviceBillDownloadurlQueryModel model =new AlipayDataDataserviceBillDownloadurlQueryModel();
    model.setBillType(bill_type);
    model.setBillDate(bill_date);
    alipay_request.setBizModel(model);

    AlipayDataDataserviceBillDownloadurlQueryResponse alipay_response = client.execute(alipay_request);
    System.out.println(alipay_response.getBillDownloadUrl());

   } catch (Exception e) {
    e.printStackTrace();

   }
  }
}

7: asynchronous notification message interface

@RequestMapping("notifyUrl")
@ResponseBody
public String notify(HttpServletRequest request){
  int im=0;
  im++;
  //Number of test requests
  System.out.println("frequency:"+im);
  //Get feedback from Alipay 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] + ",";
       }
    //Garbled code solution, this code is used when there is garbled code.
    //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
    params.put(name, valueStr);
  }
  //Get Alipay's notification return parameters, refer to the technical document page Jump synchronization notification parameter list (the following is for reference only) / /
  //Merchant order number
  String out_trade_no = request.getParameter("out_trade_no");
  //Alipay transaction number
  String trade_no = request.getParameter("trade_no");

  //Trading status
  String trade_status = request.getParameter("trade_status");
  System.out.println(trade_status);
  try {
    boolean verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, "utf-8", "RSA2");
    if(verify_result){
      //Verify success
      //Please add the business logic code of the merchant here
      System.out.println("returnUrl_params:Verify success");
      //——Please write the program according to your business logic (the following code is for reference only)——
      boolean flag = false;
      if(trade_status.equals("TRADE_FINISHED")){
        System.out.println("returnUrl_params:End of transaction");
        //Transaction closed, non refundable

        //Be careful:
        //When the refund date exceeds the refundable period (such as three months' refundable), Alipay sends the status notification.
      }else if (trade_status.equals("TRADE_SUCCESS")){
        //Transaction payment succeeded

        //Be careful:
        //After payment is completed, the Alipay system sends the transaction status notification.

        //According to the order number, the order status and the state in the Alipay record table are changed to be paid.
        System.out.println("returnUrl_params:Transaction payment succeeded");
        flag = true;
        //——Please write the program according to your business logic (the above code is for reference only)——

        if(flag){
          return "success";
        }else{
          return "fail";
        }
      }
    }else{
      //Validation failed
      System.out.println("Transaction failure");
      return "fail";
    }
  } catch (Exception e) {
    e.printStackTrace();
    return "500";
  }
  return null;
}

8: synchronization notification message interface

@RequestMapping("/returnUrl")
public ModelAndView result(HttpServletRequest request) {
   System.out.println("come in");
  //Data rendering with ModelAndView
  ModelAndView mv = new ModelAndView("alipay/return_url");
  //Get feedback from Alipay GET
  Map<String,String> params = new HashMap<String,String>();
  Map<String, String[]> requestParams = request.getParameterMap();
  for(String str:requestParams.keySet()){
    String[] values=requestParams.get(str);
    String valueStr="";
    for (int i = 0; i < values.length; i++) {
      valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
    }
    //Garbled code solution, this code is used when there is garbled code. You can also use this code conversion if mysign and sign are not equal
    //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
    params.put(str, valueStr);
   }
  //Transaction order No
  String out_trade_no = request.getParameter("out_trade_no");
  //Transaction amount
  String total_amount = request.getParameter("total_amount");
  //Alipay trading account
  //String trade_no = request.getParameter("trade_no");
  //Order creation time
  String timestamp = request.getParameter("timestamp");
  mv.addObject("out_trade_no", out_trade_no);
  mv.addObject("total_amount", total_amount);
  mv.addObject("timestamp", timestamp);
  //Print all response data
  System.out.println("returnUrl_params:"+params);
  try {
    //Remember that AlipayConfig.ALIPAY_PUBLIC_KEY is the public key of Alipay, please go to the open.alipay.com corresponding application..
    boolean verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, "utf-8", "RSA2");
    if(verify_result){
      //The verification is successful. This is a fake code
      //The system processes data based on Alipay callback to change order status or other associated tables.
      //Order order =orderService.queryOrderByNumber(out_trade_no);

      /* if(order !=null){
        //order Not for null
      mv.addObject("verify_result", verify_result);
      mv.addObject("msg", "Merchant order number does not exist ');
      } */
      return mv;
    }else{
      //Verification failure skip failure page
      System.out.println("Validation failed");
      return null;
    }

  } catch (Exception e) {
    e.printStackTrace();
    //Abnormal jump failure page
    return null;
  }
}

Tags: Java SDK Mobile JSP

Posted on Mon, 02 Dec 2019 18:03:23 -0800 by Gump