Several kernel function files of 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 { /** * Function: generate signature result* @param sArray array to be signed* @param key Security verification code* @return Signature result string*/ public static String BuildMysign(Map sArray, String key) { String prestr = CreateLinkString(sArray); //Spline all elements of the array into a string using the "&" character according to the "parameter = parameter value" prestr = prestr + key; //Connect the spliced string directly with the security check code String mysign = Md5Encrypt.md5(prestr); return mysign; } /** * Function: Remove the null values and signature parameters in the array* @param sArray Signature parameter group* @return Remove the null values and new signature parameter group*/ public static Map ParaFilter(Map sArray){ 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 the array and splice them into strings in the "&" character according to the "parameter = parameter value" pattern* @param params Params parameter groups that need to be sorted and participated in character splicing* @return String after splicing */ public static 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) {//When splicing, the last character is not included prestr = prestr + key + "=" + value; } else { prestr = prestr + key + "=" + value + "&"; } } return prestr; } /** * Function: Write logs for easy testing (see website requirements, you can also change to store records in the database) * @param sWord Text content to be written in the log*/ public static void LogResult(String sWord){ // This file exists in the same directory as the application server startup file, the file name 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(); } } /** * Function: Used to prevent phishing, call the interface query_timestamp to get the timestamp processing function* Note: An error occurred in remote parsing XML, which is related to whether the server supports SSL and other configurations* @param partner Cooperative Identity ID * @return Timestamp String * @throws IOException * @throws DocumentException * @throws MalformedURLException */ public static String query_timestamp(String partner) throws MalformedURLException, DocumentException, IOException { String strUrl = "https://mapi.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) { // Intercept the information that does not need to be parsed if (node.getName().equals("is_success") && node.getText().equals("T")) { // Determine whether there is a successful 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 the information returned* @param Params Notification parameter array returned* @param key Security verification code* @return Signature results generated*/ public static String GetMysign(Map Params, String key){ Map sParaNew = AlipayFunction.ParaFilter(Params);//Filter empty values, sign and sign_type parameters String mysign = AlipayFunction.BuildMysign(sParaNew, key);//Get signature result return mysign; } /** * *Function: Get the remote server ATN result, verify return URL * @param notify_id Notify verification ID * @return Server ATN result* Verify result set: * This error occurs when the invalid command parameter is incorrect. Please check whether the partner and key are empty in the return process* true Return correct information* false Please check the firewall or server blocking port problems and verify whether the time exceeds one minute*/ public static String Verify(String notify_id){ //Get the ATN result of the remote server and verify whether it is a request sent by the Alipay server 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 the remote server ATN result* @param urlvalue Specify the URL path address* @return Server ATN result* Verification result set: * This error occurs when the invalid command parameter is incorrect. Please check whether the partner and key are empty in the return process* true Return correct information* false Please check the firewall or server blocking port problems and verify that the time exceeds 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 { /** * Function: Construct form submission HTML * @param partner Cooperative ID * @param seller_email Signing Alipay account or seller Alipay account * @param return_url The page that jumps after payment should be used to start with http. Custom parameters such as ?id=123 are not allowed to be added* @param notify_url During the transaction process, the page notified by the server should use the complete path in the format opened by http. Custom parameters such as ?id=123 are not allowed to be added. * @param show_url The display address of the website product, and custom parameters such as ?id=123 are not allowed to be added. * @param out_trade_no Please match the unique order number in the order system of your website* @param subject The order name is displayed in the "Product Name" in the Alipay cashier and in the list of "Product Name" in the transaction management of Alipay. * @param body Order description, order details, order notes, displayed in the "Product Description" in the Alipay cashier* @param total_fee The total order amount is displayed in the "Total payable" in the Alipay cashier* @param paymentmethod Default payment method, four values are available: bankPay (online bank); cartoon (cartoon); directPay (balance); CASH (outline payment) * @param defaultbank Default online banking code, see club.alipay.com/read.php?tid=8681379 * @param encrypt_key Anti-phishing timestamp* @param exter_invoke_ip The IP address of the buyer's local computer* @param extra_common_param Custom parameters, which can store any content (except for special characters, etc.) and will not be displayed on the page * @param buyer_email Default buyer Alipay account* @param royalty_type Commitment type, which is a fixed value: 10, and does not need to be modified * @param royalty_parameters Commitment information set, and dynamically obtain each profit collection account, each profit amount, and each profit description for each transaction based on the merchant website's own situation. Only 10 characters can be set up at most * @param input_charset The character encoding format currently supports GBK or utf-8 * @param key security verification code* @param sign_type The signature method does not need to be modified* @param key security verification code* @return form submission 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 paymethod, 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", 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); //Remove the null values in the array and signature parameters String mysign = AlipayFunction.BuildMysign(sParaNew, key); //Generate the signature result StringBuffer sbHtml = new StringBuffer(); List keys = new ArrayList(sParaNew.keySet()); String gateway = "https://www.alipay.com/cooperate/gateway.do?"; //GET method pass//sbHtml.append("<form id=/"alipaysubmit/" name=/"alipaysubmit/" action=/"" + gateway + "_input_charset=" + input_charset + "/" method=/"get/">"); //POST method pass (GET and POST 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 contain the name attribute sbHtml.append("<input type=/"submit/" value=/"Alipay confirmation 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 encrypts and processes core files, and does not require modification* Version: 3.1 * Modification date: 2010-11-01 * Description: * The following code is just a sample code provided for convenience for merchant testing. Merchants can write it according to the needs of their own website and according to technical documents. This code is not necessarily required. * This code is only for learning and researching the Alipay interface, but only provides 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 msgDigest = null; try { msgDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException( "System doesn't support MD5 algorithm."); } try { msgDigest.update(text.getBytes(AlipayConfig.input_charset)); //Note that changing the interface is signed in the specified encoding format} catch (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 is 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 get the security verification code and the partner ID // 1. Visit the Alipay Merchant Service Center (b.alipay.com), and then log in with your contracted Alipay account. // 2. Access "Technical Services" → "Download Technology Integration Documents" (https://b.alipay.com/support/helperApply.htm?action=selfIntegration) // 3. In the "Self-service Integration Help", click "Partner ID query" and "Safety Verification Code (Key) query" // ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓� partner = "2088601003079118"; public static String service = "create_direct_pay_by_user"; // Transaction security verification code, 32-bit string composed of numbers and letters public static String key = "zxcdvxgksaam2zjrmv5cv0p4jqesaioh"; // Sign up for Alipay account or seller's payment Alipay account public static String seller_email = "[email protected]"; // Read configuration file // Notify_url The page of server notification during the transaction must use the full path in the format of http:// format, and custom parameters such as ?id=123 are not allowed to be added public static String notify_url ="http:www.xxx.com/projectName/alipayTrade.action"; // The page that jumps after payment must use the full path in the format of http://., and custom parameters such as ?id=123 are not allowed to be added. The domain name of return_url cannot be written as http://localhost/js_jsp_utf8/return_url.jsp, otherwise the return_url execution will be invalid. //public static String return_url = "http:www.xxx.com/projectName/alipayTrade.action"; // The display address of the website product, custom parameters such as ?id=123 are not allowed to be added public static String show_url = "http://www.alipay.com"; // The name of the payee, such as: company name, website name, payee name, etc. public static String mainname = "payer name"; // ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑� String transport = "http"; }Here is a simple application process:
I won’t talk about what you call from JSP, because this is just passed to the background, what is the price, and other parameters.
Here is a description of the background processing:
PaymentAction.java
/** * Get Alipay transaction 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 transaction order number String orderNum = getOrderNum(); // The total amount of this transaction getRequest().setAttribute("totalMoney","0.01"); //The order number of this transaction getRequest().setAttribute("out_trade_no", orderNum); //Product name description getRequest().setAttribute("subject", "Product name"); //The process of storing this order information to the database is omitted herealipay.jsp
<%@page import="com.test.constants.AlipayConfig"%> <%@page import="com.test.util.alipay.UtilDate"%> <%@page import="com.test.util.alipay.AlipayService"%> <% /* Function: Set product-related information (entry page) *Details: This page is the interface portal page, the URL when generating payment * Version: 3.1 * Date: 2010-11-01 * Description: * The following code is just a sample code provided for convenience of merchant testing. Merchants can write it according to the needs of their own website and according to technical documents, and it is not necessary to use this code. *This code is for learning and researching the Alipay interface only, and is only provided as a reference. *************************************** If you encounter problems during interface integration, you can go to the Merchant Service Center (https://b.alipay.com/support/helperApply.htm?action=consultationApply) to submit an application for integration assistance. We will have professional technical engineers to contact you to assist in solving the problem. You can also go to the Alipay forum (http://club.alipay.com/read-htm-tid-8681712.html) to find relevant solutions. The parameters to be passed are either not allowed to be empty, or they do not appear in the array, 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="description" content="" /> <style type="text/css"> .font_content{ font-family:"客"; font-size:14px; color:#FF6600; } .font_title{ font-family:"客"; 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"); //Config 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; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// String subject = (String)request.getAttribute("subject"); //Order description, order details, order notes are displayed in the "Product Description" in the Alipay cashier String body = (String)request.getAttribute("body"); //Total order amount is displayed in the "Total payable" in the Alipay cashier String total_fee = (String)request.getAttribute("totalMoney"); //Extended function parameters - default payment method // String pay_mode = request.getParameter("pay_bank"); String paymentmethod = ""; //Default payment method, four values are available: bankPay (online banking); cartoon (cartoon); directPay (balance); CASH (internet payment) String defaultbank = ""; //Default online banking code, 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-phishing//Please carefully choose whether to enable anti-phishing function //Once exter_invoke_ip and anti-phishing_key have been set, they will become required parameters //After turning on the anti-phishing function, the server and local computer must support remote XML parsing, please configure the environment. //It is recommended to use POST to request data String anti_phishing_key = ""; //Anti-phishing timestamp String exter_invoke_ip= ""; //Get the client's IP address, suggest: write a program to obtain the client's IP address //For example: //anti-phishing_key = AlipayFunction.query_timestamp(partner); //Get anti-phishing timestamp function //exter_invoke_ip = "202.1.1.1"; //Extended function parameters - other String extra_common_param = ""; //Custom parameters, can store any content (except special characters such as = and &), and will not be displayed on the page String buyer_email = "137672927"; //Default buyer Alipay account String extend_param = ""; //Extended function parameters - split profit (If you want to use it, please assign values according to the format required by the comment) String royalty_type = ""; //Commission type, this value is a fixed value: 10, no need to modify String royalty_parameters =""; //Commission information set, dynamically obtain each split payment account, each split amount, and each split description of each transaction based on the merchant website's own situation. You can only set up to 10 items //The sum of each share amount must be less than or equal to total_fee //The format of the commission information set is: Email_1^Amount 1^Remark 1|Email_2^Amount 2^Remark 2 //For example: //royalty_type = "10" //royalty_parameters = "[email protected]^0.01^Remark 1|[email protected]^0.01^Remark 2" //The 1h set before will return //Error description: Sorry, the merchant does not have the custom timeout permission to be enabled, please contact your merchant. //Error code: SELF_TIMEOUT_NOT_SUPPORT it_b_pay=""; //Constructor, generate 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" cellpadding="5" cellpacing="0"> <tr> <td align="center" colspan="2">Order confirmation</td> </tr> <tr> <td align="right">Order number: </td> <td align="left"><%=out_trade_no%></td> </tr> <tr> <td align="right">Total payment amount: </td> <td align="left"><%=total_fee%></td> </tr> <tr> <td align="center" colspan="2"><%=sHtmlText%></td> </tr> </table> </body> </html>Interface to Alipay callback: 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; //…The get and set methods are omitted here…………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………… 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) { //The logic code for processing order is omitted here……………… } } //After the callback is successful, return SUCCESS to Alipay and return SUCCESS; } return "failure"; } }In this way, Alipay's third-party instant account arrival interface is implemented.
The above is the Java implementation of Alipay's third-party Alipay instant payment function that I introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!