Este artículo comparte información relevante sobre el pago de JSAPI + envío de mensajes de plantilla para su referencia. El contenido específico es el siguiente
1. Herramientas
Consulte la categoría de herramienta: Versión de WeChat Pay Java del pago nativo
2. Configuración de cuenta pública
3. Implementación del código
OpenID: OpenID es la indicación única entre el usuario y la cuenta pública. Las siguientes clases implican generar tokens, cerrar llamadas a la interfaz de orden, obtener información de archivo de configuración y clases de herramientas. Hay implementaciones de código específicas en otros artículos.
paquete 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; importar; 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.sf.json.jen org.apache.http.httpentity; importar org.apache.http.client.methods.closablehttttpesponse; import org.apache.http.client.methods.httppost; import org.apache.http.conn.ssl.sslconnectionsockory; import org.apache.http.conn.ssl.sslcontexts; import org.apache.htttp.entity.stringEntity; import org.apache.http.impl.client.ClosEable org.apache.http.util.entityUtils; import org.dom4j.document; import org.dom4j.documenthelper; import org.dom4j.element; import org.dom4j.io.SaxReader; import og.springfframework.beanss.factory.annotation.autewired; import org. 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.service.getweixinaccesstokenservice; import com.zhrd.bussinss.platform.service.weixinpayservice; import com.zhrd.bussinss.platform.utils.customizedPropertyPlaceHolderConfigurer; import com.zhrd.bussinss.platform.weixinpayutils.clientcustomssl;@bestController@requestmapping ("/rev/weixinsendMessage") Public ClassAxinSendMessenSenSenControllaRolla WeixinPayservice; @AUtowired getWeixinAccessTokenService getWeixinAccessTokenService; Standard Standard, estática privada = 1662652800000L; /** * wechat Enviar mensaje * @param Solicitud * @param Respuesta * @return */@RequestMapping (valor = "/weixinsend", método = requestmethod.get) @ResponseBody Public Object weixinsend (httpservletRequest request, httpServletResponse respuesta, string ordenno, string openId) { System.out.println ("================================================ =================================================================== =================================================================== ===================================================================== =================================================================== =================================================================== =================================================================== ===================================================================== CustomizeSpropertyStolderConfigurer.getContextProperty ("Wx.cert"). ToString ()); SslContexts.custom (). LoadKeMaterial (KeyStore, "10061401" .ToCarArray ()). Build (); // Permitir el protocolo tlsv1 solo sslconnectionsocketFactory sslsf = new sslConnectionsocketFactory (sslContext, new String [] {"tlsv1"}, null, sslconnectionsocketfactory.how_all_hostname_verifier); ClosableHttpClient httpClient = httpclients.custom () .setsslsocketFactory (sslsf) .build (); // httpget httpget = new // httpget ("https://api.mch.weixin.qq.com/secapi/pay/refund"); // Para obtener detalles sobre cómo obtener token, consulte el artículo sobre cómo obtener token httppost httppost = new httppost ("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+getweixinaccesstokenservice.accessToke ()); Choque pay ph = nulo; List <map <string, object >> td = weixInpayservice.getTrade (ordenno); Fecha dt = nueva fecha (); SimpleDateFormat sdf = new SimpleDateFormat ("yyyymmddhhmmss"); Cadena non -Cestr = sdf.format (dt) .ToString (); Fecha ahora = nueva fecha (); String tradepayno = ordenno+string.format ("%10d", StandardTime - Now.GetTime ()). Subcans (0, 10); System.out.println ("Order OrderNo ===================================================================; número =================== "+String.Format ("%10d ", StandardTime - Now.GetTime ()). Subconsring (0, 10)); String Price = Math.round (Float.ValueOf (TD.GET (0) .get (" Price "). ToString ())*100)+"; "; Long Timeexlold = dtt.getTime () () (). // Para más detalles, consulte el artículo sobre la obtención de la información del archivo de configuración. SimpleFormat dtsdf = new SimpleDateFormat ("YYYYMMDDHMMSS"); System.out.println ("Price =="+Price); JsonObject resultJspay = (jsonObject) getJSpay (Non -Cestr, "Order", TradEpayNo, Price, Non -Cestr, TimeExPire, OpenID); resultadojspay.getString ("prepayId"); System.out.println ("================= 222Prepay_id222 ========================="+resultadojspay.getString ("prepayid"). ToString ()); Lista <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 ("valor", td.get (0) .get ("buyerName")+"(Sr./ms.) Orden"); valueparam.put ("color", "#173177"); Map <string, string> valueparam1 = new Hashmap <String, String> (); valueparam1.put ("valor", ordenno); valueparam1.put ("color", "#173177"); Map <string, string> valueParam2 = new Hashmap <String, String> (); valueparam2.put ("valor", "orden de la comunidad inteligente amor nuevo orden"); valueparam2.put ("color", "#173177"); Map <string, string> valueParam3 = new Hashmap <String, String> (); valueparam3.put ("valor", td.get (0) .get ("precio")+"meta"); valueparam3.put ("color", "#173177"); Map <string, string> valueparam4 = new Hashmap <String, String> (); valueparam4.put ("valor", "esperar el pago"); valueparam4.put ("color", "#173177"); Map <string, string> valueParam5 = new Hashmap <String, String> (); valueparam5.put ("valor", "haga clic para pagar"); valueparam5.put ("color", "#173177"); FirstParam.put ("Primero", ValueParam); FirstParam.put ("Keyword1", ValueParam1); FirstParam.put ("Keyword2", ValueParam2); FirstParam.put ("Keyword3", ValueParam3); FirstParam.put ("Keyword4", ValueParam4); FirstParam.put ("Observación", valueparam5); data.Add (FirstParam); Jspay jp = new JSpay (); jp.settouser (OpenID); jp.settemplate_id ("miexd4-4uqrfmdjnvqmjh0egfypm16r5dpdt6p9gpgg"); jp.settopcolor ("#173177"); jp.seturl ("http: // enlace para configuración de cuenta pública/weixin_jspay/weixinjspay/init.action? paqueteValue ="+resultJspay.getString ("PrepareID"). ToString ()); JP.SetData (datos); JsonObject jsonObject = jsonObject.FromObject (JP); Cadena str = new String (jsonObject.ToString (). GetBytes ("UTF-8"), "ISO8859-1"); // string xml = clientCustomsSl.RefundnativePackage (weixInRefundservice.getTradepayno (OrderNo), Non -CESTR, TotalFee, Reembols, Reembolso, Non -CESTR); try { System.out.println("data============================================================================================== ClientCustomsSl.ReFundnativePackage (weixInRefundservice.getTradepayNo (OrderNo), Non -Cestr. Httpentity entity = ResponseEntry.getEntity (); Len ++; JsonObject.FromObject (nueva cadena (b, 0, len)); ph.SetTradepayUrl (""); ph.SetPayTradeno (OrderNo); ph.SetTradepayno (TradEpayNo); Ph.SetPayStatus (PayHistoryPayStatus.wechat_pay_status_wait); ph.setPayType (PayHistoryPayType.wechat_js_pay); List <Shisthist> payHistList = weixinpayservice.getpayhist (ordenno, "weChat", ""); if (payHistList == null || payHistList.size () == 0) {weixInpayservice.addpayhist (ph); } else {// Para obtener detalles sobre los pedidos de cierre, consulte el artículo sobre la cancelación de pedidos. JsonObject strStatus = (jsonObject) CloseWeixInorderUtils.closeWeixInorder (payHistList.get (0) .getTradepayno ()); if (strstatus.getString ("status"). Equals ("Success")) {System.out.println (ph.getTradepayno ()); weixinpayservice.updatepayhist (ph); }}} Resultado de retorno; } EntityUtils.consume (entidad); } Finalmente {ResponseEntry.Close (); }} finalmente {httpclient.close (); } return null; } catch (Exception e) {E.PrintStackTrace (); JsonObject resultado = new JsonObject (); resultado.put ("estado", "error"); resultado.put ("msg", e.getMessage ()); resultado de retorno; }} Public static Object getJSpay (String Non -Cestr, String OrderDescribe, String OrderNo, String Price, String TimeStart, String TimeExpire, String OpenId) {try {KeyStore KeyStore = KeyStore.getInstance ("PKCS12"); FileInputStream Insteam = new FileInputStream (nuevo archivo (CustomizedPropertyPlaceHolderConfigurer.getContextProperty ("wx.cert"). ToString ())); intente {KeyStore.Load (INSTAÑO, "10061401" .ToCarArray ()); } finalmente {enterTream.close (); } // Confía en su propio CA y todos los certificados autofirmados SSLContext sslContext = sslContexts.custom (). LoadKeMaterial (KeyStore, "Ver correo electrónico" .toCarArray ()). Build (); // Permitir el protocolo tlsv1 solo sslconnectionsocketFactory sslsf = new sslConnectionsocketFactory (sslContext, new String [] {"tlsv1"}, null, sslconnectionsocketfactory.how_all_hostname_verifier); ClosableHttpClient 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"); Cadena xml = ClientCustomsSl.CreateJSapipackage (Non -CESTR, OrderDescribe, OrderNo, Price, TimeStart, TimeExpire, OpenID); intente {StringEntity SE = New StringEntity (xml); httppost.setEntity (SE); System.out.println ("Ejecución de solicitud" + httppost.getRequestline ()); ClosableHttPResponse ResponseEntry = httpclient.execute (httppost); intente {httpentity entity = ResponseEntry.getEntity (); System.out.println ("----------------------------------------"); System.out.println (ResponseEntry.getStatusLine ()); if (entity! = null) {System.out.println ("Longitud de contenido de respuesta:" + entity.getContentLength ()); Saxreader saxreader = new saxreader (); Documento documento = saxreader.read (entity.getContent ()); Elemento rootelt = document.getRootElement (); Documento documentxml = documenthelper.parsetext (xml); Elemento rootEltxml = documentxml.getRootElement (); System.out.println ("nodo raíz:" + rootelt.getName ()); System.out.println ("==="+rootelt.elementText ("result_code")); System.out.println ("==="+rootelt.elementText ("return_msg")); Cadena resultCode = rootElt.ElementText ("result_code"); JsonObject resultado = new JsonObject (); if (resultcode.equals ("éxito")) {System.out.println ("================== PREPAY_ID ====================="+ Rootelt.elementText ("Preparay_id")); resultado.put ("prepayId", rootElt.ElementText ("prepay_id")); resultado.put ("signo", rootEltxml.ElementText ("signo")); resultado.put ("estado", "éxito"); resultado.put ("msg", "éxito"); } else {result.put ("status", "false"); resultado.put ("msg", rootelt.elementText ("err_code_des")); } resultado de retorno; } EntityUtils.consume (entidad); } Finalmente {ResponseEntry.Close (); }} finalmente {httpclient.close (); } return null; } catch (Exception e) {E.PrintStackTrace (); JsonObject resultado = new JsonObject (); resultado.put ("estado", "error"); resultado.put ("msg", e.getMessage ()); resultado de retorno; }}} 4. El código de la capa de control de implementación del código en el proyecto weixin_jspay
paquete com.weixin.jspay.controller; import javax.servlet.http.httpservletRequest; import javax.servlet.http.httpservletResponse; import org.springframework.stereotype.controller; import org.springframe.web.bind.annotation.notation.Requesting; importador; org.springframework.web.bind.annotation.requestmethod;@controler@requestmapping ("/weixinjspay") clase pública weixinjspayController {@RequestMapping (valor = "/init", método = requestmethod.get) public string init (httpservletRequest, httpservletRessessesses PaySign) {System.out.println ("==================== 微信 Jspay 开始 =================="); System.out.println ("paqueteValue ================"+paquete de paquetes); System.out.println ("PaySign ======================"+PaySign); request.setAttribute ("PackageValue", "prepay_id =" + paquete); request.setAttribute ("PaySign", PaySign); System.out.println ("==================== 微信 Jspay 页面跳转开始 ================="); regresar "weixin"; }}
código JSP
<%@ page lenguaje = "java" contentType = "text/html; charset = utf-8" pageEncoding = "utf-8"%> <! DocType html público "-// w3c // dtd html 4.01 transición // en" " "http://www.w3.org/tr/html4/loose.dtd"><html><head><Script type =" text/javaScript "src ="/weixin_jspay/js/md5.js "> </script> <script idioma =" javaScript "> window.onloader = function () {var paquete = = '$ {paquete Value}'; var paySign = '$ {paySign}'; alerta ("paqueteValue ==========="+PackageValue); alerta ("PaySign ==============="+PaySign); VAR SignString = "Appid = Ver cuenta pública & Non -Cestr = Random String & Package ="+PackageValue+"& PaySign ="+PaySign+"& Firmtype = MD5 & Timestamp = Time"; // alerta (firma); var md5signValue = ("" + cryptojs.md5 (firmante)). toupperCase (); // alerta (MD5SignValue); WeixinJSBridge.invoke('getBrandWCPayRequest',{ "appId" : "<span style="font-family: Arial, Helvetica, sans-serif;">See the public account</span>", "timeStamp" : "1395712654", "nonceStr" : "123456", "package" : packageValue, "signType" : "MD5", "PaySign": MD5SignValue}, function (res) {alert (res.err_msg); "get_brand_wcpay_request: cancelar") {alerta ("pago de la cancelación del usuario"); </body> </html>Pago de WeChat MD5.JS: MD5.JS y WeChat Documento de desarrollo de pagos: Dirección de descarga
Este artículo se ha compilado en "Resumen de las habilidades de desarrollo de JavaScript WeChat", y todos son bienvenidos a aprender y leer.
Recomiendo un tutorial sobre los applets de WeChat que están muy preocupados ahora: el editor de "WeChat Mini Program Development Tutorial" lo ha compilado cuidadosamente para todos, espero que les guste.
Lo anterior es todo el contenido de este artículo. Espero que sea útil para el aprendizaje de todos y espero que todos apoyen más a Wulin.com.