Micro-Credit Payment Java version of the native payment _java

Source: Internet
Author: User
Tags date now getmessage md5 md5 digest md5 encryption openid urlencode

Recently work in contact with some of the micro-letter payment, see the demo are PHP version, plus micro-letter payment document written really dare not compliment, after a lot of pits idle down to do a summary.

First, preliminary preparation

To do the micro-credit development first to apply for a public account, the successful application will send you a message in the form of the necessary information, the public account has the development of documents and the necessary information in the development, as well as testing the data query.

Second, the tool class
1.MD5 Encryption Tool class

 package com.pay.utils.weixin; import java.security.MessageDigest; public class Md5util {public final static string MD5 (string s) {char hexdigits[]={' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' D    
    ', ' E ', ' F '};
      try {byte[] btinput = S.getbytes ();
      Obtain the MessageDigest object messagedigest mdinst = messagedigest.getinstance ("MD5") of MD5 Digest algorithm;
      Use the specified Byte update digest mdinst.update (Btinput);
      Get ciphertext byte[] MD = Mdinst.digest ();
      Converts cipher text into a 16-binary string form int j = md.length;
      Char str[] = new CHAR[J * 2];
      int k = 0;
        for (int i = 0; i < J; i++) {byte byte0 = md[i];
        str[k++] = hexdigits[byte0 >>> 4 & 0xf];
      str[k++] = hexdigits[byte0 & 0xf];
    return new String (str);
      catch (Exception e) {e.printstacktrace ();
    return null; }
 }
}

2.CommonUtil Tool class for replacing the required XML for a micro-letter. The following return to the new String (Xml.tostring (). GetBytes (), "iso8859-1"); change the utf-8 in the tool class to iso8859-1, otherwise the Chinese in the micro-letter order will appear garbled, and can be displayed correctly after the change.

Package com.pay.utils.weixin;
Import java.io.UnsupportedEncodingException;
Import Java.net.URLEncoder;
Import java.util.*;

Import Java.util.Map.Entry; public class Commonutil {public static string createnoncestr (int length) {string chars = ' Abcdefghijklmnopqrstuvwxyza
 BCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";
 String res = "";
  for (int i = 0; i < length; i++) {Random rd = new Random ();
 Res + chars.indexof (Rd.nextint (Chars.length ()-1));
 return res; public static string Createnoncestr () {String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678
 9 ";
 String res = "";
  for (int i = 0; i < i++) {Random rd = new Random ();
 Res + Chars.charat (Rd.nextint (Chars.length ()-1));
 return res; public static String Formatqueryparamap (hashmap<string, string> parameters) throws Sdkruntimeexception {Str
 ing buff = ""; try {list<map.entry<string, string>> infoids = new arraylist<map.entry<string, String>> (Parameters.entryset ()); Collections.sort (Infoids, New comparator<map.entry<string, string>> () {public int compare (map.entry< String, string> O1, map.entry<string, string> O2) {return (O1.getkey ()). ToString (). CompareTo (o2.ge
   TKey ());

  }
   });
  for (int i = 0; i < infoids.size (); i++) {map.entry<string, string> item = Infoids.get (i);
  if (Item.getkey ()!= "") {buff + = Item.getkey () + "=" + Urlencoder.encode (Item.getvalue (), "utf-8") + "&";
  } if (buff.isempty () = = false) {buff = buff.substring (0, Buff.length ()-1);
 } catch (Exception e) {throw new Sdkruntimeexception (E.getmessage ());
 return buff; public static String Formatbizqueryparamap (hashmap<string, String> Paramap, Boolean urlencode) throws Sdkrunti
 meexception {String buff = ""; try {list<map.entry<string, string>> infoids = new arraylist<map.entry<string, String>> (par Amap.entrYset ()); Collections.sort (Infoids, New comparator<map.entry<string, string>> () {public int compare (map.entry< String, string> O1, map.entry<string, string> O2) {return (O1.getkey ()). ToString (). CompareTo (o2.ge
   TKey ());

  }
   });
  for (int i = 0; i < infoids.size (); i++) {map.entry<string, string> item = Infoids.get (i);
  System.out.println (Item.getkey ());
   if (Item.getkey ()!= "") {String key = Item.getkey ();
   String val = Item.getvalue ();

   if (UrlEncode) {val = Urlencoder.encode (val, "Utf-8");

  } Buff + = Key.tolowercase () + "=" + val + "&";
  } if (buff.isempty () = = false) {buff = buff.substring (0, Buff.length ()-1);
 } catch (Exception e) {throw new Sdkruntimeexception (E.getmessage ());
 return buff;
 public static Boolean isnumeric (String str) {if (Str.matches ("\\d *")) {return true;
 else {return false; }} public static String Arraytoxml (Hashmap<striNg, string> arr) {String xml = "<xml>";
 Iterator<entry<string, string>> iter = Arr.entryset (). iterator ();
  while (Iter.hasnext ()) {entry<string, string> Entry = Iter.next ();
  String key = Entry.getkey ();
  String val = Entry.getvalue ();

  if (IsNumeric (val)) {xml = = "<" + key + ">" + val + "</" + key + ">"; else XML = "<" + key + "><!
 [cdata["+ val +"]]></"+ key +" > ";
  XML = = "</xml>";
 try {return new String (Xml.tostring (). GetBytes (), "iso8859-1");
 catch (Unsupportedencodingexception e) {//TODO auto-generated catch block E.printstacktrace ();
 Return "";

 }

}

3.ClientCustomSSL Tool class for generating sign and creating micro-letter orders package com.pay.utils.weixin;

Import java.util.ArrayList;
Import java.util.Collections;
Import Java.util.Comparator;
Import Java.util.HashMap;
Import java.util.List;

Import Java.util.Map;


Import Org.springframework.util.StringUtils;
 /** * This example demonstrates you to create secure connections with a custom SSL * context. */public class Clientcustomssl {public static String getbizsign (hashmap<string, string> bizobj) throws Sdkrunt

 imeexception {hashmap<string, string> bizparameters = new hashmap<string, string> ();
  list<map.entry<string, string>> infoids = new arraylist<map.entry<string, String>> (
 Bizobj.entryset ());
 System.out.println (Infoids); Collections.sort (Infoids, New comparator<map.entry<string, string>> () {public int compare (map.entry<
  String, string> O1, map.entry<string, string> O2) {return (O1.getkey ()). ToString (). CompareTo (O2.getkey ());
}
 });
 System.out.println ("--------------------"); System.out.println(Infoids);
  for (int i = 0; i < infoids.size (); i++) {map.entry<string, string> item = Infoids.get (i);
  if (Item.getkey ()!= "") {Bizparameters.put (Item.getkey (). toLowerCase (), Item.getvalue ());
 }//bizparameters.put ("Key", "12345678123456781234567812345671");
 String bizstring = Commonutil.formatbizqueryparamap (Bizparameters, false);
 Bizstring + = "&key=12345678123456781234567812345671";
 
 System.out.println ("***************");

System.out.println (bizstring);
 Return SHA1UTIL.SHA1 (bizstring);

 Return Md5util.md5 (bizstring); /** * Micro Letter Create order * @param noncestr * @param orderdescribe * @param orderNo * @param price * @param timestart * @para M Timeexpire * @return * @throws sdkruntimeexception/public static string Createnativepackage (String Noncestr,strin G orderdescribe,string orderno,string price,string timestart,string timeexpire) throws Sdkruntimeexception {HashMap
 <string, string> nativeobj = new hashmap<string, string> (); NAtiveobj.put ("AppID", "See Public account");    Public Account ID nativeobj.put ("mch_id", "See Mail");       Merchant number Nativeobj.put ("Nonce_str", noncestr);    Random string Nativeobj.put ("Body", orderdescribe);    Product Description Nativeobj.put ("Attach", "Tradeno");          Additional Data nativeobj.put ("Out_trade_no", orderNo);   Merchant Order number (globally unique) nativeobj.put ("Total_fee", price);     Total Amount (unit is divided, can not bring small points) Nativeobj.put ("Spbill_create_ip", "192.168.0.144");          Terminal IP nativeobj.put ("Time_start", Timestart);      Transaction start Time Nativeobj.put ("Time_expire", Timeexpire); Transaction End Time Nativeobj.put ("Notify_url", Customizedpropertyplaceholderconfigurer.getcontextproperty ("Wxurl") + "/                   Weixin_callback/weixincallback/init.action ");   Callback Notification Address Nativeobj.put ("Trade_type", "NATIVE");
 
 Transaction type String sign = getbizsign (nativeobj);
 
 Nativeobj.put ("Sign", Sign.touppercase ());

 Return Commonutil.arraytoxml (nativeobj); /** * Micro-Credit Order Payment Enquiry * @param noncestr * @param orderdescribe * @param orderNo * @param price * @param tImestart * @param timeexpire * @return * @throws sdkruntimeexception/public static string Searchnativepackage (String tr Ansactionid,string outtradeno,string noncestr) throws Sdkruntimeexception {hashmap<string, String> nativeObj =
New hashmap<string, string> (); Nativeobj.put ("AppID", "See Public account"); Public Account ID nativeobj.put ("mch_id", "See Mail");/merchant number Nativeobj.put ("Nonce_str", noncestr);//random string if (! 
Stringutils.isempty (TransactionID)) {nativeobj.put ("transaction_id", TransactionID); } if (! Stringutils.isempty (Outtradeno)) {nativeobj.put ("Out_trade_no", Outtradeno);//random string} string sign = Getbizsign (
Nativeobj); 
Nativeobj.put ("Sign", Sign.touppercase ());
 Return Commonutil.arraytoxml (nativeobj); /** * @param outtradeno * @param outrefundno * @param totalfee * @param refundfee * @return * @throws Sdkruntimeex Ception */public static string Refundnativepackage (String outtradeno,string outrefundno,string totalfee,string Refundfee,string noncestr) throws Sdkruntimeexception {hashmap<string, string> nativeobj = new hashmap<string, string> (); Nativeobj.put ("AppID", "See Public Account");//Public Account ID nativeobj.put ("mch_id", "See Mail");/merchant number Nativeobj.put ("Nonce_str", Noncestr) ;//random string Nativeobj.put ("Out_trade_no", Outtradeno);//Merchant Order number (globally unique) nativeobj.put ("Out_refund_no", Outrefundno); Merchant Refund Number (globally unique) nativeobj.put ("Total_fee", totalfee);//Total Amount (unit is divided, can not bring small points) Nativeobj.put ("Refund_fee", refundfee);/Refund Amount
(Unit is divided, can not bring small points) Nativeobj.put ("op_user_id", "Mail");
String sign = getbizsign (nativeobj);
Nativeobj.put ("Sign", Sign.touppercase ());
Return Commonutil.arraytoxml (nativeobj); /** * @param noncestr * @param orderdescribe * @param orderNo * @param price * @param timestart * @param timee Xpire * @return * @throws sdkruntimeexception/public static string Createjsapipackage (String noncestr,string ORDERDESCR Ibe,string orderno,string price,string timestart,string timeexpire,string openId) throws Sdkruntimeexception {HashMap& Lt String, string> nativeobj = new Hashmap<strING, string> (); Nativeobj.put ("AppID", "See Public Account");/Public Account ID nativeobj.put ("OpenID", OpenID);//Public Account ID nativeobj.put ("mch_id", "See Mail")// Merchant number Nativeobj.put ("Nonce_str", noncestr);//random string Nativeobj.put ("Body", orderdescribe);//Product Description Nativeobj.put ("Attach" , "Tradeno")//Additional Data nativeobj.put ("Out_trade_no", orderNo);//Merchant Order number (globally unique) nativeobj.put ("Total_fee", price);//Total Amount ( Unit is divided, can not bring small points) Nativeobj.put ("Spbill_create_ip", "192.168.0.144");/terminal IP nativeobj.put ("Time_start", Timestart); Transaction start Time Nativeobj.put ("Time_expire", Timeexpire)//Transaction End time Nativeobj.put ("Notify_url", Customizedpropertyplaceholderconfigurer.getcontextproperty ("Wxurl") + "/weixin_callback/weixincallback/
Init.action ");//Notification Address Nativeobj.put (" Trade_type "," Jsapi ");//transaction type String sign = getbizsign (nativeobj);
Nativeobj.put ("Sign", Sign.touppercase ());
Return Commonutil.arraytoxml (nativeobj); /** * Micro-letter Close Order * @param noncestr * @param orderdescribe * @param orderNo * @param price * @param timestart * @param Timeex Pire * @param openId * @return * @thRows Sdkruntimeexception */public static string Createcloseorder (String outtradeno,string noncestr) throws sdkruntimeexception {hashmap<string, string> nativeobj = new hashmap<string, string> (); NativeObj.put (" AppID "," See Public Account ");//Public Account ID nativeobj.put (" mch_id "," See Mail ");/merchant number Nativeobj.put (" Out_trade_no ", Outtradeno);//Merchant Order number (
Globally unique) nativeobj.put ("Nonce_str", noncestr);//random strings string sign = Getbizsign (nativeobj);
 Nativeobj.put ("Sign", Sign.touppercase ());
Return Commonutil.arraytoxml (nativeobj);

 }
}

4. Calling the micro-credit payment interface  

Package com.pay.controller.weixin;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.security.KeyStore;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;

Import java.util.List;
Import Javax.net.ssl.SSLContext;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;
Import Net.sf.json.JSONArray;

Import Net.sf.json.JSONObject;
Import org.apache.http.HttpEntity;
Import Org.apache.http.client.methods.CloseableHttpResponse;
Import Org.apache.http.client.methods.HttpPost;
Import Org.apache.http.conn.ssl.SSLConnectionSocketFactory;
Import org.apache.http.conn.ssl.SSLContexts;
Import org.apache.http.entity.StringEntity;
Import org.apache.http.impl.client.CloseableHttpClient;
Import org.apache.http.impl.client.HttpClients;
Import Org.apache.http.util.EntityUtils;
Import org.dom4j.Document;
Import Org.dom4j.DocumentHelper;
Import org.dom4j.Element;
Import Org.dom4j.io.SAXReader; Import Org.springframework.beans.factory.annotation.autowired;
Import Org.springframework.http.HttpStatus;
Import Org.springframework.web.bind.annotation.RequestBody;
Import org.springframework.web.bind.annotation.RequestMapping;
Import Org.springframework.web.bind.annotation.RequestMethod;
Import Org.springframework.web.bind.annotation.ResponseStatus;

Import Org.springframework.web.bind.annotation.RestController;
Import com.pay.bo.PayHist;
Import Com.pay.constants.PayHistoryPayStatus;
Import Com.pay.constants.PayHistoryPayType;
Import Com.pay.service.WeiXinPayService;
Import Com.pay.utils.weixin.ClientCustomSSL;
Import Com.pay.utils.weixin.CloseWeiXinOrderUtils;


Import Com.pay.utils.weixin.CustomizedPropertyPlaceholderConfigurer; @RestController @RequestMapping ("/pay") public class Weixinpaycontroller {@Autowired weixinpayservice weixinpayserv
 Ice
 
 private static long standardtime = 1662652800000L; /** * Returns the URL generating a two-dimensional code @param request * @param response * @return * * * @RequestMapping (value= "/geturl", Method=requestmeth Od. POST) @ResponseStatus (httpstatus.ok) public Object getUrl (httpservletresponse response, @RequestBody String body) {try{
  Jsonobject Jsono = jsonobject.fromobject (body);
Payhist ph = NULL;
  List<map<string,object>> td = Weixinpayservice.gettrade (ORDERNO);
  Date dt = new Date ();
  SimpleDateFormat SDF = new SimpleDateFormat ("Yyyymmddhhmmss");
  String noncestr = sdf.format (dt). toString ();
  
  Date now = new Date (); String Tradepayno = Jsono.get ("OrderNo"). ToString () +string.format ("%10d", Standardtime-now.gettime ()). substring (0,
  10);
  System.out.println ("Order marking orderno=======" +jsono.get ("OrderNo"). toString ());
  System.out.println ("10-bit random number =======" +string.format ("%10d", Standardtime-now.gettime ()). substring (0, 10));
  String Price = Math.Round (float.valueof (Jsono.get ("price"). ToString ()) *100) + "";
  Long timeexpirestrold = Dt.gettime (); Long timenew = Long.parselong (Customizedpropertyplaceholderconfigurer.getcontextproperty ("
Weixin.send2finish.overtime "). toString ());  Long timeexpirenew = timeexpirestrold+timenew;
  Date Dttimeexpire = new Date (timeexpirenew);
  SimpleDateFormat dtsdf = new SimpleDateFormat ("Yyyymmddhhmmss");
  String Timeexpire = Dtsdf.format (Dttimeexpire). toString ();
  System.out.println ("noncestr==" +noncestr);
  System.out.println ("orderno==" +jsono.get ("OrderNo"). toString ());
  System.out.println ("price==" +price);
  System.out.println ("timestart==" +noncestr);
  
  
  System.out.println ("timeexpire==" +timeexpire);
  
  Jsonobject result = (jsonobject) seturl (Noncestr, "order", Tradepayno,price,noncestr,timeexpire);
  if (Result.get ("status"). ToString (). Equals ("Success")) {ph = new payhist (); Ph.settradepayurl (result.getstring ("Weixinpayurl"));//This field is paid link, which can be delivered into two-dimensional code sweep code to pay Ph.setpaytradeno (Jsono.get ("
  OrderNo "). toString ());
  Ph.settradepayno (Tradepayno);
  Ph.setpaystatus (payhistorypaystatus.wechat_pay_status_wait);
  Ph.setpaytype (Payhistorypaytype.wechat);
  Ph.setappkey (jsono.getstring ("Appkey"). toString ()); Ph.setpayamount (price);
  Result.put ("Paytradeno", Ph.getpaytradeno ());
  Result.put ("Tradepayno", Ph.gettradepayno ());
  Result.put ("Paystatus", Ph.getpaystatus ());
  
  Result.put ("PayType", Ph.getpaytype ());
  
  
 return result;
  }catch (Exception e) {e.printstacktrace ();
  Jsonobject result = new Jsonobject ();
  Result.put ("Status", "error");
Result.put ("msg", E.getmessage ());
 return result.tostring ();
 
 
 return null; Public Object SetUrl (String noncestr,string orderdescribe,string orderno,string price,string timestart,string timeExp
  IRE) {try{KeyStore KeyStore = keystore.getinstance ("PKCS12");
  FileInputStream instream = new FileInputStream (new File (micro-letter Certificate absolute path));
  try {keystore.load (instream, merchant ID. ToCharArray ());
  }finally {instream.close (); }//Trust own CA and all self-signed certs sslcontext sslcontext = Sslcontexts.custom (). Loadkeymaterial (keystore,&lt ; span style= "font-family:arial, Helvetica, Sans-serif;" > Merchant Id</span>.tochararray ()). BuilD (); Allow TLSV1 protocol only sslconnectionsocketfactory SSLSF = new Sslconnectionsocketfactory (Sslcontext, New Strin
  G[] {"TLSV1"}, NULL, sslconnectionsocketfactory.allow_all_hostname_verifier);
  Closeablehttpclient httpclient = Httpclients.custom (). Setsslsocketfactory (SSLSF). build ();
  HttpGet HttpGet = new//HttpGet ("Https://api.mch.weixin.qq.com/secapi/pay/refund");
  
  HttpPost HttpPost = new HttpPost ("Https://api.mch.weixin.qq.com/pay/unifiedorder");
  String XML = Clientcustomssl.createnativepackage (Noncestr,orderdescribe,orderno,price,timestart,timeexpire);
  
  try {stringentity se = new stringentity (XML);

  Httppost.setentity (SE);

  SYSTEM.OUT.PRINTLN ("Executing request" + httppost.getrequestline ());
  Closeablehttpresponse responseentry = Httpclient.execute (HttpPost);

   try {httpentity entity = responseentry.getentity ();
   System.out.println ("----------------------------------------"); System.out.println (Responseentry.getstatUsline ());
  if (entity!= null) {System.out.println ("Response Content Length:" + entity.getcontentlength ());
   /* BufferedReader BufferedReader = new BufferedReader (New InputStreamReader (Entity.getcontent ()));
   String text;
   while (Text = Bufferedreader.readline ())!= null) {System.out.println ("=======" +text);
   }*/Saxreader saxreader = new Saxreader ();
   Document document = Saxreader.read (Entity.getcontent ());
   Element Rootelt = Document.getrootelement ();
   SYSTEM.OUT.PRINTLN ("root node:" + Rootelt.getname ());
   System.out.println ("= =" +rootelt.elementtext ("Result_code"));
   System.out.println ("= =" +rootelt.elementtext ("return_msg"));
   String ResultCode = Rootelt.elementtext ("Result_code");  
   
   Jsonobject result = new Jsonobject ();
   Document documentxml =documenthelper.parsetext (XML);
   
   Element rooteltxml = Documentxml.getrootelement (); if (Resultcode.equals ("SUCCESS")) {System.out.println ("=================prepay_id==================== "+ rootelt.elementtext (" prepay_id "));
    System.out.println ("=================sign====================" + rooteltxml.elementtext ("sign"));
    Result.put ("Weixinpayurl", Rootelt.elementtext ("Code_url"));
    Result.put ("Prepayid", Rootelt.elementtext ("prepay_id"));
    Result.put ("Status", "Success");
   Result.put ("MSG", "success");
    }else{result.put ("status", "false");
   Result.put ("msg", Rootelt.elementtext ("Err_code_des"));

   return result;
  } entityutils.consume (entity);
  finally {responseentry.close ();
  finally {httpclient.close ();
  
  
 return null;
  }catch (Exception e) {e.printstacktrace ();
  Jsonobject result = new Jsonobject ();
  Result.put ("Status", "error");
  Result.put ("msg", E.getmessage ());
 return result;


 }
 }
 
}

HttpClient jar package and JSON jar package: Download address.

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.