In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
Java how to achieve Wechat jsApi payment, I believe that many inexperienced people do not know what to do, so this article summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.
Notes: 1. Payment must be made in Wechat's built-in browser; 2. Openid must be obtained; 3. To obtain code, you must request the backend server to get the code, and then request to obtain the openid, and store the openid in the session of your own server.
I. account preparation
1. Set up a service number on Wechat public platform and pay RMB 300 for authentication (only enterprises can open it) to obtain appid, register a Super Admin on WeChat Pay merchant platform and pay 300 for certification, and obtain mch_id (merchant id).
2. Obtain appid,appsecret on Wechat public platform. Obtain API key (paternerKey) in obtaining mch_id,api security on merchant platform
II. Platform configuration
1. Merchant platform: product center development configuration, which belongs to the payment page
2. Public platform: set the account details function and configure the authorized domain name on the web page. (put the txt file in the first-level domain name and directory, which can be accessed through the domain name / txt (full name of the file) to test whether txt content can be obtained. If not, configure the domain name to access the directory with nginx)
3, public platform: development, basic settings, configure server address (need to write interface and return echostr, verify server), token write casually, message key (randomly generated), encryption mode: compatible mode.
Third, develop (download javasdk. Import the utility classes from Wechat into https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=11_1)
1. Obtain basic parameters before payment
/ * request to open the page in Wechat * / @ RequestMapping (value = "/ toJob") public String toJob (HttpServletResponse response) {String appId = WxConstants.APPID; String tologin = redirectURL; return "redirect: https://open.weixin.qq.com/connect/oauth3/authorize?appid="+appId+"&redirect_uri="+tologin+"&response_type=code&scope=snsapi_base#wechat_redirect"; } stop * * Wechat requests to open a page to be redirected to this API, get code * and then redirect to its own page * / @ RequestMapping (value = "/ tologin") public String tologin (String code, HttpServletResponse response) {return "redirect:" + loginUrl+code } / * get openid * / @ RequestMapping ("/ getOpenId") @ ResponseBody public String getOpenId (@ RequestParam ("code") String code,HttpServletRequest request) {logger.info ("code code:" + code); Map result = new HashMap (); / / Page get openId interface String getopenid_url = "https://api.weixin.qq.com/sns/oauth3/access_token";" Map param = new HashMap (); param.put ("appid", WxConstants.APPID); param.put ("secret", WxConstants.SECRET); param.put ("code", code); param.put ("grant_type", "authorization codes"); / / send a get request to the Wechat server to get openIdStr String openIdStr = HttpClientUtil.doGet (getopenid_url, param) JSONObject jsonObject = JSON.parseObject (openIdStr); logger.info ("opendID JSON:" + openIdStr); String openid = jsonObject.getString ("openid"); / / store openid in session. / / if you redirect to this API directly, the openid will not be stored in the session, but will only be stored in Tencent's session / / Wechat. The opening page can only request the backend API, and the backend can get the code and / / the foreground to get the code and then request the API to obtain the openid. You can store the openid in our own server request.getSession () .setAttribute ("openid", openid). / / return to the login page return openid;} / * Wechat test interface * @ param request * @ return * / @ RequestMapping ("/ Token") @ ResponseBody public String Token (HttpServletRequest request) {logger.info (JSON.toJSONString (request.getParameterMap (); return request.getParameter ("echostr");}
2. Payment and callback
/ * * resume WeChat Pay * @ param request * @ param isUpdate is a certified order * / @ RequestMapping (value = "/ wxPayJob") @ ResponseBody public Map wxpay (HttpServletRequest request, @ RequestParam ("isUpdate") Integer isUpdate, @ RequestParam ("jobUserId") Long jobUserId @ RequestParam ("totalAmount") String totalAmount) {String openId = (String) request.getSession () .getAttribute ("openid") Logger.info ("opendID pay:" + openId); / / get openId String ip = WxUtils.getIpAddress (request); / / convert meta to String totalFee = AmountUtils.changeY2F (totalAmount); Map result = wxService.orderPayment (openId, ip, totalFee, jobUserId, isUpdate); return result @ param request * @ param response * @ return * / @ RequestMapping (value = "/ wxPayJobNotify") @ ResponseBody public String wxPayJobNotify (HttpServletRequest request, HttpServletResponse response) {InputStream is = null; try {is = request.getInputStream () / / get the requested stream information (here is the xml format sent by Wechat, so you can only use streams to read) String xml = IOUtils.toString (is, "utf-8"); Map notifyMap = WXPayUtil.xmlToMap (xml) / transfer the xml sent by Wechat to map if (notifyMap.get ("return_code"). Equals ("SUCCESS")) {if (notifyMap.get ("result_code"). Equals ("SUCCESS")) {String orderNum = notifyMap.get ("out_trade_no"); / / merchant order number String amountpaid = notifyMap.get ("total_fee") / / order amount actually paid: String amount = AmountUtils.changeF2Y (amountpaid); / / String openid = notifyMap.get ("openid"); / / get / / String trade_type = notifyMap.get ("trade_type") if necessary / / modify the authentication status, order status jobOrderDtoService.updateState (orderNum);}} / / tell Wechat server to receive the message and do not call callback action again = it is important to reply to Wechat server information by sending a xml () .write ("") Is.close ();} catch (Exception e) {e.printStackTrace ();} return null;}
3. The payment uniformly issues the order subject
/ / WeChat Pay-Asynchronous callback (API: payForOrder) @ Value (value = "${WxConfig.wxJObNotifyUrl}") private String wxJObNotifyUrl; / * call WeChat Pay * / @ Override public Map orderPayment (String openId, String ip, String totalAmount, Long jobUserId, Integer isUpdate) {Map payMap = new HashMap (); try {String OrderNum = OrderNumUtil.outtradeno ("JOB") String body = "Certification"; Map mapBody = setSortedMap (openId,OrderNum,body,totalAmount,ip); String xml = WXPayUtil.mapToXml (mapBody); / / convert all parameters (map) to xml format / / Unified order String unifiedorder_url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; / / send post request "Unified order issuing API" returns prepaid id:prepay_id Map xmlMap = new HashMap (); xmlMap.put ("xml", xml); String xmlStr = HttpClientUtil.doPostJson (unifiedorder_url, xml); / / return json data of front-end page payMap = resultMap (xmlStr) / / insert resume order} catch (Exception e) {e.printStackTrace ();} return payMap } / * issuing order subject information * / public Map setSortedMap (String openId,String OrderNum,String body,String totalFee,String ip) throws Exception {/ / splicing unified order issuing address parameter Map paraMap = new HashMap (); paraMap.put ("appid", WxConstants.APPID); paraMap.put ("body", body); paraMap.put ("mch_id", WxConstants.MCHID) ParaMap.put ("nonce_str", WXPayUtil.generateNonceStr ()); / generate uuID paraMap.put ("openid", openId); paraMap.put ("out_trade_no", OrderNum); / / order number paraMap.put ("spbill_create_ip", ip); paraMap.put ("total_fee", totalFee); / / amount unit paraMap.put ("trade_type", WxConstants.WX_TRADE_JSAPI) ParaMap.put ("notify_url", wxJObNotifyUrl); / / this path is the path where Wechat server calls payment result notification: String sign = WXPayUtil.generateSignature (paraMap, WxConstants.KEY); paraMap.put ("sign", sign); return paraMap } / * return the json data of the front page * / public Map resultMap (String xmlStr) throws Exception {Map json = WXPayUtil.xmlToMap (xmlStr); / / JSONObject json = JSONObject.parseObject (xmlStr); / / convert to Json format LOGGER.info ("prepay_id JSON:" + json); / / get prepay_id String prepay_id = json.get ("prepay_id") / / prepaid id if (xmlStr.indexOf ("SUCCESS")! =-1) {Map map = WXPayUtil.xmlToMap (xmlStr); prepay_id = (String) map.get ("prepay_id");} Map payMap = new HashMap (); payMap.put ("appId", WxConstants.APPID); payMap.put ("timeStamp", WXPayUtil.getCurrentTimestamp () + "") PayMap.put ("nonceStr", WXPayUtil.generateNonceStr ()); payMap.put ("signType", "MD5"); payMap.put ("package", "prepay_id=" + prepay_id); String paySign = WXPayUtil.generateSignature (payMap, WxConstants.KEY); payMap.put ("paySign", paySign); return payMap;}
4. Tool class:
Yuan-to-yuan
Public class AmountUtils {/ * * format of amount in minutes * / public static final String CURRENCY_FEN_REGEX = "\\ -? [0-9] +" / * convert the units to meta and return the string in amount format (except 100) * * @ param amount * @ return * @ throws Exception * / public static String changeF2Y (Long amount) throws Exception {if (! amount.toString (). Matches (CURRENCY_FEN_REGEX)) {throw new Exception ("incorrect amount format") } int flag = 0; String amString = amount.toString (); if (amString.charAt (0) = ='-') {flag = 1; amString = amString.substring (1);} StringBuffer result = new StringBuffer (); if (amString.length () = = 1) {result.append ("0.0") .append (amString) } else if (amString.length () = = 2) {result.append ("0.") .append (amString);} else {String intString = amString.substring; for (int item1; I = 3) {amLong = Long.valueOf ((currency.substring (0, index+3)). Replace (".", ") } else if (length-index = = 2) {amLong = Long.valueOf ((currency.substring (0, index+2)). Replace (".", ") + 0);} else {amLong = Long.valueOf ((currency.substring (0, index+1)). Replace (". ",") + "00");} return amLong.toString () } public static void main (String [] args) {/ / try {/ / System.out.println ("result:" + changeF2Y ("- 000a00")); / /} catch (Exception e) {/ / System.out.println ("- > >" + e.getMessage ()); / return e.getErrorCode () / /} / / System.out.println ("result:" + changeY2F ("1.00000000001E10")); System.out.println (AmountUtils.changeY2F ("1.33")); try {System.out.println (AmountUtils.changeF2Y ("1322"));} catch (Exception e) {e.printStackTrace () } / / System.out.println (Long.parseLong (AmountUtils.changeY2F ("1000000000000000); / / System.out.println (Integer.parseInt (AmountUtils.changeY2F (" 10000000 "); / / System.out.println (Integer.MIN_VALUE); / / long a = 0 System.out.println / System.out.println (a);}}
Http doPost doGet request
Import org.apache.http.NameValuePair;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.ContentType;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils Import java.io.IOException;import java.net.URI;import java.util.ArrayList;import java.util.List;import java.util.Map;public class HttpClientUtil {public static String doGet (String url, Map param) {/ / create Httpclient object CloseableHttpClient httpclient = HttpClients.createDefault (); String resultString = ""; CloseableHttpResponse response = null Try {StringBuilder sb = new StringBuilder (url+ "?"); for (String key: param.keySet ()) {sb.append (key+ "=" + param.get (key) + "&") } sb.deleteCharAt (sb.length ()-1); URI uri = new URI (sb.toString ()); / / create http GET request HttpGet httpGet = new HttpGet (uri) / / execute the request response = httpclient.execute (httpGet); / / determine whether the returned status is 200if (response.getStatusLine (). GetStatusCode () = = 200) {resultString = EntityUtils.toString (response.getEntity (), "UTF-8") }} catch (Exception e) {e.printStackTrace ();} finally {try {if (response! = null) {response.close () } httpclient.close ();} catch (IOException e) {e.printStackTrace ();}} return resultString } public static String doGet (String url) {return doGet (url, null);} public static String doPost (String url, Map param) {/ / create Httpclient object CloseableHttpClient httpClient = HttpClients.createDefault (); CloseableHttpResponse response = null; String resultString = "" Try {/ / create HttpPost request HttpPost httpPost = new HttpPost (url); / / create parameter list if (param! = null) {List paramList = new ArrayList () For (String key: param.keySet ()) {paramList.add (new BasicNameValuePair (key, param.get (key);} / / Simulation form UrlEncodedFormEntity entity = new UrlEncodedFormEntity (paramList) HttpPost.setEntity (entity);} / execute http request response = httpClient.execute (httpPost); resultString = EntityUtils.toString (response.getEntity (), "utf-8") } catch (Exception e) {e.printStackTrace ();} finally {try {response.close () } catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace ();}} return resultString } public static String doPost (String url) {return doPost (url, null);} public static String doPostJson (String url, String json) {/ / create Httpclient object CloseableHttpClient httpClient = HttpClients.createDefault (); CloseableHttpResponse response = null; String resultString = "" Try {/ / create HttpPost request HttpPost httpPost = new HttpPost (url); / / create request content StringEntity entity = new StringEntity (json, ContentType.APPLICATION_JSON); httpPost.setEntity (entity) / execute http request response = httpClient.execute (httpPost); resultString = EntityUtils.toString (response.getEntity (), "utf-8");} catch (Exception e) {e.printStackTrace () } finally {try {response.close ();} catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace () }} return resultString;}}
Wechat tool class
Import com.alibaba.fastjson.JSON;import org.apache.commons.lang3.StringUtils;import org.dom4j.Document;import org.dom4j.DocumentHelper;import org.dom4j.Element;import javax.servlet.http.HttpServletRequest;import java.util.*;public class WxUtils {/ / request xml assembly public static String getRequestXml (Map parameters) {StringBuffer sb = new StringBuffer (); sb.append ("); Set es = parameters.entrySet (); Iterator it = es.iterator () While (it.hasNext ()) {Map.Entry entry = (Map.Entry) it.next (); sb.append ("+ entry.getValue () +");} sb.append ("); return sb.toString () } / * Random string generation * / public static String getRandomString (int length) {/ / length represents the length of the generated string String base = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Random random = new Random (); StringBuffer sb = new StringBuffer (); for (int I = 0; I
< length; i++) { int number = random.nextInt(base.length()); sb.append(base.charAt(number)); } return sb.toString(); } /** * 将xml格式的字符串转换成Map对象 * * @param xmlStr xml格式的字符串 * @return Map对象 * @throws Exception 异常 */ public static Map xmlStrToMap(String xmlStr) throws Exception { if(StringUtils.isEmpty(xmlStr)) { return null; } Map map = new HashMap(); //将xml格式的字符串转换成Document对象 Document doc = DocumentHelper.parseText(xmlStr); //获取根节点 Element root = doc.getRootElement(); //获取根节点下的所有元素 List children = root.elements(); //循环所有子元素 if(children != null && children.size() >0) {for (int I = 0; I < children.size (); iTunes +) {Element child = (Element) children.get (I); map.put (child.getName (), child.getTextTrim ());}} return map;} public static T xmlStrToBean (String xmlStr, Class clazz) throws InstantiationException, IllegalAccessException {T obj = clazz.newInstance () Try {/ / convert data in xml format into Map objects Map map = xmlStrToMap (xmlStr); / / convert data from map objects to Bean objects obj = JSON.parseObject (JSON.toJSONString (map), clazz);} catch (Exception e) {e.printStackTrace ();} return obj } public static String getIpAddress (HttpServletRequest request) {String ip = request.getHeader ("x-forwarded-for"); if (ip = = null | | ip.length () = = 0 | | "unknown" .equals IgnoreCase (ip)) {ip = request.getHeader ("Proxy-Client-IP") } if (ip = = null | | ip.length () = = 0 | | "unknown" .equalsIgnoreCase (ip)) {ip = request.getHeader ("WL-Proxy-Client-IP");} if (ip = = null | | ip.length () = = 0 | | "unknown" .equalsIgnoreCase (ip)) {ip = request.getHeader ("HTTP_CLIENT_IP") } if (ip = = null | | ip.length () = = 0 | | "unknown" .equalsIgnoreCase (ip)) {ip = request.getHeader ("HTTP_X_FORWARDED_FOR");} if (ip = = null | | ip.length () = = 0 | | "unknown" .equalsIgnoreCase (ip)) {ip = request.getRemoteAddr ();} return ip;}}
Wechat constant class
Public class WxConstants {/ / Wechat uniformly issues an order request xml parameter public static final String APPID= "wx1111111"; / / appid is the unique ID public static final String MCHID= "111111" of Wechat public account or open platform APP; / / after the merchant applies for WeChat Pay, the merchant collection account assigned by WeChat Pay is public static final String SECRET= "aaaaaaaa"; / / AppSecret is the interface password public static final String KEY= "1111111111" corresponding to APPID. / / the signed key generated by the transaction process is the same as the API key public static final String NONCE_STR= "nonce_str"; public static final String SIGN= "sign"; / / generate signature public static final String ATTACH= "attach"; public static final String TIMESTAMP = "timeStamp"; public static final String NONCESTR = "noncestr"; public static final String PREPAYID = "prepayid"; public static final String PARTNERID = "111111"; / / API key public static final String PACKAGE = "package" Public static final String OPENID = "OPENID"; / / unique identification of the user public static final int getHttpConnectTimeoutMs = 8000 / connection time public static final int getHttpReadTimeoutMs = 10000; / / timeout / * Wechat JSAPI pay (or Mini Program pay) Web page payment called in Wechat * / public static final String WX_TRADE_JSAPI = "JSAPI" * Wechat Native pay * / public static final String WX_TRADE_NATIVE = "NATIVE"; / * * Wechat H5 payment * / public static final String WX_TRADE_MWEB = "MWEB"; / * * Wechat app payment * / public static final String WX_TRADE_APP = "APP" } after reading the above, have you mastered how java implements Wechat jsApi payment? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.