Este artigo compartilha informações relevantes sobre o JSAPI Payment + Enviar Model Messply para sua referência. O conteúdo específico é o seguinte
1. Ferramentas
Veja a categoria da ferramenta: WeChat Pay Java Versão do pagamento nativo
2. Configurações de conta pública
3. Implementação de código
OpenId: OpenId é a indicação única entre o usuário e a conta pública. As classes a seguir envolvem geração de tokens, encerramento de chamadas de interface da ordem, obtenção de informações de arquivo de configuração e classes de ferramentas. Existem implementações específicas de código em outros artigos.
pacote com.zhrd.bussins.platform.controller.rest; importar java.io.file; importar java.io.fileInputStream; importar java.io.inputStream; import java.Security.Keystore; import java.Text.simpledEformat; 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; importar org.apache.http.client.methods.closeablehttpResponse; importar org.apache.http.client.methods.httppost; importar org.httpacy.conn.methods.sslconnções; org.apache.http.conn.sssl.sslcontexts; importar org.apache.http.entity.stringentity; importar org.apache.http.impl.client.closeablehttpclient; import orgache.httpache.impl.clienthttpclents; org.apache.http.util.entityutils; importar org.dom4j.document; importar org.dom4j.documentHelper; importar org.dom4j.Element; importação org.dom4j.io.saxreader; importar org.springframework.BeanS.Factory.AnTation.autador; org.springframework.web.bind.annotation.requestmapping; importar org.springframework.web.bind.annotation.requestmethod; importação org.springframework.web.bind.annotion.Responsoody; Import.scringframework.web.bind.annotionsensonsone; com.zhrd.bussins.platform.bo.jspay; importar com.zhrd.bussins.platform.bo.payhist; importar com.zhrd.bussins.platform.constants.payhistoryPaystatus; import.zhrd.buss.Plform.Constays.ConstayPayStatus; Import.zhrd.buss.Plform.Coções com.zhrd.bussins.platform.service.getweixinAcssTokenservice; importar com.zhrd.bussins.platform.service.weixinPayService; importar com.zhrd.bussins.platform.utils.closewixordetils; importa 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; Padrão de longo prazo estático privado = 1662652800000L; /** * WeChat Enviar mensagem * @param request * @param Resposta * @return */@requestMapping (value = "/weixinsend", método = requestMethod.get) @ResponseBody Public Object Weixinsend (httpsVleTleTreQuest Solicitação, htpServletResponse Resposta, string Ordemno, abeto) {Solicitação HttTleTleQuest, htpsVletRespovem System.out.println ("============================================== ==================================================================== ==================================================================== ===================================================================== ==================================================================== ==================================================================== ==================================================================== ===================================================================== Personalizado PropertyPlateHoldConfigurer.getContextProperty ("WX.CERT"). ToString ())); SslContexts.custom (). Loadkeymaterial (Keystore, "10061401" .toCharArray ()). Build (); // Permitir apenas o protocolo TLSV1 SSLConnectionSocketFactory SSLSF = new SSLConnectionSocketFactory (SSLContext, new String [] {"TLSV1"}, NULL, SSLConnectionSocketFactory.allow_all_Hostname_Verifier); ClosableHttpClient httpClient = httpClients.custom () .SetsSlSocketFactory (sslsf) .build (); // httpget httpget = new // httpget ("https://api.mch.weixin.qq.com/secapi/pay/refund"); // Para obter detalhes para obter token, consulte o artigo sobre como obter token httppost httppost = new httppot ("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+getwixinacctice.acctonactkesk "+getwixinaccesstokston/template/send?acss_token="+getwixinacctto Payhist pH = nulo; Lista <map <string, objeto >> td = weixInPayService.gettrade (orderno); Data dt = new Date (); SimpledateFormat sdf = new SimpleDateFormat ("yyyymmddhhmmss"); String noncestr = sdf.format (dt) .toString (); Data agora = new date (); String tradePayno = orderno+string.format ("%10d", StandardTime - agora.getTime ()). Substring (0, 10); System.out.println ("Pedido Rótulo OrderNo ============================================================; número ==================== "+String.Format ("%10D ", StandardTime - agora.getTime ()). Consulte o Artigo sobre a obtenção de informações sobre o arquivo de configuração. SimpletateFormat ("Yyyymmddhhmms"); System.out.println ("timestart =="+não -cest); JsonObject ResultJSPay = (JsonObject) getJSPay (não -cest, "Ordem", TradePayno, Price, Non -Cest, TimeExpire, OpenID); resultadojspay.getString ("pré -condyID"); System.out.println ("================= 222Prepay_ID222 =========================="+ResultJspay.GetString ("Pdayid"). Tostring ()); List <map <string, map <string, string >>> data = new ArrayList <map <string, map <string, string >>> (); Mapa <string, mapa <string, string >> primeiroparam = new hashmap <string, mapa <string, string >> (); Mapa <string, string> valueparam = new hashmap <string, string> (); valueparam.put ("value", td.get (0) .get ("Buyername")+"(Mr./ms.) Ordem"); valueparam.put ("color", "#173177"); Mapa <string, string> valueparam1 = new hashmap <string, string> (); valueparam1.put ("value", orderno); valueparam1.put ("color", "#173177"); Mapa <string, string> valueparam2 = new hashmap <string, string> (); valueparam2.put ("valor", "comunidade inteligente adora ordem nova"); valueparam2.put ("color", "#173177"); Mapa <string, string> valueparam3 = novo hashmap <string, string> (); valueparam3.put ("value", td.get (0) .get ("price")+"meta"); valueparam3.put ("color", "#173177"); Mapa <string, string> valueparam4 = new hashmap <string, string> (); valueparam4.put ("valor", "aguarde pelo pagamento"); valueparam4.put ("color", "#173177"); Mapa <string, string> valueparam5 = new hashmap <string, string> (); valueparam5.put ("value", "clique para pagar"); valueparam5.put ("color", "#173177"); FirstParam.put ("Primeiro", Valueparam); FirstParam.put ("Keyword1", valueparam1); FirstParam.put ("Keyword2", valueparam2); FirstParam.put ("Keyword3", valueparam3); FirstParam.put ("Keyword4", valueparam4); FirstParam.put ("Observação", Valueparam5); data.add (FirstParam); JSPAY JP = novo JSPAY (); jp.setTouser (OpenID); jp.setTemplate_id ("miexd4-4uqrfmdjnvqmjh0egfypm16r5dpdt6p9gpgg"); jp.setTopcolor ("#173177"); jp.seturl ("http: // link para configurações de conta pública/weixin_jspay/weixinjspay/init.action? packageValue ="+resultadojspay.getString ("pré -anyid"). tostring ()); jp.setData (dados); JsonObject jsonObject = jsonObject.FromObject (JP); String str = new String (JsonObject.ToString (). GetBytes ("UTF-8"), "ISO8859-1"); // string xml = clientcustomssl.refundnativepackage (weixinRefundService.getTradePayNo (OrderNo), Non -Cest, Totalfee, Refundfee, Non -Cest); try { System.out.println("data============================================================================================== ClientCustomsSl.RefundnativePackage (WeixInRefundService.GetTradePayNo (OrderNo), Non -Cest, não -CEST); Entidade de Responsação de HttPentity = Response.getentity (); len ++; JsonObject.FromObject (New String (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 <Payhist> payhistlist = weixInPayService.getPayhist (OrderNo, "WeChat", ""); if (payhistlist == null || payhistlist.size () == 0) {weixInPayService.addpayhist (ph); } else {// Para detalhes sobre encerramento, consulte o artigo sobre cancelamento de pedidos. JsonObject strstatus = (jsonObject) CloseWeixinOrderUtils.CloseWeixinOrder (payhistlist.get (0) .gettradePayno ()); if (strstatus.getString ("status"). Equals ("succcess")) {System.out.println (ph.gettradepayno ()); weixInPayService.UpdatePayhist (pH); }}} Retornar resultado; } Entityutils.consume (entidade); } finalmente {ResponseEntry.close (); }} finalmente {httpclient.close (); } retornar nulo; } catch (Exceção e) {e.printStackTrace (); Resultado jsonObject = new jsonObject (); resultado.put ("status", "erro"); resultado.put ("msg", e.getMessage ()); resultado de retorno; }} objeto estático público getJSPay (String não -cest, string orderDescribe, string orderno, preço da string, string timeStart, string timeExpire, string openId) {try {keystore keystore = keystore.getInstance ("pkcs12"); FileInputStream Instruam = new FileInputStream (novo File (PersonalizadoPropertyPlaceHoldConfigurer.getContextProperty ("WX.CERT"). ToString ())); tente {keystore.load (Instruam, "10061401" .toCharArray ()); } finalmente {EnterStream.close (); } // Trust CA O próprio CA e todos os certificados autônomos sslContext sslContext = sslContexts.custom (). Loadkeymaterial (keystore, "consulte email" .toCharArray ()). Build (); // Permitir apenas o protocolo TLSV1 SSLConnectionSocketFactory SSLSF = new SSLConnectionSocketFactory (SSLContext, new String [] {"TLSV1"}, NULL, SSLConnectionSocketFactory.allow_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"); String xml = clientcustomssl.createjsapipackage (não -cest, orderDescribe, orderno, preço, timestart, timeExpire, openID); tente {stringentity se = new stringentity (xml); httppost.setentity (SE); System.out.println ("Execução da solicitação" + httppost.getRequestLine ()); ClosableHttpResponse ResponderEntry = httpClient.execute (httppost); tente {httpentity entity = respostaEntry.getEntity (); System.out.println ("--------------------------------------"); System.out.println (ResponseEntry.getStatusline ()); if (entidade! = null) {System.out.println ("Resposta Conteúdo Comprimento:" + entity.getContentLength ()); Saxreader saxreader = new saxReader (); Documento documento = saxreader.read (entity.getContent ()); Elemento rootelt = document.getrootelement (); DocumentXML = DocumentHelper.ParseText (XML); Elemento rooteltxml = documentxml.getrootelement (); System.out.println ("nó raiz:" + rootelt.getName ()); System.out.println ("==="+rootelt.ElementText ("result_code")); System.out.println ("==="+rootelt.ElementText ("return_msg")); String resultCode = rootelt.ElementText ("result_code"); Resultado jsonObject = new jsonObject (); if (resultadocode.equals ("succcess")) {System.out.println ("================== Prébio pré -PAY_ID ====================="+ Rootelt.ElementText ("PrePay_id_id"); resultado.put ("pré -anyid", rootelt.ElementText ("pré -any_id")); resultado.put ("signo", rooteltxml.ElementText ("sinal")); resultado.put ("status", "sucesso"); resultado.put ("msg", "sucesso"); } else {result.put ("status", "false"); resultado.put ("msg", rootelt.ElementText ("err_code_des")); } resultado de retorno; } Entityutils.consume (entidade); } finalmente {ResponseEntry.close (); }} finalmente {httpclient.close (); } retornar nulo; } catch (Exceção e) {e.printStackTrace (); Resultado jsonObject = new jsonObject (); resultado.put ("status", "erro"); resultado.put ("msg", e.getMessage ()); resultado de retorno; }}} 4. O código da camada de controle de implementação do código no projeto weixin_jspay
pacote com.weixin.jspay.controller; importar javax.servlet.http.httpServletRequest; importar javax.servlet.http.httpServletResponse; importação org.springframework.teroType.Controller; import.springfringfringFrameworkwork.Crete.Controller; import.springFringFrameTworkwork.Controller; org.springframework.web.bind.annotation.RequestMethod;@Controller@RequestMapping("/weixinJsPay")public class WeiXinJsPayController { @RequestMapping(value = "/init", method = RequestMethod.GET) public String init( HttpServletRequest request,HttpServletResponse response,String packageValue,String paySign) {System.out.println ("=================== 微信 JSPAY 开始 ================="); System.out.println ("packageValue ==============="+PackageValue); System.out.println ("Paysign ====================="+Paysign); request.setAttribute ("packageValue", "pré -any_id =" + packageValue); request.setAttribute ("Paysign", PaySign); System.out.println ("=================== 微信 JSPAY 页面跳转开始 ================="); retornar "Weixin"; }}
Código JSP
<%@ página de página = "java" contentType = "text/html; charset = utf-8" pageEncoding = "utf-8"%> <! Doctype html public "-// w3c // dtd html 4.01 transitório // en" "http://www.w3.org/tr/html4/loose.dtd"><html><head><script type =" text/javascript "src ="/weixin_jspay/js/md5.js "> </script> <cratives) '$ {packageValue}'; var paysign = '$ {PaySign}'; alerta ("packageValue ==========="+packageValue); alerta ("Paysign ==============="+PaySign); var SignString = "Appid = consulte a conta pública e não -cest = string aleatória & package ="+packageValue+"& Paysign ="+PaySign+"& SignType = md5 & timestamp = time"; // alerta (SignString); var md5SignValue = ("" + Cryptojs.md5 (SignString)). TOUPPERCASE (); // alerta (md5SignValue); Weixinjsbridge.invoke ('getBrandwcpayRequest', {"Appid": "<span style =" font-family: Arial, Helvetica, Sans-Serif; "> Veja a conta pública </span>", "Timestamp": "1395712654", "NONCEL>" "MD5", "Paysign": md5signvalue}, function (res) {alert (res.err_msg); "get_brand_wcpay_request: cancel") {alert ("pagamento de cancelamento do usuário"); </body> </html>Pagamento WeChat MD5.JS: MD5.JS e WECHAT Documento de Desenvolvimento de Pagamento: Download Endereço
Este artigo foi compilado em "Resumo das Habilidades de Desenvolvimento do Javascript WeChat", e todos são bem -vindos para aprender e ler.
Eu recomendo um tutorial sobre os applets WeChat que estão altamente preocupados agora: o editor do "WeChat Mini Program Development Tutorial" o compilou cuidadosamente para todos, espero que gostem.
O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.