Javaweb realize online payment function _java

Source: Internet
Author: User
Tags hmac md5 stringbuffer

1, Online Payment overview

What is online payment? Yes, just spending money on the internet! We must have had this experience. But you may not be familiar with the "insider" of online payments, so let's take a look at it!

If you start operating an E-commerce site now, users must pay to buy something, your site must be able to connect the major banks, and then after the major banks to pay the completion, and then return to your site to show "pay success"!

That's what we're going to do today, connecting the bank's net banking system to complete payment. Speaking professionally, we call it "developing online payment gateways"

2, two ways to pay online

A total of two ways to pay online:

* Direct connection with the bank by the electric dealer
* The electricity trader through the third party payment platform and the bank docking

The electric dealer directly with the bank docking, this also wants the bank to agree only then, but unfortunately, the bank is very "ox", is not who wants with it to butt all can. If your dealer's daily cash flow is large enough, then the bank will dock with you, because the customer pays the electricity dealer's money to deposit in the bank's account! But if the money flow is small, the bank will not be able to ignore you!

When small Web sites do not have enough money to dock with banks, they will choose to work with third-party payment companies. We all know what it is. Companies, such as: Alipay, Yeepay, wealth Qualcomm, fast money and other companies are more famous in China. These companies can dock with the banks (because they have enough money), and then the small electric dealers dock with them! But a third party is asking for a fee! Third parties will generally charge 1% of the cost of electricity, but will not accept the customer's money.

Through the above figure you can understand that on the bank's page will show the mall name, RMB order number, order time ... , these things how the bank knows, of course, the electricity dealer to the bank. When the electricity trader and the bank docking, the electric dealer will give the bank the page to pass the Bank page to need the parameter, therefore the bank's page can display this data!

However, our mall can not only butt a bank bar! How to docking BOC, CCB, ABC, ICBC four! The docking parameters required by different banks are not the same, which means that we have to write different docking codes for different banks at the time of development. This is also a direct connection with the bank's shortcomings! Of course, with the bank direct docking also has the advantage, is safe, no handling fees!

Develop different codes (disadvantages) for different banks;
Safety (advantages);
No handling fees (advantages);
The small electricity merchant bank does not let the docking (disadvantage).

As indicated above, the customer clicks on the confirmation payment on the electric Dealer's website, directs to the third party's website, then the third party and the bank docking. This means that the electrical business to pass to the third party parameters! Then the third party passes the parameter to the bank. The advantage of this approach is that it only needs to be developed for third parties, without having to provide parameters for each bank. The job of providing parameters for each bank is a third party task. However, the third party is not old and reliable, if the third party closed down, the person ran, then your money is gone. Because the customer pays the money not to your bank account, but is paid to the third party's bank account, and you have an account in the third party. And the third party also charge fees, is generally 1%, this is not a small number ah (really black).

3, through the third party online payment rules

The electric dealer wants to register the merchant in the third party, need to provide the ICP Attestation to the third party. ICP operating license is according to the state "Internet management Regulations", operating website must be handled by the website business license, is not an illegal operation.

We can't go through icp! because of practice. Therefore we cannot register the merchant in the third party. However, we already have ready-made in the easy to register the merchant, so this step can be ignored.

When you successfully registered in the Easy treasure, Yi Bao will give you the following things:

Account number in Yeepay (ie Merchant code): 10001126856
Yeepay Access specification: a CHM file
Symmetric encryption Algorithm class: Paymentutil.java
Key: 69CL522AV6Q613II4W6U8K6XUW8VM1N6BFGYV769220IUYE9U37N4Y7RI4PL
In the easy to access the specification, we can find Yeepay payment gateway, in fact, is a URL, used with the easy to dock a URL: Https://www.yeepay.com/app-merchant-proxy/node

In the easy to access specification, you can also find Yeepay requirements of the parameters, in the electrical quotient and easy docking when the payment gateway to pass these parameters:

Official Request Address: Https://www.yeepay.com/app-merchant-proxy/node

These parameters need to be appended to the URL.

Note, however, that the values of these parameters need to be encrypted. Encryption key and encryption algorithm Yeepay will provide!

Where P8_url says that when the payment is successful, return to which page of the electrical quotient. This means that we need to write a page that shows the results. The third party will redirect to our designated return page after the payment succeeds, and will also bring us some parameters that our page needs to get these parameters to display on the page. The following are the parameters returned by the third party:

4. Developing the third party online payment system

Steps:

