javaweb online payment function implementation code

  • 2020-06-19 10:27:07
  • OfStack

This article shares the specific implementation code of javaweb online payment function for your reference. The specific content is as follows


package com.learning.web.servlet;

import java.io.IOException;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.learning.utils.PaymentUtil;

@WebServlet("/payOnline")
public class PayOnline extends HttpServlet {
  private static final long serialVersionUID = 1L;
    
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      doPost(request, response);
  }


  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  
    String orderid = request.getParameter("orderid");
    String money = request.getParameter("money");
    
        //  bank 
        String pd_FrpId = request.getParameter("pd_FrpId");

        //  What data is required to send to the payment company 
        String p0_Cmd = "Buy";
        String p1_MerId = ResourceBundle.getBundle("/WEB-INF/classes/merchantInfo").getString(
            "p1_MerId");
        String p2_Order = orderid;
        String p3_Amt = money;
        String p4_Cur = "CNY";
        String p5_Pid = "";
        String p6_Pcat = "";
        String p7_Pdesc = "";
        //  Payment successful callback address  ----  The first 3 The payment company will access, user access 
        //  The first 3 Party pay can visit the website ( Website of this project )
        String p8_Url = "http://115.170.37.189/day19pay/callback";
        String p9_SAF = "";
        String pa_MP = "";
        String pr_NeedResponse = "1";
        //  encryption hmac  Need a key 
        String keyValue = ResourceBundle.getBundle("merchantInfo").getString(
            "keyValue");
        String hmac = PaymentUtil.buildHmac(p0_Cmd, p1_MerId, p2_Order, p3_Amt,
            p4_Cur, p5_Pid, p6_Pcat, p7_Pdesc, p8_Url, p9_SAF, pa_MP,
            pd_FrpId, pr_NeedResponse, keyValue);
        //  generate url --- url?
        request.setAttribute("pd_FrpId", pd_FrpId);
        request.setAttribute("p0_Cmd", p0_Cmd);
        request.setAttribute("p1_MerId", p1_MerId);
        request.setAttribute("p2_Order", p2_Order);
        request.setAttribute("p3_Amt", p3_Amt);
        request.setAttribute("p4_Cur", p4_Cur);
        request.setAttribute("p5_Pid", p5_Pid);
        request.setAttribute("p6_Pcat", p6_Pcat);
        request.setAttribute("p7_Pdesc", p7_Pdesc);
        request.setAttribute("p8_Url", p8_Url);
        request.setAttribute("p9_SAF", p9_SAF);
        request.setAttribute("pa_MP", pa_MP);
        request.setAttribute("pr_NeedResponse", pr_NeedResponse);
        request.setAttribute("hmac", hmac);

        request.getRequestDispatcher("/confirm.jsp").forward(request, response);
    
    
  }

}

2. User confirmation of submitted information (ES8en.jsp)


<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>

<%@taglib prefix="p" uri="http://www.itcast.cn/tag"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
  <p:user />
  <!--  Confirm the payment form -->
  <form action="https://www.yeepay.com/app-merchant-proxy/node"
    method="get">
    <h3> The order no. : ${p2_Order}, The payment amount   : ${p3_Amt }</h3>
    <input type="hidden" name="pd_FrpId" value="${pd_FrpId }" /> <input
      type="hidden" name="p0_Cmd" value="${p0_Cmd }" /> <input
      type="hidden" name="p1_MerId" value="${p1_MerId }" /> <input
      type="hidden" name="p2_Order" value="${p2_Order }" /> <input
      type="hidden" name="p3_Amt" value="${p3_Amt }" /> <input
      type="hidden" name="p4_Cur" value="${p4_Cur }" /> <input
      type="hidden" name="p5_Pid" value="${p5_Pid }" /> <input
      type="hidden" name="p6_Pcat" value="${p6_Pcat }" /> <input
      type="hidden" name="p7_Pdesc" value="${p7_Pdesc }" /> <input
      type="hidden" name="p8_Url" value="${p8_Url }" /> <input
      type="hidden" name="p9_SAF" value="${p9_SAF }" /> <input
      type="hidden" name="pa_MP" value="${pa_MP }" /> <input type="hidden"
      name="pr_NeedResponse" value="${pr_NeedResponse }" /> <input
      type="hidden" name="hmac" value="${hmac }" /> <input type="submit"
      value=" Confirm the payment " />
  </form>
</body>
</html>

3. The Website receives information about payment from third Party


package com.learning.web.servlet;

import java.io.IOException;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.learning.service.OrderService;
import com.learning.utils.PaymentUtil;


/**
 *  the Servlet It will be after the payment is successful   The calling -----  To pay the company   , customers, 
 * 
 * @author seawind
 * 
 */
