This article for everyone to share the Java version of the JSAPI payment + Send template message related information for your reference, the specific content as follows
1. Tool class
Tools class See: Micro-Credit Payment Java version of the native payment
2. Public account setting
3. Code implementation
Openid:openid is the only indication that users are represented between the user and the public account
The following classes involve generating token, closing order interface calls, obtaining configuration file information, and tool classes, which are implemented in other articles with specific code
Package com.zhrd.bussinss.platform.controller.rest;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.InputStream;
Import Java.security.KeyStore;
Import Java.text.SimpleDateFormat;
Import java.util.ArrayList;
Import Java.util.Date;
Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;
Import Javax.net.ssl.SSLContext;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
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.web.bind.annotation.RequestMapping;
Import Org.springframework.web.bind.annotation.RequestMethod;
Import Org.springframework.web.bind.annotation.ResponseBody;
Import Org.springframework.web.bind.annotation.RestController;
Import Com.zhrd.bussinss.platform.bo.JsPay;
Import com.zhrd.bussinss.platform.bo.PayHist;
Import Com.zhrd.bussinss.platform.constants.PayHistoryPayStatus;
Import Com.zhrd.bussinss.platform.constants.PayHistoryPayType;
Import Com.zhrd.bussinss.platform.service.GetWeiXinAccessTokenService;
Import Com.zhrd.bussinss.platform.service.WeiXinPayService;
Import Com.zhrd.bussinss.platform.utils.CloseWeiXinOrderUtils;
Import Com.zhrd.bussinss.platform.utils.CustomizedPropertyPlaceholderConfigurer;
Import Com.zhrd.bussinss.platform.weixinPayUtils.ClientCustomSSL; @RestController @RequestMapping ("/rest/weixinsendmessage") public class WeixinsendmessageRestfulcontroller {@Autowired Weixinpayservice weixinpayservice;
@Autowired Getweixinaccesstokenservice Getweixinaccesstokenservice;
private static long standardtime = 1662652800000L; /** * @param Request * @param response * @return * * @RequestMapping (value= "/weixinsend", Method=requestmetho D.get) @ResponseBody public Object weixinsend (httpservletrequest request,httpservletresponse response,string OrderNo, String openId) {System.out.println ("========================== Send message start ========================" +
Getweixinaccesstokenservice.accesstoken ());
try{KeyStore KeyStore = keystore.getinstance ("PKCS12"); FileInputStream instream = new FileInputStream (New File (Customizedpropertyplaceholderconfigurer.getcontextproperty (
"Wx.cert"). toString ());
try {keystore.load (instream, see Mail). ToCharArray ());
}finally {instream.close (); }//Trust own CA and all self-signed certs sslcontext sslcontext = Sslcontexts.custom (). Loadkeymaterial (KeyStore, "10 061401 ". ToCharArray ()). build (); Allow TLSV1 protocol only sslconnectionsocketfactory SSLSF = new Sslconnectionsocketfactory (Sslcontext, new string[]
{"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"); Get token See get token article HttpPost HttpPost = new HttpPost ("Https://api.weixin.qq.com/cgi-bin/message/template/send?").
Access_token= "+getweixinaccesstokenservice.accesstoken ());
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 = Orderno+string.format ("%10d", Standardtime-now.gettime ()). substring (0, 10); System.out.println ("Order marking orderno=======" +orderno);
System.out.println ("10-bit random number =======" +string.format ("%10d", Standardtime-now.gettime ()). substring (0, 10));
String Price = Math.Round (float.valueof (td.get (0). Get ("price"). ToString ()) *100) + ""; Long timeexpirestrold = Dt.gettime (); Get profile information see the article getting profile information 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==" +orderno);
System.out.println ("price==" +price);
System.out.println ("timestart==" +noncestr);
System.out.println ("timeexpire==" +timeexpire);
Jsonobject Resultjspay = (jsonobject) getjspay (noncestr, "orders", Tradepayno, Price, Noncestr,timeexpire,openid);
Resultjspay.getstring ("Prepayid"); System.out.prIntln ("================222prepay_id222=========================" +resultjspay.getstring ("PrepayId"). ToString ())
; list<map<string,map<string,string>>> data = new arraylist<map<string,map<string,string
>>> ();
map<string,map<string,string>> Firstparam = new hashmap<string, map<string,string>> ();
map<string,string> Valueparam = new hashmap<string, string> ();
Valueparam.put ("Value", Td.get (0). Get ("buyername") + "(Sir/ms) Order");
Valueparam.put ("Color", "#173177");
map<string,string> valueParam1 = new hashmap<string, string> ();
Valueparam1.put ("value", orderNo);
Valueparam1.put ("Color", "#173177");
map<string,string> valueParam2 = new hashmap<string, string> ();
Valueparam2.put ("Value", "Intelligent community love Fresh Orders");
Valueparam2.put ("Color", "#173177");
map<string,string> valueParam3 = new hashmap<string, string> ();
Valueparam3.put ("Value", Td.get (0). Get ("price") + "Yuan"); Valueparam3.put ("Color"),"#173177");
map<string,string> valueParam4 = new hashmap<string, string> ();
Valueparam4.put ("value", "Waiting to pay");
Valueparam4.put ("Color", "#173177");
map<string,string> VALUEPARAM5 = new hashmap<string, string> ();
Valueparam5.put ("Value", "click to pay");
Valueparam5.put ("Color", "#173177");
Firstparam.put ("A", valueparam);
Firstparam.put ("Keyword1", valueParam1);
Firstparam.put ("Keyword2", valueParam2);
Firstparam.put ("Keyword3", VALUEPARAM3);
Firstparam.put ("Keyword4", VALUEPARAM4);
Firstparam.put ("Remark", VALUEPARAM5);
Data.add (Firstparam);
Jspay JP = new Jspay ();
Jp.settouser (OPENID);
jp.settemplate_id ("Miexd4-4uqrfmdjnvqmjh0egfypm16r5dpdt6p9gpgg");
Jp.settopcolor ("#173177"); Jp.seturl ("http://Public account Settings link/weixin_jspay/weixinjspay/init.action?packagevalue=" +resultjspay.getstring ("
Prepayid "). toString ());
Jp.setdata (data);
Jsonobject jsonobject = jsonobject.fromobject (JP); String str = new String (jsonobject.tostring (). GetBytes ("Utf-8"), "iso8859-1 "); String XML = Clientcustomssl.refundnativepackage (Weixinrefundservice.gettradepayno (orderNo), Noncestr,totalfee,
REFUNDFEE,NONCESTR);
try {System.out.println ("data==========" +str.tostring ());
Stringentity se = new stringentity (str.tostring (). replace ("[", ""). Replace ("]", ""). toString ());
Httppost.setentity (SE);
SYSTEM.OUT.PRINTLN ("Executing request" + httppost.getrequestline ());
Closeablehttpresponse responseentry = Httpclient.execute (HttpPost);
try {httpentity entity = responseentry.getentity ();
InputStream in = Entity.getcontent ();
byte b[] = new byte[1024];
int len = 0; int temp=0;
All read content uses the TEMP receive while ((Temp=in.read ())!=-1) {//continues to read the b[len]= (byte) temp When the reading is not finished;
len++;
} in.close ();
System.out.println (New String (B,0,len));
if (entity!= null) {System.out.println ("Response Content Length:" + entity.getcontentlength ());
System.out.println ("= =" +responseentry.getentity (). toString ()); Jsonobject result = JsonobjEct.fromobject (New String (B,0,len));
if (result.getstring ("ErrMsg"). Equals ("OK")) {ph = new payhist ();
Ph.settradepayurl ("");
Ph.setpaytradeno (OrderNo);
Ph.settradepayno (Tradepayno);
Ph.setpaystatus (payhistorypaystatus.wechat_pay_status_wait);
Ph.setpaytype (Payhistorypaytype.wechat_js_pay);
list<payhist> payhistlist = weixinpayservice.getpayhist (OrderNo, "WeChat", "");
if (payhistlist = null | | payhistlist.size () = = 0) {weixinpayservice.addpayhist (ph); }else{//Close orders see the cancellation article Jsonobject strstatus = (jsonobject) closeweixinorderutils.closeweixinorder (payhistlist.ge
T (0). Gettradepayno ());
if (strstatus.getstring ("status"). Equals ("Success")) {System.out.println (Ph.gettradepayno ());
Weixinpayservice.updatepayhist (ph);
}} 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; } public static Object Getjspay (String noncestr,string orderdescribe,string orderno,string price,string Timestar
T,string timeexpire,string openId) {try{KeyStore KeyStore = keystore.getinstance ("PKCS12"); FileInputStream instream = new FileInputStream (New File (Customizedpropertyplaceholderconfigurer.getcontextproperty (
"Wx.cert"). toString ());
try {keystore.load (instream, "10061401". ToCharArray ());
}finally {instream.close (); }//Trust own CA and all self-signed certs sslcontext sslcontext = Sslcontexts.custom (). Loadkeymaterial (KeyStore, "See Mail
Pieces ". ToCharArray ()). build (); Allow TLSV1 protocol only sslconnectionsocketfactory SSLSF = new Sslconnectionsocketfactory (Sslcontext, new string[]
{"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.createjsapipackage (Noncestr,orderdescribe,orderno,price,timestart,timeexpire,openid)
;
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 ());
Saxreader Saxreader = new Saxreader ();
Document document = Saxreader.read (Entity.getcontent ());
Element Rootelt = Document.getrootelement ();
Document documentxml =documenthelper.parsetext (XML); Element Rooteltxml = documentxml.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 (); if (Resultcode.equals ("SUCCESS")) {System.out.println ("=================prepay_id====================" +
Rootelt.elementtext ("prepay_id"));
Result.put ("Prepayid", Rootelt.elementtext ("prepay_id"));
Result.put ("Sign", Rooteltxml.elementtext ("sign"));
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;
}
}
}
Code implementation in 4.weixin_jspay projects;
Control layer code
Package Com.weixin.jspay.controller;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import Org.springframework.stereotype.Controller;
Import org.springframework.web.bind.annotation.RequestMapping;
Import Org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping ("/weixinjspay") public class Weixinjspaycontroller {@RequestMapping (value = "/init"), Meth OD = requestmethod.get) public String init (httpservletrequest request,httpservletresponse response,string packageValue
, String paysign) {System.out.println ("=================== micro-letter Jspay start =================");
System.out.println ("packagevalue===============" +packagevalue);
System.out.println ("paysign=====================" +paysign);
Request.setattribute ("Packagevalue", "prepay_id=" + packagevalue);
Request.setattribute ("Paysign", paysign);
SYSTEM.OUT.PRINTLN ("=================== micro-letter Jspay page Jump start =================");
return "Weixin";
}
}
jsp Code
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" Utf-8 "%> <!
DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
Micro-credit Payment MD5.js:md5.js and micro-credit payment development document: Download address
This article has been organized into the "JavaScript micro-Credit Development Skills Summary", welcome to learn to read.
For everyone to recommend now more attention than the micro-letter Program Tutorial: "Micro-letter Small Program Development tutorial" Small series for everyone carefully organized, hope like.
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.