index.jsp page: a form, submitted to buyservlet, table items are: Order number, payment amount, select Bank
buyservlet: get form data and prepare to connect to a third party gateway. Because only 3 parameters are given in the Index.jsp page, and the third party needs more than n parameters, the page does not give the parameters to be supplemented by buyservlet. And the parameters also need to be encrypted, which also needs to be done in the Buyservlet
Backservlet: When the user pays successfully, the third party will redirect to our designated return page, we use Backservlet as the return page, it is used to receive the parameters passed by the third party, displayed in the page

Because we already have a registered firm in Yeepay, we don't have to register ourselves. So here you use Yeepay as a Third-party payment platform to test. Because I do not have the electric dealer (must pass the ICP Certified Electricity dealer), therefore also cannot register the firm in the third party.

We are now using the barter business is provided by the Chuan-chi podcast, Baba Sports Network registered in the trade firm. So the money paid during the test was given to the Pakistani sports net in the name of the registered firm.

First step: index.jsp

<form action= "" method= "POST" >
 order Number: <input type= "text" name= "P2_order"/><br/>
 amount:< Input type= "text" name= "P3_amt"/><br/> Select Bank:<br/> <input type= "Radio" name= "Pd_frpid"
 Value= "ICBC-NET-B2C"/> ICBC
  <input type= "Radio"
 Name= "Pd_frpid" value= "BOC-NET-B2C"/> Bank of China <br/><
 br/>
 <input type= "Radio" name= "Pd_frpid" value= "abc-net-b2c"/> Agricultural Bank  <input type= "Radio" name= "Pd_frpid" value= "ccb-net-b2c"/> "
 Construction Bank <br/><br/> <input type=" Radio "name=" Pd_frpid "value="
 BOCO-NET-B2C "/> Bank of communications
 <br/> <input" type= "
 Submit "value=" Confirmation payment/>
</form>

Each bank corresponds to the value:

Step Two: Buyservlet.java

public class Buyservlet extends HttpServlet {public void DoPost (HttpServletRequest request, HttpServletResponse respons
  E) throws Servletexception, IOException {request.setcharacterencoding ("utf-8");

  Response.setcontenttype ("Text/html;charset=utf-8"); String p0_cmd = "buy";//business type, fixed value is bought, that is, "buying" String P1_merid = "10001126856";//in P2_order registered firm String = REQUEST.GETPA Rameter ("P2_order");//order number String P3_amt = Request.getparameter ("P3_amt");//payment of amount string p4_cur = "CNY";//transaction seed currency, fixed value CNY, indicating that the RMB string p5_pid = "";//commodity name string P6_pcat = ""//commodity various types string p7_pdesc = ""//Product description string P8_url = "Htt P://localhost:8080/buy/backservlet "//The return page of the electrical quotient, when payment succeeds, Yi Bao will redirect to this page string p9_saf =" ";//shipping address string pa_mp =" ";//Product extension Information String pd_frpid = Request.getparameter ("Pd_frpid");//payment channel, that is, select Bank String pr_needresponse = "1";//answer mechanism, fixed value 1//Secret
  The key, provided by the PO, only merchant and Yeepay know this key.

  String keyvalue = "69CL522AV6Q613II4W6U8K6XUW8VM1N6BFGYV769220IUYE9U37N4Y7RI4PL"; Through the above parameters, keys, plusCryptographic algorithms, the order in which the HMAC value//parameter is generated is required, and if no value is given, NULL is given, but an empty string should be presented. 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);
  Connect all parameters to the gateway address String URL = "Https://www.yeepay.com/app-merchant-proxy/node"; url = "? p0_cmd=" + P0_cmd + "&p1_merid=" + P1_merid + "&p2_order=" + P2_order + "&p3_amt=" + P3 _amt + "&p4_cur=" + p4_cur + "&p5_pid=" + p5_pid + "&p6_pcat=" + p6_pcat + "&p7_pdesc=" "+ P7_pdesc +" &p8_url= "+ P8_url +" &p9_saf= "+ P9_saf +" &pa_mp= "+ pa_mp +" &pd_fr
  Pid= "+ pd_frpid +" &pr_needresponse= "+ pr_needresponse +" &hmac= "+ HMAC;
  System.out.println (URL);
 Redirect to Gateway Response.sendredirect (URL);

 }
}