public class CallbackServlet extends HttpServlet {

  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    //  Get all the data for the callback 
    String p1_MerId = request.getParameter("p1_MerId");
    String r0_Cmd = request.getParameter("r0_Cmd");
    String r1_Code = request.getParameter("r1_Code");
    String r2_TrxId = request.getParameter("r2_TrxId");
    String r3_Amt = request.getParameter("r3_Amt");
    String r4_Cur = request.getParameter("r4_Cur");
    String r5_Pid = request.getParameter("r5_Pid");
    String r6_Order = request.getParameter("r6_Order");
    String r7_Uid = request.getParameter("r7_Uid");
    String r8_MP = request.getParameter("r8_MP");
    String r9_BType = request.getParameter("r9_BType");
    String rb_BankId = request.getParameter("rb_BankId");
    String ro_BankOrderId = request.getParameter("ro_BankOrderId");
    String rp_PayDate = request.getParameter("rp_PayDate");
    String rq_CardNo = request.getParameter("rq_CardNo");
    String ru_Trxtime = request.getParameter("ru_Trxtime");
    //  Identity check  ---  Determine whether to pay the company to notify you 
    String hmac = request.getParameter("hmac");
    String keyValue = ResourceBundle.getBundle("merchantInfo").getString(
        "keyValue");

    //  Encrypt the above data yourself  ---  Compare payment companies to send hamc
    boolean isValid = PaymentUtil.verifyCallback(hmac, p1_MerId, r0_Cmd,
        r1_Code, r2_TrxId, r3_Amt, r4_Cur, r5_Pid, r6_Order, r7_Uid,
        r8_MP, r9_BType, keyValue);
    if (isValid) {
      //  Response data valid 
      if (r9_BType.equals("1")) {
        //  Browser redirection 
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println("<h1> Payment successful! Waiting for the mall to enter 1 Step operation! Waiting for the goods ...</h1>");
      } else if (r9_BType.equals("2")) {
        //  Servers point to point  ---  The payment company notifies you 
        System.out.println(" Payment successful! ");
        //  Modify order status   For the payment 
        OrderService orderService=new OrderService();
        orderService.modifyOrderState(p1_MerId);
        
        //  Reply to payment Company 
        response.getWriter().print("success");
      }
    } else {
      //  The data is invalid 
      System.out.println(" Data has been tampered with! ");
    }
  }

  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }

}

File:

merchantInfo.properties

p1_MerId=10001126856
keyValue=69cl522AV6q613Ii4W6u8K6XuW8vM1N6bFgyv769220IuYe9u37N4y7rI4Pl
responseURL=http://localhost:8080/onlinepay/servlet/PaymentResponse

Tools class: PaymentUtil


