Several kernel feature files for Alipay:
Alipayfunction.java
Package com.test.util.alipay;
Import Java.io.FileWriter;
Import java.io.IOException;
Import java.net.MalformedURLException;
Import Java.net.URL;
Import java.util.ArrayList;
Import java.util.Collections;
Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;
Import org.dom4j.Document;
Import org.dom4j.DocumentException;
Import Org.dom4j.Node;
Import Org.dom4j.io.SAXReader; public class Alipayfunction {/** * Features: Generating signature results * @param sarray the array to be signed * @param key Security Check code * @return Signature Result String * * public static string Buildmysign (Map Sarray, string key) {String prestr = createlinkstring (Sarray);//Put all elements of an array in the mode of "parameter = parameter value" "& amp; " character concatenation into string prestr = Prestr + key;
The concatenation string is then connected directly with the security check code string mysign = Md5encrypt.md5 (PRESTR);
return mysign; /** * Function: Remove null values and signature parameters in array * @param sarray signature Parameter Group * @return remove the null and signature parameters of the new signature parameter group/public static map Parafilter (map Sarra
Y) {List keys = new ArrayList (Sarray.keyset ());
Map sarraynew = new HashMap (); for (int i = 0; i < keys. Size ();
i++) {String key = (string) keys.get (i);
String value = (string) sarray.get (key);
if (value = null | | value.equals ("") | | Key.equalsignorecase ("sign") | |
Key.equalsignorecase ("Sign_type")) {continue;
} sarraynew.put (key, value);
return sarraynew; /** * Function: Sort all elements of an array and concatenate them into strings by "&" characters according to the "parameter = parameter value" Pattern * @param params the parameter group that needs to sort and participate in the character concatenation * @return concatenation string/public Stati
C String createlinkstring (Map params) {List keys = new ArrayList (Params.keyset ());
Collections.sort (keys);
String prestr = "";
for (int i = 0; i < keys.size (); i++) {String key = (String) keys.get (i);
String value = (string) params.get (key);
if (i = = Keys.size ()-1) {//stitching, excluding the last & character prestr = prestr + key + "=" + value;
else {prestr = prestr + key + "=" + Value + "&";
} return PRESTR; /** * Function: Write log, easy to test (see the website needs, can also be changed to the record into the database) * @param sword The text content to be written to the log * * public static void Logresult (String sword) {/ /The file exists in the same directory as the application server startup file, the filename is Alipay log plus server time try {FileWriter WRiter = new FileWriter ("D:\\alipay_log" + system.currenttimemillis () + ". txt");
Writer.write (sword);
Writer.close ();
catch (Exception e) {e.printstacktrace (); }/** * Features: For anti-phishing, call interface Query_timestamp to get timestamp processing function * Note: Remote parse XML error, with server support SSL configuration related * @param partner Partner ID * @return Timestamp String * @throws IOException * @throws documentexception * @throws malformedurlexception/public static string Que Ry_timestamp (string partner) throws Malformedurlexception, Documentexception, IOException {String strURL = "Https://map
I.alipay.com/gateway.do?service=query_timestamp&partner= "+partner;
StringBuffer buf1 = new StringBuffer ();
Saxreader reader = new Saxreader ();
Document doc = Reader.read (new URL (strURL). OpenStream ());
List<node> nodelist = doc.selectnodes ("//alipay/*"); for (Node node:nodelist) {//intercepting information that does not need to be parsed if (Node.getname (). Equals ("Is_success") && Node.gettext (). Equals (" T ")) {//To determine whether there is a success mark list<node> nodeList1 = Doc.selectnodes ("//response/timestamp/* ");
for (Node node1:nodelist1) {buf1.append (Node1.gettext ());
}} return buf1.tostring (); }
}
Alipaynotify.java
Package com.test.util.alipay;
Import Java.io.BufferedReader;
Import Java.io.InputStreamReader;
Import java.net.HttpURLConnection;
Import Java.net.URL;
Import Java.util.Map;
Import Com.test.constants.AlipayConfig; public class Alipaynotify {/** * * function: Generate signature results based on feedback information * @param Params notification returns the parameter array * @param key security Check code * @return generated signature knot Fruit/public static String getmysign (map Params, string key) {Map sparanew = Alipayfunction.parafilter (Params);//filter null value, si
GN and Sign_type parameter String mysign = Alipayfunction.buildmysign (sparanew, key);//Get signature result return mysign; /** * * Features: Get remote server ATN results, verify return URL * @param notify_id notification CHECKSUM ID * @return Server ATN results * Validate result set: * Invalid command parameter does not appear this error, please detect the return Richong partner and key is NULL * True returns the correct message * False check the firewall or the server block port problem and verify that the time is more than one minute/public static string Verify (String notify_i
d) {//Get the remote server ATN results, verify that the Alipay server sent the request String transport = Alipayconfig.transport;
String partner = Alipayconfig.partner;
String Veryfy_url = ""; if (transport.equalsignorecase ("https")) {veRyfy_url = "Https://www.alipay.com/cooperate/gateway.do?service=notify_verify";
} else{Veryfy_url = "http://notify.alipay.com/trade/notify_query.do?";
} Veryfy_url = Veryfy_url + "&partner=" + partner + "¬ify_id=" + notify_id;
String responsetxt = Checkurl (Veryfy_url);
return responsetxt; /** * * Function: Get remote server ATN result * @param urlvalue Specify URL path address * @return Server ATN results * Validate result set: * Invalid command parameter does not appear this error, please detect the return processing part
NER and key is NULL * True returns the correct message * False check the firewall or the server blocking port problem and whether the verification time is more than one minute/public static string Checkurl (String urlvalue) {
String inputline = "";
try {URL url = new URL (urlvalue);
HttpURLConnection URLConnection = (httpurlconnection) URL. OpenConnection ();
BufferedReader in = new BufferedReader (New InputStreamReader (Urlconnection.getinputstream ()));
Inputline = In.readline (). toString ();
catch (Exception e) {e.printstacktrace ();
return inputline; }
}
Alipayservice.java
Package com.test.util.alipay;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map; public class Alipayservice {/** * feature: Structuring form submission HTML * @param partner Partner ID * @param seller_email sign up for Alipay account or seller Alipay accounts * @pa Ram Return_url After paying the paragraph to jump to the page to the HTTP opening format of the full path, not allowed to add? id=123 such custom parameters * @param notify_url The full path of the server notification in the course of the transaction to HTTP open format, not allowed to add? ID =123 This kind of custom parameter * @param show_url website product display address, not allowed to add? id=123 such custom parameters * @param out_trade_no please match the unique order number in your site order system * @param subject Order
The name, shown in the Alipay cashier's "Commodity name", is displayed in the "Commodity name" list of Alipay's transaction management. * @param the body Order description, Order details, order notes, shown in the Alipay cashier's "description of goods" * @param total_fee Order Total amount, shown in the Alipay Cashier's "Total payable" * @param paymethod Default payment method, four Value Optional: Bankpay (net silver); Cartoon (Cartoon); DirectPay (balance); CASH (dot payment) * @param defaultbank Default network Silver code, code list see club.alipay.com/read.php?tid=8681379 * @param encrypt_key Fishing time stamp * @param e XTER_INVOKE_IP Buyer Local Computer IP address * @param extra_common_param custom parameters, can be stored in any content (except for special characters), will not appear on the page * @param buyer_email default Buyer pay Treasure Account * @param royalty_type Commission type, which is a fixed value: 10, no need to modify
* @param royalty_parameters Commission information set, and the need to combine the situation of the merchant site itself dynamically obtain each transaction splitting collection account number, splitting amount, each splitting description. Up to 10 * @param input_charset character encoding format currently supports GBK or Utf-8 * @param key Security Check code * @param sign_type Signature without modification * @param key
Secure Checksum code * @return Form Submit HTML text/public static string Buildform (string partner, String seller_email, String Return_url, String Notify_url, String Show_url, String out_trade_no, string subject, String body, String Total_fee, String Paym Ethod, String Defaultbank, String Anti_phishing_key, String exter_invoke_ip, String Extra_common_param, String buyer_ Email, string royalty_type, String royalty_parameters, String input_charset, String key, String Sign_type, string it
_b_pay) {Map Spara = new HashMap ();
Spara.put ("service", "Create_direct_pay_by_user");
Spara.put ("Payment_type", "1");
Spara.put ("partner", partner);
Spara.put ("Seller_email", Seller_email);
Spara.put ("Return_url", Return_url);
Spara.put ("Notify_url", Notify_url); Spara.put ("_input_charset", Input_charset);
Spara.put ("Show_url", Show_url);
Spara.put ("Out_trade_no", out_trade_no);
Spara.put ("Subject", subject);
Spara.put ("Body", the body);
Spara.put ("Total_fee", Total_fee);
Spara.put ("Paymethod", Paymethod);
Spara.put ("Defaultbank", Defaultbank);
Spara.put ("Anti_phishing_key", Anti_phishing_key);
Spara.put ("Exter_invoke_ip", exter_invoke_ip);
Spara.put ("Extra_common_param", Extra_common_param);
Spara.put ("Buyer_email", Buyer_email);
Spara.put ("Royalty_type", Royalty_type);
Spara.put ("Royalty_parameters", royalty_parameters);
Spara.put ("It_b_pay", It_b_pay); Map sparanew = Alipayfunction.parafilter (Spara); Drop null values and signature parameters in arrays String mysign = alipayfunction.buildmysign (sparanew, key);//Generate signature result StringBuffer sbhtml = new Stringbuffe
R ();
List keys = new ArrayList (Sparanew.keyset ());
String gateway = "https://www.alipay.com/cooperate/gateway.do?"; Get Way Passes//sbhtml.append ("<form id=\" alipaysubmit\ "name=\" alipaysubmit\ "action=\" "+ Gateway +" _input_charset= " + Input_charset + "" \ "method=\" Get\ ">"); Post mode pass (GET and post two must be selected) Sbhtml.append ("<form id=\" alipaysubmit\ "name=\" alipaysubmit\ "action=\" "+ Gateway +" _
Input_charset= "+ input_charset +" \ "method=\" post\ ">");
for (int i = 0; i < keys.size (); i++) {String name = (string) keys.get (i);
String value = (string) sparanew.get (name);
Sbhtml.append ("<input type=\" hidden\ "name=\" "+ name +" \ "value=\" "+ Value +" \ "/>");
} sbhtml.append ("<input type=\" hidden\ "name=\" sign\ "value=\" "+ mysign +" \ "/>");
Sbhtml.append ("<input type=\" hidden\ "name=\" sign_type\ "value=\" "+ Sign_type +" \ "/>");
Submit Button control Please do not include the Name property Sbhtml.append ("<input type=\" submit\ "value=\" Alipay confirm payment \ "></form>");
Sbhtml.append ("<script>document.forms[' Alipaysubmit '].submit ();</script>");
return sbhtml.tostring (); }
}
Md5encrypt.java
Package com.test.util.alipay;
Import java.io.UnsupportedEncodingException;
Import Java.security.MessageDigest;
Import java.security.NoSuchAlgorithmException;
Import Com.test.constants.AlipayConfig; /** * Function: Alipay MD5 encryption processing core files, do not need to modify the * version: 3.1 * Modified: 2010-11-01 * Description: * The following code is only for the convenience of merchant test sample code, merchants can according to their own website needs, according to technical documentation, not necessarily to make
With the code. * This code is only for learning and research Alipay interface use, just provide a * */public class Md5encrypt {/** * Used building OUTPUT as Hex * * private static final
Char[] DIGITS = {' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' d ', ' e ', ' f '}; /** * MD5 Encryption of Strings * * @param text * plaintext * * @return ciphertext/public static string MD5 (string text) {MessageDigest ms
Gdigest = null;
try {msgdigest = messagedigest.getinstance ("MD5");
catch (NoSuchAlgorithmException e) {throw new IllegalStateException ("System doesn ' t support MD5."); try {msgdigest.update (text.getbytes (Alipayconfig.input_charset));//Note that the interface is signed in the specified encoding form ( Unsupportedencodingexception e) {
throw new IllegalStateException ("System doesn ' t support your encodingexception.");
} byte[] bytes = Msgdigest.digest ();
String md5str = new String (Encodehex (bytes));
return md5str;
public static char[] Encodehex (byte[] Data {int L = data.length;
Char[] out = new char[l << 1];
Two characters form the hex value.
for (int i = 0, j = 0; i < L; i++) {out[j++] = digits[(0xF0 & Data[i)) >>> 4];
Out[j++] = digits[0x0f & Data[i]];
} return out; }
}
Alipayconfig.java Here are some settings for account number, Key, callback connection address, etc.
Package com.test.constants;
Import java.util.Properties;
Import Com.test.util.PropertiesUtil;
public class Alipayconfig {private static alipayconfig alconfig = null;
Private Alipayconfig () {} public static Alipayconfig getinstance () {if (alconfig==null) {alconfig = new alipayconfig ();
return alconfig;
//How to obtain the security checksum code and partner ID//1. Visit Alipay Merchant Service Center (b.alipay.com) and login with your signed Alipay account. 2. Visit "Technical Services" → "Download Technology Integration Document" (Https://b.alipay.com/support/helperApply.htm?action=selfIntegration)//3. In the self-help integration Help, click Partner identity (Partner ID) query "," Security check Code (Key) query "//↓↓↓↓↓↓↓↓↓↓ Please configure your basic information here ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓//Partner ID, starting with 2088 a string of 16-digit pure digits public
static String It_b_pay = "1h";
public static String partner = "2088601003079118";
public static String service = "Create_direct_pay_by_user";
Transaction security Inspection Code, consisting of numbers and letters of the 32-bit string public static string key = "Zxcdvxgksaam2zjrmv5cv0p4jqesaioh";
Signed Alipay account or seller's payment PO accounts public static String Seller_email = "test@yahoo.com.cn"; Read profile//NOTIFY_URL Transaction Process Server Notification page to be in http://format full path, do not allowId=123 This kind of custom parameter public static String Notify_url = "Http:www.xxx.com/projectname/alipaytrade.action"; After paying the paragraph to jump the page to use the full path of http://format, not allowed to add? id=123 such custom parameters//Return_url domain names cannot be written http://localhost/js_jsp_utf8/return_
Url.jsp, otherwise it will cause Return_url to execute invalid//public static String Return_url = "Http:www.xxx.com/projectname/alipaytrade.action";
The display address of the website product, do not allow add? id=123 This kind of custom parameter public static String Show_url = "http://www.alipay.com";
Payee name, such as: Company name, website name, payee name, etc. public static String mainname = "payee name";
↑↑↑↑↑↑↑↑↑↑ Please configure your basic information here ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑//character encoding format currently supports GBK or utf-8 public static String Input_charset = "UTF-8";
The signature method does not need to modify the public static String Sign_type = "MD5";
Access mode, depending on whether your server supports SSL access, if supported please select HTTPS; select HTTP public static String transport = "http" if not supported; }
The following is a simple application process:
The call from the JSP does not say, because this is just to the background you want to buy something is what the price of some of the parameters.
Here is an introduction to the background processing:
Paymentaction.java
/**
* Get Alipay Trading Order number
* @return
/public
synchronized static String Getordernum () {
Date date=new date ( );
DateFormat df=new SimpleDateFormat ("yyyymmddhhmmsssss");
return Df.format (date);
Protected HttpServletRequest Getrequest () {return
servletactioncontext.getrequest ();
}
Alipay Trading Order Number
String ordernum = Getordernum ();
The total amount of the transaction
Getrequest () setattribute ("Totalmoney", "0.01");
The order number of this transaction
getrequest () setattribute ("Out_trade_no", ordernum);
Description of the Product name
getrequest (). setattribute ("Subject", "Commodity Name");
alipay.jsp
<% @page import= "Com.test.constants.AlipayConfig"%> <% @page import= "Com.test.util.alipay.UtilDate"%> <% @page import= "Com.test.util.alipay.AlipayService"%> <%/* Features: Set up merchandise Information (Entry page) * Details: This page is the interface entry page, generate payment URL * Version: 3
1 * Date: 2010-11-01 * Description: * The following code is only for the convenience of merchant test samples provided by the sample code, merchants can according to their own website needs, according to technical documentation, not necessarily to use the code.
* This code is only for learning and research Alipay interface use, just provide a reference. Note ***************** If you encounter problems with the interface integration process, you can go to the Merchant Service Center (https://b.alipay.com/support/ helperapply.htm?action=consultationapply), submit application integration assistance, we will have professional technical engineers to contact you to help resolve, you can also go to the Alipay forum (http://club.alipay.com/
read-htm-tid-8681712.html) Find related solutions The parameters to pass are either not allowed to be empty or not in the array and hidden controls or URL links. * *%> <%@ page language= "java" contenttype= "text/html;" Charset=utf-8 "pageencoding=" UTF-8 "%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > <html> <head> <meta http-equiv= "Content -type "content=" text/html; Charset=utf-8 "> <title>test</title>
<link rel= "Shortcut ICON" href= "Favicon.ico" > <meta name= "keywords" content= ""/> <meta name= "Descriptio
N "content=" "/> <style type=" text/css "> font_content{font-family:" Song Body ";
font-size:14px;
Color: #FF6600;
}. font_title{font-family: "XXFarEastFont-Arial";
font-size:16px;
Color: #FF0000;
Font-weight:bold;
table{border:1px solid #CCCCCC; } </style> <script type= "Text/javascript" > var _gaq = _gaq | |
[];
_gaq.push ([' _setaccount ', ' ua-25469955-1 ']);
_gaq.push ([' _trackpageview ']);
(function () {var ga = document.createelement (' script '); ga.type = ' text/javascript '; ga.async = true; GA.SRC = (' https: ' = = Document.location.protocol?
' Https://ssl ': ' http://www ') + '. Google-analytics.com/ga.js '; var s = document.getelementsbytagname (' script ') [0];
S.parentnode.insertbefore (GA, s);
})();
</script> </head> <%//request.setcharacterencoding ("UTF-8"); Configuration information in Alipyconfig.java (cannot be modified) String Input_charset = Alipayconfig.getinstanCE (). Input_charset;
String Sign_type = Alipayconfig.getinstance (). Sign_type;
String seller_email = Alipayconfig.getinstance (). Seller_email;
String partner = alipayconfig.getinstance (). Partner;
String key = Alipayconfig.getinstance (). Key;
String Show_url = Alipayconfig.getinstance (). Show_url;
String Notify_url = Alipayconfig.getinstance (). Notify_url;
String Return_url = Alipayconfig.getinstance (). Return_url;
String It_b_pay = Alipayconfig.getinstance (). It_b_pay; The following parameters are required to be passed in the order data to get// Required parameter String out_trade_no = (string) request.getattribute ("Out_trade_no");//Please match the unique order number in your site order System//order name, shown at the Alipay Cashier's counter.
Product Name ", shown in Alipay's transaction management's" Commodity name "list.
String subject = (string) request.getattribute ("subject");
Order description, Order details, order notes, shown at the Alipay Cashier's "Product description" string BODY = (string) request.getattribute ("Body");
The total amount of the order, shown at the Alipay Cashier's "total payable" string Total_fee = (string) request.getattribute ("Totalmoney"); Extended function parameter--default payment method//StRing Pay_mode = Request.getparameter ("Pay_bank"); String Paymethod = ""; Default payment method, four values optional: Bankpay (net silver); Cartoon (Cartoon); DirectPay (balance); CASH (dot payment) String Defaultbank = ""; Default network silver Code, code list see http://club.alipay.com/read.php?tid=8681379/*if (Pay_mode.equals ("DirectPay")) {Paymethod = "
DirectPay ";
} else{Paymethod = "Bankpay";
Defaultbank = Pay_mode; }*///Extended function Parameters--anti-fishing//Please be careful to choose whether to turn on the anti-phishing feature//exter_invoke_ip, Anti_phishing_key once set, then they will be required parameters//open anti-phishing function, server,
The native computer must support remote XML parsing, please configure the environment. It is recommended that you use post to request data String Anti_phishing_key = ""; Anti-phishing timestamp String exter_invoke_ip= ""; To obtain the IP address of the client, it is recommended that you write a program to obtain the client IP address//such as://anti_phishing_key = Alipayfunction.query_timestamp (partner);
Get anti-phishing timestamp function//exter_invoke_ip = "202.1.1.1"; Extended function parameter--other String Extra_common_param = ""; Custom parameters, which can be stored in any content (except =, & and other special characters), will not appear on the page String buyer_email = "137672927";
Default buyer Alipay account String Extend_param = ""; Extended function Parameters-splitting (to use, please assign values in the format required by the annotation) String royalty_type = "";
Commission type, this value is fixed value: 10, do not need to modify String royalty_parameters = ""; CommissionInformation set, and the need to combine the situation of the Merchant website to obtain each transaction of the splitting collection account, the splitting amount, each splitting description. Up to 10//splitting sum must be less than or equal to Total_fee//royalty Information Set format: Payee email_1^ amount 1^ notes 1| payee email_2^ amount 2^ notes 2//such as://royalty_type = "Ten"//roya
Lty_parameters = "111@126.com^0.01^ splitting remark one |222@126.com^0.01^ splitting remark II"//1h will return//error description: Sorry, the merchant did not open custom Timeout permission, please contact your business.
Error code: Self_timeout_not_support it_b_pay= ""; constructor to generate the request URL String shtmltext = Alipayservice.buildform (partner,seller_email,return_url,notify_url,show_url,out_ Trade_no, Subject,body,total_fee,paymethod,defaultbank,anti_phishing_key,exter_invoke_ip,extra_common_param,
Buyer_email, Royalty_type,royalty_parameters,input_charset,key,sign_type,it_b_pay); %> <body> <table align= "center" width= "All" cellpadding= "5" cellspacing= "0" > <tr> <td align= "c Enter "class=" Font_title "colspan=" 2 "> Order confirmation </td> </tr> <tr> <td class=" font_content "align=" Right "> order number:</td> <td class=" font_content "align=" left "><%=out_trade_no%></td> </tr >
<tr> <td class= "font_content" align= "right" > Total payment amount:</td> <td class= "font_content" align= "left" ><%=total_fee%></td> </tr> <tr> <td align= "center" colspan= "2" ><%=shtmltext% ></td> </tr> </table> </body> </html>
Alipay Callback Interface: Alipaynotify.java
Package com.test.action.payment;
Import Java.util.Date;
Import java.util.List;
Import com.test.action.base.BaseAction;
Import Com.test.dao.model.paymentcenter.OrderForm;
Import com.test.dao.model.paymentcenter.OrderList;
Import Com.test.dao.model.paymentcenter.UserPurview;
public class Alipaynotify extends Baseaction {private static final long serialversionuid = 1L;
Private String Buyer_email;
Private long buyer_id;
Private String Exterface;
Private String is_success;
Private String notify_id;
Private String Notify_time;
Private String Notify_type;
Private String out_trade_no;
Private String Payment_type;
Private String Seller_email;
Private long seller_id;
Private String subject;
private float Total_fee;
Private String trade_no;
Private String Trade_status;
Private String sign;
Private String Sign_type;
Private OrderForm of; ...... This eliminates the get and set methods ..... ......... ............ ............. ....... ...... ....... ...//Processing Payment PO passed the parameter information public String Alipaytrade () throws Exception {if (this.is_su Ccess.eQualsignorecase ("T") && "Trade_success". Equalsignorecase (This.trade_status)) {of = (orderform)
Orderformservice. Findorderformsbyout_trade_no (This.out_trade_no);
if (of!= null) {of.settradestatus (1);
Of.settradeno (THIS.TRADE_NO);
Of.setnotifytime (New Date ()); Orderformservice.updateoldmodel (of);
Update list<orderlist> orderlist = Orderlistservice. Findorderformsbyouttradeno (This.out_trade_no);
for (OrderList ol:orderlist) {///This eliminates the processing order logic code ...........}
After the callback is successful, return a "success" character to the Alipay, returning to success;
Return to "failure"; }
}
In this way, Alipay's third-party real-time access to the account interface even if implemented.
The above is a small set to introduce the implementation of the Java payment of the third party Alipay Alipay real-time to pay the function, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!