Step three: backservlet

 public class Backservlet extends HttpServlet {public void doget (HttpServletRequest req Uest, HttpServletResponse response) throws Servletexception, IOException {response.setcontenttype ("Text/html;charset
  =utf-8 ");
   * * * Yi Bao will provide a series of result parameters, we get what they need to * obtain payment results: r1_code,1 to pay success.
   * Get Payment Amount: R3_amt * Obtain the order number of the dealer: R6_order * Get the result return type: r9_btype,1 for redirect return, 2 for point-to-point return, * but we can't get the point-to-point, because our IP is LAN IP.
  */String R1_code = Request.getparameter ("R1_code");
  String R3_amt = Request.getparameter ("R3_amt");
  String R6_order = Request.getparameter ("R6_order");

  String R9_btype = Request.getparameter ("R9_btype"); if (R1_code.equals ("1")) {if (R9_btype.equals ("1")) {Response.getwriter (). Print (" 
 

Yeepay payment provided by the tool class to obtain HMAC

public class Paymentutil {private static String Encodingcharset = "UTF-8";  /** * Generate HMAC method * * @param p0_cmd Business type * @param p1_merid merchant number * @param p2_order merchant Order number * @param p3_amt Payment amount * @param p4_cur Trading Currency * @param p5_pid commodity name * @param p6_pcat Commodity Description * @param p7_pdesc Product Descriptions * @param p8_url Merchants receive payment of successful data Site * @param p9_saf Shipping Address * @param pa_mp merchant Extension Information * @param pd_frpid Bank Code * @param pr_needresponse Response mechanism * @param Keyva Lue 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_frpi
  D, String pr_needresponse,string keyvalue) {StringBuilder svalue = new StringBuilder ();
  Business Type svalue.append (P0_cmd);
  Merchant number Svalue.append (P1_merid);
  Merchant Order number Svalue.append (P2_order);
  Payment amount Svalue.append (P3_amt);
  Transaction currency Svalue.append (p4_cur);
Commodity name Svalue.append (P5_PID);  Commodity type svalue.append (P6_PCAT);
  Product Description Svalue.append (P7_PDESC);
  The merchant receives the address Svalue.append (P8_url) to pay the successful data;
  Shipping Address svalue.append (P9_SAF);
  Merchant Extended Information Svalue.append (PA_MP);
  Bank Code Svalue.append (PD_FRPID);

  Response mechanism Svalue.append (pr_needresponse);
 Return Paymentutil.hmacsign (Svalue.tostring (), keyvalue); /** * Returns the Verify HMAC method * * @param the Cryptographic authentication code sent from the HMAC payment gateway * @param p1_merid Merchant number * @param r0_cmd Business type * @param r1_cod E Payment result * @param r2_trxid yeepay Payment Transaction serial number * @param r3_amt payment amount * @param r4_cur transaction currency * @param r5_pid commodity name * @param r6_or Der Merchant Order Number * @param r7_uid yeepay payment Member ID * @param R8_MP merchant Extension information * @param r9_btype Transaction result return type * @param keyvalue key * @retu RN/public static Boolean Verifycallback (String HMAC, String P1_merid, String r0_cmd, String R1_code, String r2_tr XId, String R3_amt, String r4_cur, String r5_pid, String R6_order, String r7_uid, String r8_mp, String r9_btype, Str ing keyvalue) {StringBuilder svalue = new StringBuilder ();
  Merchant number Svalue.append (P1_merid);
  Business Type svalue.append (R0_cmd);
  Payment Results Svalue.append (R1_code);
  Yeepay Payment Transaction serial number Svalue.append (R2_TRXID);
  Payment amount Svalue.append (R3_amt);
  Transaction currency Svalue.append (r4_cur);
  Commodity name Svalue.append (R5_PID);
  Merchant Order number Svalue.append (R6_order);
  Yeepay Payment Member ID svalue.append (R7_UID);
  Merchant Extended 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, $, (byte) 54); Arrays.filL (K_opad, Keyb.length,, (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 <) 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 "));

 // }
}

Yeepay Callback

Point-to-Point: Yeepay Direct access to the electrical business, there is no client what happened

This way is necessary to use, we do not receive this way! Because we don't have a fixed IP
Yeepay has a postback mechanism, if it visits you, you do not give it back to the information, it will continue to be sent again!
The electric dealer needs to return a string that starts with success!

Directs the client browser to redirect to the electrical quotient. is to let the client access the electrical business!

Can not use the!

HMAC:13 parameter Value +keyvalue (key) + algorithm (MD5)

13 parameter value: Set it yourself!
KeyValue: Yeepay After we registered, this dongdong only we and Yeepay know!
Bottom-MD5 algorithm: Paymentutil.buildhmac (14), which returns HMAC

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.