package com.learning.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class PaymentUtil {

  private static String encodingCharset = "UTF-8";
  
  /**
   *  generate hmac methods 
   * 
   * @param p0_Cmd  Business types 
   * @param p1_MerId  Merchant code 
   * @param p2_Order  Merchant Order Number 
   * @param p3_Amt  Pay the amount 
   * @param p4_Cur  Trading currencies 
   * @param p5_Pid  Name of commodity 
   * @param p6_Pcat  items 
   * @param p7_Pdesc  Commodity description 
   * @param p8_Url  Address where the merchant receives payment success data 
   * @param p9_SAF  Shipping address 
   * @param pa_MP  Merchant Extension Information 
   * @param pd_FrpId  The bank code 
   * @param pr_NeedResponse  Response mechanism 
   * @param keyValue  Merchant key 
   * @return
   */
  public static String buildHmac(String p0_Cmd,String p1_MerId,
      String p2_Order, String p3_Amt, String p4_Cur,String p5_Pid, String p6_Pcat,
      String p7_Pdesc,String p8_Url, String p9_SAF,String pa_MP,String pd_FrpId,
      String pr_NeedResponse,String keyValue) {
    StringBuilder sValue = new StringBuilder();
    //  Business types 
    sValue.append(p0_Cmd);
    //  Merchant code 
    sValue.append(p1_MerId);
    //  Merchant Order Number 
    sValue.append(p2_Order);
    //  Pay the amount 
    sValue.append(p3_Amt);
    //  Trading currencies 
    sValue.append(p4_Cur);
    //  Name of commodity 
    sValue.append(p5_Pid);
    //  items 
    sValue.append(p6_Pcat);
    //  Commodity description 
    sValue.append(p7_Pdesc);
    //  Address where the merchant receives payment success data 
    sValue.append(p8_Url);
    //  Shipping address 
    sValue.append(p9_SAF);
    //  Merchant Extension Information 
    sValue.append(pa_MP);
    //  The bank code 
    sValue.append(pd_FrpId);
    //  Response mechanism 
    sValue.append(pr_NeedResponse);
    
    return PaymentUtil.hmacSign(sValue.toString(), keyValue);
  }
  
  /**
   *  Return to check hmac methods 
   * 
   * @param hmac  An encrypted verification code sent by the payment gateway 
   * @param p1_MerId  Merchant code 
   * @param r0_Cmd  Business types 
   * @param r1_Code  Pay for results 
   * @param r2_TrxId  Ebao payment transaction serial number 
   * @param r3_Amt  Pay the amount 
   * @param r4_Cur  Trading currencies 
   * @param r5_Pid  Name of commodity 
   * @param r6_Order  Merchant Order Number 
   * @param r7_Uid  Ebao pay members ID
   * @param r8_MP  Merchant Extension Information 
   * @param r9_BType  Transaction result return type 
   * @param keyValue  The key 
   * @return
   */
  public static boolean verifyCallback(String hmac, String p1_MerId,
      String r0_Cmd, String r1_Code, String r2_TrxId, String r3_Amt,
      String r4_Cur, String r5_Pid, String r6_Order, String r7_Uid,
      String r8_MP, String r9_BType, String keyValue) {
    StringBuilder sValue = new StringBuilder();
    //  Merchant code 
    sValue.append(p1_MerId);
    //  Business types 
    sValue.append(r0_Cmd);
    //  Pay for results 
    sValue.append(r1_Code);
    //  Ebao payment transaction serial number 
    sValue.append(r2_TrxId);
    //  Pay the amount 
    sValue.append(r3_Amt);
    //  Trading currencies 
    sValue.append(r4_Cur);
    //  Name of commodity 
    sValue.append(r5_Pid);
    //  Merchant Order Number 
    sValue.append(r6_Order);
    //  Ebao pay members ID
    sValue.append(r7_Uid);
    //  Merchant Extension Information 
    sValue.append(r8_MP);
    //  Transaction result return type 
    sValue.append(r9_BType);
    String sNewString = PaymentUtil.hmacSign(sValue.toString(), keyValue);
    return sNewString.equals(hmac);
  }
  
  /**
   * @param aValue
   * @param aKey
   * @return
   */
  public static String hmacSign(String aValue, String aKey) {
    byte k_ipad[] = new byte[64];
    byte k_opad[] = new byte[64];
    byte keyb[];
    byte value[];
    try {
      keyb = aKey.getBytes(encodingCharset);
      value = aValue.getBytes(encodingCharset);
    } catch (UnsupportedEncodingException e) {
      keyb = aKey.getBytes();
      value = aValue.getBytes();
    }

    Arrays.fill(k_ipad, keyb.length, 64, (byte) 54);
    Arrays.fill(k_opad, keyb.length, 64, (byte) 92);
    for (int i = 0; i < keyb.length; i++) {
      k_ipad[i] = (byte) (keyb[i] ^ 0x36);
      k_opad[i] = (byte) (keyb[i] ^ 0x5c);
    }

    MessageDigest md = null;
    try {
      md = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {

      return null;
    }
    md.update(k_ipad);
    md.update(value);
    byte dg[] = md.digest();
    md.reset();
    md.update(k_opad);
    md.update(dg, 0, 16);
    dg = md.digest();
    return toHex(dg);
  }

  public static String toHex(byte input[]) {
    if (input == null)
      return null;
    StringBuffer output = new StringBuffer(input.length * 2);
    for (int i = 0; i < input.length; i++) {
      int current = input[i] & 0xff;
      if (current < 16)
        output.append("0");
      output.append(Integer.toString(current, 16));
    }

    return output.toString();
  }

  /**
   * 
   * @param args
   * @param key
   * @return
   */
  public static String getHmac(String[] args, String key) {
    if (args == null || args.length == 0) {
      return (null);
    }
    StringBuffer str = new StringBuffer();
    for (int i = 0; i < args.length; i++) {
      str.append(args[i]);
    }
    return (hmacSign(str.toString(), key));
  }

  /**
   * @param aValue
   * @return
   */
  public static String digest(String aValue) {
    aValue = aValue.trim();
    byte value[];
    try {
      value = aValue.getBytes(encodingCharset);
    } catch (UnsupportedEncodingException e) {
      value = aValue.getBytes();
    }
    MessageDigest md = null;
    try {
      md = MessageDigest.getInstance("SHA");
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      return null;
    }
    return toHex(md.digest(value));

  }
  
//  public static void main(String[] args) {
//    System.out.println(hmacSign("AnnulCard1000043252120080620160450.0http://localhost/SZXpro/callback.asp Ma ?4564868265473632445648682654736324511","8UPp0KE8sq73zVP370vko7C39403rtK1YwX40Td6irH216036H27Eb12792t"));
//  }
}

Related articles: