要使用JsApi进行微信支付,首先要从微信获得一个prepay_id,然后通过调用微信的jsapi完成支付,JS API的返回结果get_brand_wcpay_request:ok仅在用户成功完成支付时返回。由于前端交互复杂,get_brand_wcpay_request:cancel或者get_brand_wcpay_request:fail可以统一处理为用户遇到错误或者主动放弃,不必细化区分。
El código de ejemplo es el siguiente:
Función onbridgeReady () {weixinjsbridge.invoke ('getBrandwcpayRequest', {"appid": "wx2421b1c4370ec43b", // El nombre de la cuenta pública se pasó a "Timestamp": "139" 5712654 ", // timestamp, desde 1970 秒 秒 秒 秒 秒数 "Noncestr": "E61463f8efa94090b1f366cccfbbb444", // 随机串 "paquete": "u802345jgfjsdfgsdg8888", "firtype": "md5", // 微信签名方式: "paysign": "" 700aA570631E 4C63FF7FADD89 "// 微信签名}, función ( res) {if (res.err_msg == "get_brand_wcpay_request: ok") {} // Use el método anterior para determinar la devolución del frente del frente, el equipo de WeChat Solemn: Res.err_msg volverá a OK después de que el pago del usuario sea exitoso, pero no lo garantiza. );
Los parámetros anteriores del paquete de parámetros son prepAay_id
Lo siguiente se trata de obtener parámetros para llamar a JSAPI
Cuando llamamos a JSAPI, debemos obtener el usuario del usuario.
Primero defina el objeto de una solicitud:
paquete com.unstoppedable.protocol; Importar java.util.map; String Time_Start; = build.mch_id; .out_trade_no; etiqueta ; void setAppid (string appid) = appid;} public void setmch_id (string mch_id) {this .mch_id = mch_id;} public void setDevice_info (String dispositivo_info) {this.device_info = dispositivo_info;} public void setnononononononce_str r) {this.nonce nonce_str;} public void setSign (firma de cadena) {this.sign = firma; ch (string attach) {this.attach = Attach;} 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 = fee_type;} publ IC Void Settotal_fee (int Total_fee ) {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) {this.time_start = 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 limit_pay) {this.limit_pay = limit_pay;} public void setOpenid (string openId) {this.openID = openId;} public map <string, objeto> tom> ap () {MAP <String, Object> MAP = New HashMap <String, Object> (); .get (this); if (obj! = null) {{ Map.put (field.getName (), obj);}} Catch (illegalargumentedException E) {e.printstacktrace ();} Catch (illegalaccessException E) { ACE (); Cadena privada Spbill_Create_ip; Pasando el parámetro APPID no puede ser nulo ");} if (mch_id == null) {lanzar newAlArgumentException (" "Los números de MCH_ID no pueden ser nulos");} if (Body == NULL) {tirar nueva IllegalArGumentedException ("" Pase el cuerpo del parámetro del parámetro) no se puede ser nulo ");} if (out_trade_no == null) {throle newAlArGumentException Numbers out_trade_no no puede ser nulo");} if (total_fee == null) {tirar nueva ilegalargumentException ("Total_fee no puede ser null");} if (spban_create_ip == null) {tire newAlArGumentException ("El número de parámetros spbill_create_ip no puede ser nulo");} if (notify_url == null) {lanzar nueva ilegalArGumentException ("El parámetro de paso notify_url no puede ser nulo");} if (comercio_type == null ) de_type no puede 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; this.trade_type = Trade_Type;} public unifyReqDatabuilder setDevice_info) {{this.device_info = dispositivo_info; Adjuntar; = time_expire; s;} Public UnifiedOrderreqdatabuilder Setgoods_tags_tags (String Goods_tag) {this.Goods_tags_tags_tag; Return This;} Public Lder Setproduct_id (String Product_id) {This.product_id = Product_id; Return This;} Public UnifiederReqdataBuilder limit_pay) {this.limit_pay = limit_pay ; Return This;} Public UnifiedREQDATABUILEDER STRING Openid (String Openid) {this.openid = OpenID; Return This;} Public UnifiederReqdata () {if ("jsapi" .equals (this.trade_type) &&TYPE &&OPENID == NULL) {Throw New iLlegalagumentexception ("When trade_type is JSAPI, openid is a must -fill parameter");} if ("native" .equals (this.trade_type) &&PRODUCT_ID == NULL) Throw New iLlegalagumentexception ("" When trade_type is native, product_id is a Must -Fill Parameter ");} return New UnifiedOrderReqData (this);}}}}
Debido a que se requieren algunos parámetros, se seleccionan algunos parámetros. Y el signo tiene que esperar a que pasen todos los parámetros antes de calcular, por lo que el modo Builder se usa aquí. Sobre el modo de constructor.
Elegimos httpclient para la transmisión de red.
paquete com.unstoppedable.com; Log; .apache.http.client.config.requestconfig; .Conn.ConnectionPoolTimeutException; http.client.httpclients; Java.security.keystore; Conecte el tiempo de espera, predeterminado 10 segundos static int sockettimeout = 5000; KeyStore = KeyStore.getInstance ("PKCS12"); Sslcontexts.custom () .loadKeyMaterial (KeyStore, configure.getCertpassword (). TCharray (). Ild (); // Permitir el protocolo TLSV1 Solo SSLConnectionSockyFactory SSLSF = New SSLConnectionSotFactory (SSLContex Sslconnectionsotfactory.browser_compatible_hostname_verifier); f) .Build (); {Throw New Runtimee Xception ("Error cree httpclient ...", e);}} public static string doget (String requestUrl) lanza la excepción {httpget httpget = new httpget (request); . GetStatUscode (); estado: " + status);}}}; return httpClient.Execute (httpget, respuestashandler);} finalmente {httpget.releaseconnection ();}} public stric stric vopost (string url, objeto object2Xml) {String string Result = null; ost = Nuevo httppost (url); Enviado a la API se convierte en datos de formato XML a API PostDataxml = XStreamForRequestPostData .TOXML (Object2XML); -8 Codificación, de lo contrario, el chino del servidor API XML no se puede identificar con éxito. ;/ Establezca la configuración logger.info del dispositivo de solicitud ("Ejecución de la solicitud" + httppost.getRequestline ()); Entidad, "UTF-8");} Catch (ConnectionPoolTimeOutException e) {logger.error ("http get throw ConnectionPoolTimeOutException (Wait Time Out)", e);} Event E) {logger.error ("http get thnecttimeOutException ", e);} catch) {logger.error (" "http get throw socketttimeutexception", e);} capt (excepción e) {logger.error ("http get throw), e);} finalmente {httppp ost. abort ();} Resultado de retorno;
Luego está nuestra entrada general:
paquete com.unstoppedable.service; .ParserConfigurationException; Lanza ioexception, saxException, parserconfigutexception {string res) onfigure.unified_order_api, reqData); , "mch_id", "out_trade_no", 1, "spaby_create_ip_ip_ip ", notify_url", "jsapi"). Setopenid ("openid"). Build () ; System.out.println (unifiedOrder (ReqData));}}
El XML devuelto es:
<xml> <shurn_code> <! CDATA [10000100]]> </mch_id> <nonce_str> <! [cdata [IITRI8IABBBLZ1JC]]> </nonce_str> <! [7921e432F6555F0E86D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D7D76D7D7D7D76D7D7D7D7D7D7D76D7D7D7D76D7D7D7D76D7D7E86D7D7ED75E8E8ED0CE6 2F]]> </sign> < result_code> <! [cdata [Success]]> </Resultado_code> <PROPAY_ID> <!
Return_code y result_code devolverá el prepay_id cuando sean éxito. Esencia Esencia , Luego úsalo en Jsapi. Esencia
Este artículo se ha organizado para "JavaScript WeChat Development Resumen", "Android WeChat Development Tutorial Tutorial" y "Java WeChat Development Tutorial" Summary "bienvenidos a todos para aprender y leer.
Recomiendo un tutorial de WeChat Mini Program con un mayor grado de atención a todos: el editor de "WeChat Mini Development Tutorial" está cuidadosamente organizado para todos.
Lo anterior es todo el contenido de este artículo.