Para usar o JSAPI para pagamento do WeChat, você deve primeiro obter um pré -pagamento do WeChat e, em seguida, preencher o pagamento chamando o JSAPI do WeChat. Devido à interação interativa frontal complicada, get_brand_wcpay_request: cancelar ou get_brand_wcpay_request: falhar pode ser tratado uniformemente para os usuários encontrarem erros ou desistirem ativamente, sem precisar refinar a distinção.
O código de exemplo é o seguinte:
Function onbridgeready () {weixinjsbridge.invoke ('getbrandwcpayRequest', {"appid": "wx2421b1c4370EC43B", // The name of the public account was passed into "Timestamp": "139" 5712654 ", // timestamp, since 1970秒数 "Non -CEST": "E61463F8EFA94090B1F366CCCFBBBB444", // 随机串 "pacote": "u802345jgfjsdfgsdg888", "signote": "md5", // 微信签名方式: " 34c63ff7fadd89 "// 微信签名}, função ( res) {if (res.err_msg == "get_brand_wcpay_request: ok") {} // use o método acima para determinar o retorno do front -end, o WeChat Team Solemn: res.err_msg retornará ao OK após o sucesso do usuário, o pagamento do usuário for bem -sucedido, mas não garante. );
Os parâmetros acima do pacote de parâmetros são prepaay_id
O seguinte é sobre obter parâmetros para ligar para o JSAPI
Quando chamamos o JSAPI, devemos obter o usuário OpenID.
Primeiro defina o objeto de uma solicitação:
package com.unstoppedable.protocol; Import com.unstoppedable.Configure; Import com.unstoppedable.httpservice; Ommon.randomStringGenerator; Import com.unstoppedable.Common.signature; Import Java.lang.reflet. FIELD; Import Java.util.hashmap; Importar Java Time_start; = Builder.mch_id; .out_trade_no; this.fee_type = builder.fee_type ; this.total_fee = builder.total_fee; this.spbill_create_ip = builder.spbill_create_ip; this. time_start = builder.time_start; this.time_expire = builder.time_expire; this.goods_tag = builder.goods_tag ; void setappid (string appid) = Appid;} Public void Setmch_id (String mch_id) {this .mch_id = mch_id;} Public void SetDevice_info (String Device_info) {this.Device_info = Device_info;} Public Void SetnOnOnonONONONONONCE_STR r) {this.nonce_str = nonce_str;} public void Setsign (string signo) {this.sign = signe; ch (string anex) {this.attach = anex;} public void setout_trade_no (string out_trade_no) {this.out_trade_no = out_trade_no;} public void setFee_type (string Fee_type) {this.fee_type = swee_type; ) {This.total_fee = total_fee;} public void setspbill_create_ip (string spbill_create_ip) {this .spbill_create_ip = spban_create_ip;} public void settime_start (string time_start) {time.time_start; void setgoods_tags (string goods_tag) {this.goods_tags_tag; } PUBLIC VOID SETNOTIFY_URL (String Notify_url) {this.notify_url = notify_url;} Public void Settrade_Type (String Trade_type) {This.tr Ade_type = Trade_type;} Public Void SetProduct_id (String Product_id) {this.product_id = product_id;} public void Setlimit_pay (string limite_pay) {this.limit_pay = limite_pay;} public void SetopenId (string openId) {this.openid = openId;} public map <string, object> tom> ap () {map <string, objeto> mapa = novo hashmap <string, objeto> (); .get (this); (); String privada spbill_create_ip; O parâmetro de aprovação Appid não pode ser nulo ");} if (mch_id == null) {lança newALARGumGentException (" "Números de mch_id não podem ser nulos");} se (corpo == null) {lança novo ilegalarGumentException ("" PASS FUREMETRO BORD não pode ser nulo ");} if (out_trade_no == null) {lança números newAlarGumentException out_trade_no não pode ser nulo");} if (total_fee == null) {lança new ilegalarGumentException ("total_fee não pode ser nulo); == null) {tiro newALARGumentException ("O número de parâmetros spbill_create_ip não pode ser nulo");} if (notify_url == null) {lança novo ilegalarGumentEdException ("PASS parâmetro notify_url não pode ser null");} se (trade_type == null ) de_type não pode ser nulo ");} this.appid = appid; this .mch_id = mch_id; this.body = body; this.out_trade_no = out_trade_no; this.Total_Fee = TOPAL_FEE; ATE_IP; this.notify_url = Notify_url; = trade_type;} public UnifyReqDatabuilder SetDevice_info) {{this.Device_info = Device_info; Anexar; time_expire; ay = limite_pay Retorne este; ilegalAgumentException ("Quando Trade_type é JSAPI, o OpenID é um parâmetro obrigatório");} if ("nativo" .Equals (this.trade_type) && product_id == null) joga nova ilegalagumentException ("" deve -filar o parâmetro ");} retornar novo unifiedOrderReqData (this);}}}}
Como alguns parâmetros são necessários, alguns parâmetros são selecionados. E o sinal deve esperar que todos os parâmetros passem antes de calcular, para que o modo Builder seja usado aqui. Sobre o modo construtor.
Escolhemos o HTTPClient para transmissão de rede.
pacote com.unstoppedable.com; Log; .apache.http.client.config.requestconfig; .Conn.ConnectionPoolTimeoutExey; http.client.httpclients; Java.Security.KEYSTORE; /** * Created by Hupeng on 2015/7/28. */Public Class httpservice {Private Static Logger = LogFactory.getLog (httpservice.class); Private Static CloseablehttpClient = BUILDHTTPCL IENT (); // Connect timeout time, default 10 seconds Private Static int Sockettimeout = 5000; // Transmission timeout, default 30 Second Private Static int ConnectTimeout = 5000; Private Static int Requesttimeout = 5000; Public Static CloseHtttpClient () {Try {try {try {try YSTORE KeyStore = KeyStore.getInstance ("PKCS12"); FileInputStream Instream = New FileInputStream (New File (Configure.getcertLocalPath () ); // Load the local certificate for https encryption transmission. Trust OWN CA and All Self-Signed Certs SSLCONTEXT SSLCONTEXT = SslContexts.custom () .loadKeymaterial (KeyStore, configure.getCertPordword (). Tocarray (). ILD (); // Permite o protocolo TLSV1 apenas SSLConnectionSocketFactory SSLSF = new SSLCONNOTFACTORY (SSLCONTEXT, NOVO String [] {"TLSF = TLSF = TLSF" TLSF "TLSF", NOVA, NOVA SSLSF "TLSF" TLSF, "SSLCONTEXT, NOVA String [] Sslconnectionotfactory.browser_compatible_hostname_verifier); sf) .build (); {Throw New Runtimee xception ("ERROR CREATE HTTPCLIENT ...", E);}} Public Static String Doget (String Requesturl) Throws Exception {httpget httpget = new httpget (requesturl); TRY {logger.debug ("Executing request" GetRequestLine (); GetStatuscode (); status: " + status);}}}; retorna httpclient.execute (httpget, resposta -oral);} finalmente {httpget.releaseconnection ();}} public stric VoPost (string url, object2xml) {result = null; ast. = Novo httppost (url); Enviado para a API é convertida em dados de formato XML para API PostDataxml = XSTEAMFORRequestPostData .Toxml (Object2xml); -8 codificação, caso contrário, o chinês do servidor API XML não pode ser identificado com sucesso. ; Entidade, "utf-8");} catch (conexãoPoolTimeoutException e) {Logger.error ("http obtém arremesso de conexãoPoolTimeoutException (aguarde tempo para fora)", e);} Catch Event e) {Logger.error ("http Geting ThNectTimeoutException ", e);} catch) {Logger.error (" "http obtém arremesso de sockettimeOutException", e);} catch (Exceção e) {Logger.error ("http get tiro), e);} finalmente {httppp ast. abort ();} Retorno Resultado;
Depois, há nossa entrada geral:
pacote com.unstable.Service; .ParserConfigurationExceding; Throws IOEXCEPTION, SAXEXCEPTION, PARSERCONFIGUTEXCEPTION {String Res) Onfigure.Unified_order_api, ReqData); Return XMLPARSER.GetMapfromxml (res);} Public Static void Main (String [] args) Throws Exception {UnifiedOrderreqdata Reqdata = new unifiedOrDerreqdata.UnifyReqdataBuilder ("appid" , "mch_id", "out_trade_no", 1, "spaby_create_ip_ip_ip", notify_url "," jsapi "). SetopenId (" OpenId "). build (); system.out.println (unifiedorder (reqdata));};}
O XML retornado é:
<XML> <STURN_CODE> <! CDATA [10000100]]> </mch_id> <nonce_str> <! [cdata [IITRI8IABBBLZ1JC]]> </nonce_str> <! [7921e432F6555F0E86D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D76D7D7D7D76D7D7D7D7D7D7D76D7D7D7D76D7D7D7D76D7D7E86D7D7ED75E8E8ED0CE6 2F]]> </sign> < result_code> <! [cdata [Success]]> </Resultado_code> <prapay_id> <!
Return_code e resultado_code retornarão o pré -pagamento_id quando forem sucesso. Essência Essência , Então use -o em Jsapi. Essência
Este artigo foi organizado para "JavaScript WeChat Development Resumo", "Resumo do tutorial de desenvolvimento do Android WeChat" e "Resumo do tutorial de desenvolvimento Java WeChat", receba todos para aprender e ler.
Eu recomendo um tutorial do WeChat Mini Program com um maior grau de atenção a todos: o editor do "Tutorial de Desenvolvimento do Programa do WeChat" é cuidadosamente organizado para todos.
O exposto acima é todo o conteúdo deste artigo.