이 기사에서는 JSAPI 결제에 대한 관련 정보를 공유합니다. 특정 내용은 다음과 같습니다
1. 도구
도구 카테고리보기 : Wechat Pay Java 버전의 기본 결제
2. 공개 계정 설정
3. 코드 구현
OpenID : OpenID는 사용자와 공개 계정 간의 고유 한 표시입니다. 다음 클래스에는 토큰 생성, 순서 인터페이스 호출 폐쇄, 구성 파일 정보 얻기 및 도구 클래스가 포함됩니다. 다른 기사에는 특정 코드 구현이 있습니다.
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 java.util.hashmap; import java.util.list; import java.util.map; import javax.net.ssl.sslcontext; import javax.servlet.http.htttp.htttp.httervletrequest; import javax.servlet.http.httpervletr ronge; import net org.apache.http.httpentity; import org.apache.http.client.methods.closeablehttpresponse; import org.apache.http.client.methods.httppost; import org.apache.http.conn.ssl.sslconnectionsocketforcory; import org.apache.http.conn.ssl.sslcontexts; import org.apache.http.entity.stringentity; import org.apache.http.impl.client.closeablehttpclient; import org.apache.impl.client.httpclients; 수입 org.apache.http.util.entityutils; import org.dom4j.document; import org.dom4j.documenthelper; import org.dom4j.element; import org.dom4j.io.saxreader; import org.spramework.beans.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.bind.bind.rest 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.payhistorypaystants.payhistorypaystatus; com.zhrd.bussinss.platform.service.getWeixInAccessTokenService; import com.zhrd.bussinss.platform.service.weixinpayservice; import com.zhrd.bussinss.platform.utils.closeweixinordutils; import com.zhrd.bussinss.platform.utils.customizedPropertyplaceholderconfigurer; import com.zhrd.bussinss.platform.weixinpayutils.clientcustomssl;@restcontroller@requestmapping ( "/rest/weixinsendmessage") 공공 classinsendmessagerestfultufultuctontrollercontroller {weixinsendmessager weixinpayservice; @autowired getWeixInAccessTokenService getWeixInaccessTokenService; 개인 정적 긴 표준 시간 = 1662652800000L; /** * weChat 메시지 보내기 * @param request * @param response * @return */@requestmapping (value = "/weixinsend", method = requestmethod.get) @ResponseBody public object weixinsend (httpservletrequest request, httpservletResponse 응답, 문자열, String OpenID) { System.out.println ( "=============================================== =========================================================================== =========================================================================== ============================================================================ =========================================================================== =========================================================================== =========================================================================== ============================================================================ CustomizedPropertyHolderConfigurer.getContextProperty ( "wx.cert"). trytring ()); sslcontexts.custom (). LoadKeymaterial (Keystore, "10061401".tochararray ()). build (); // tlsv1 프로토콜 허용 SSLConnectionSocketFactory sslsf = new sslConnectionSocketFactory (sslcontext, new String [] { "tlsv1"}, null, sslconnectionsocketfactory.allow_all_all_hostname_verifier); Closeblehttpclient httpclient = httpclients.custom () .setsslsocketfactory (sslsf) .build (); // httpget httpget = new // httpget ( "https://api.mch.weixin.qq.com/secapi/pay/refund"); // 토큰을 얻으려면 Token httppost httppost httppost = new httppost ( "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+getweixinaccesstokenservices.accssokenstoken ()에 관한 기사를 참조하십시오. Payhist pH = null; List <map <string, object >> td = weixinpayservice.gettrade (OrderNo); 날짜 dt = 새 날짜 (); simpledateformat sdf = 새로운 simpledateformat ( "yyyymmddhhmmss"); 문자열 noncestr = sdf.format (dt) .toString (); 날짜 지금 = 새 날짜 (); String TradePayNo = OrderNo+String.format ( "%10D", 표준 시간 -Ogon.getTime ()). 서브 스트링 (0, 10); System.out.println ( "주문 레이블 Orderno ====================================================== 숫자 ================== "+string.format ("%10d ", 표준 시간 - now.gettime ()). substring (0, 10)); String price = math.round (float.valueof (td.get ("price ")). tostring (100)+"; "; 구성 파일 정보를 얻으십시오 DTSDF = "YYYYMMDDHHMMSS"); System.out.println ( "price =="+price); jsonobject resultjspay = (jsonobject) getJspay (비정부, "Order", TradePayno, 가격, 비정규, TimeExpire, OpenID); resultjspay.getString ( "propayId"); 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")+"(Mr./ms.) Order"); valueparam.put ( "색상", "#173177"); map <string, string> valueparam1 = new Hashmap <String, String> (); valueparam1.put ( "value", Orderno); valueparam1.put ( "색상", "#173177"); map <string, string> valueparam2 = new Hashmap <String, String> (); ValueParam2.put ( "Value", "Smart Community Love Fresh Order"); valueparam2.put ( "색상", "#173177"); map <string, string> valueparam3 = new Hashmap <String, String> (); valueparam3.put ( "value", td.get (0) .get ( "price")+"meta"); valueparam3.put ( "색상", "#173177"); map <string, string> valueparam4 = new Hashmap <String, String> (); valueparam4.put ( "value", "대기 대기"); valueparam4.put ( "색상", "#173177"); map <string, string> valueparam5 = new Hashmap <String, String> (); valueparam5.put ( "value", "click to pay"); valueparam5.put ( "색상", "#173177"); FirstParam.put ( "첫 번째", valueparam); FirstParam.put ( "keyword1", valueparam1); FirstParam.put ( "Keyword2", ValueParam2); FirstParam.put ( "Keyword3", ValueParam3); FirstParam.put ( "Keyword4", ValueParam4); FirstParam.put ( "비고", valueparam5); data.add (FirstParam); jspay jp = new jspay (); jp.settouser (OpenID); jp.settemplate_id ( "miexd4-4uqrfmdjnvqmjh0egfypm16r5dpdt6p9gpgg"); jp.settopcolor ( "#173177"); jp.seturl ( "http : // 공개 계정 설정/weixin_jspay/weixinjspay/init.action? packageValue ="+resultjspay.getString ( "propayId"). toString ()); jp.setData (데이터); jsonobject jsonobject = jsonobject.fromobject (jp); String str = new String (jsonobject.toString (). getBytes ( "UTF-8"), "iso8859-1"); // String XML = ClientCustomsSl.RefundNativePackage (weixinRefundService.getTradePayno (OrderNo), 비 CESTR, TotalFee, RefundFee, Noncestr); try {System.out.println ( "data ===================================================================================================================== ClientCustomssl.refundnativePackage (weixinrefundservice.getTradepayno (noncest, noncest); "System.out.println"; httpentity entity. Len ++; in.close (); 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); <payhist> payhistlist = weixinpayservice.getpayhist (Orderno, "wechat", ""); if (payhistList == null || payHistList.size () == 0) {weixinpayservice.addpayhist (ph); } else {// 주문 마감에 대한 자세한 내용은 주문 취소에 관한 기사를 참조하십시오. jsonobject strstatus = (jsonobject) coseweixinorderutils.closeweixinorder (payhistList.get (0) .getTradePayno ()); if (strstatus.getString ( "status"). equals ( "success")) {System.out.println (ph.getTradePayno ()); weixinpayservice.updatepayhist (ph); }}} 반환 결과; } entityutils.consume (엔티티); } 마침내 {responseentry.close (); }} 마침내 {httpclient.close (); } return null; } catch (예외 e) {e.printstacktrace (); jsonobject result = new jsonobject (); result.put ( "상태", "오류"); result.put ( "msg", e.getMessage ()); 반환 결과; }} public static 객체 getJspay (문자열 비 시스트, 문자열 정서도, 문자열 주문 노, 문자열 가격, 문자열 timestart, String TimeExpire, String OpenID) {try {keystore keystore = keystore.getInstance ( "pkcs12"); fileInputStream instream = new FileInputStream (새 파일 (customizedPropertyPlaceHolderConfigurer.GetContextProperty ( "wx.cert"). toString ()); try {keystore.load (Instream, "10061401".tochararray ()); } 마침내 {enterstream.close (); } // 자신의 CA 및 모든 자체 서명 된 CERTS SSLCONTEXT SSLCONTEXT = SSLCONTEXTS.CUSTOM (). LOADKEYMATERIAL (KeyStore, "이메일 참조".ToCharArray ()). 빌드 (); // tlsv1 프로토콜 허용 SSLConnectionSocketFactory sslsf = new sslConnectionSocketFactory (sslcontext, new String [] { "tlsv1"}, null, sslconnectionsocketfactory.allow_all_all_hostname_verifier); Closeblehttpclient 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/unifeordorder"); 문자열 XML = ClientCustomsSl.CreateJsapiPackage (비 CESTRED, ORDERDESCRIBE, ORDERNO, 가격, TIMESTART, TIMEEXPIRE, OpenID); try {stramentity se = 새로운 엄격함 (xml); httppost.setentity (se); System.out.println ( "실행 요청" + httppost.getRequestline ()); closeblehtttpresponse responseentry = httpclient.execute (httppost); {httpentity entity = responsentry.getentity (); System.out.println ( "-------------------------------------------------------- System.out.println (ResponseEntry.getStatusline ()); if (entity! = null) {system.out.println ( "응답 내용 길이 :" + entity.getContentLength ()); SaxReader SaxReader = New SaxReader (); 문서 문서 = saxReader.Read (entity.getContent ()); 요소 rootelt = document.getRootElement (); document documentxml = documentHelper.parsetext (XML); 요소 rooteltxml = documentxml.getRootElement (); System.out.println ( "루트 노드 :" + rootelt.getName ()); System.out.println ( "==="+rootelt.elementText ( "result_code")); System.out.println ( "==="+rootelt.elementText ( "return_msg")); 문자열 resultCode = rootelt.elementText ( "result_code"); jsonobject result = new jsonobject (); if (resultCode.equals ( "success")) {System.out.println ( "====================================="+ rootelt.elementText ( "prepay_id")); result.put ( "prepayId", rootelt.elementText ( "propay_id")); result.put ( "부호", rooteltxml.elementtext ( "sign")); result.put ( "상태", "성공"); result.put ( "msg", "success"); } else {result.put ( "status", "false"); result.put ( "msg", rootelt.elementtext ( "err_code_des")); } 반환 결과; } entityutils.consume (엔티티); } 마침내 {responseentry.close (); }} 마침내 {httpclient.close (); } return null; } catch (예외 e) {e.printstacktrace (); jsonobject result = new jsonobject (); result.put ( "상태", "오류"); result.put ( "msg", e.getMessage ()); 반환 결과; }}} 4. Weixin_jspay 프로젝트의 코드 구현 제어 계층 코드
package com.weixin.jspay.controller; import javax.servlet.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import org.springframework.stereotyp.controller; import org.springframework.bind.bind.annot.annot.annot org.springframework.web.bind.annotation.requestmethod;@controller@requestmapping ( "/weixinjspay") public class weixinjspaycontroller {@requestmapping (value = "/init", method = requestmethod.get) public quest (httpervletrequest, string, string, string). PaySign) {System.out.println ( "====================================="); System.out.println ( "PackageValue ==============="+PackageValue); System.out.println ( "PaySign ======================"+PaySign); request.setAttRibute ( "packageValue", "prepay_id =" + packageValue); request.setAttribute ( "PaySign", PaySign); System.out.println ( "==================== 微信 jspay 页面跳转开始 =================="); "weixin"을 반환합니다. }}
JSP 코드
<%@ page language = "java"contmenttype = "text/html; charset = utf-8"pageencoding = "utf-8"%> <! doctype html public "-// w3c // dtml 4.01 Transitional // en" "http://www.w3.org/tr/tr/html4/loose.dtd"> html> <haid> <script type ="text/javascript "src ="/weixin_jspay/js/md5.js "> </script> <cript> <cript> <cript> <cript> <script> '$ {packageValue}'; var paysign = '$ {paysign}'; Alert ( "PackageValue ==========="+PackageValue); ALERT ( "PAYSIGN ================"+PAYSIGN); var signstring = "appid = 공개 계정 및 noncest = random string & package ="+packagevalue+"& paysign ="+paysign+"& signtype = md5 & timestamp = time"; // Alert (Sigstring); var md5signvalue = ( "" + cryptojs.md5 (sigstring)). touppercase (); // alert (md5signvalue); weixinjsbridge.invoke ( 'getBrandwcpayRequest', { "appid": "<span style ="font-family : arial, helvetica, sans-serif; "> 공개 계정 참조 </span>", "timestamp": "1395712654", "123456", "package": ":": ":": ":": ":" "md5", "Paysign": md5signvalue}, alert (res.err_msg); "get_brand_wcpay_request : cancel"{alert ( "사용자 취소 결제") {alert ( "pay develment")}; </body> </html>Wechat 지불 MD5.JS : MD5.JS 및 WeChat 지불 개발 문서 : 다운로드 주소
이 기사는 "JavaScript WeChat Development Skills의 요약"으로 편집되었으며 모두가 배우고 읽을 수 있습니다.
"Wechat Mini Program Development Tutorial"의 편집자가 모든 사람을 위해 신중하게 편집 한 WeChat 애플릿에 대한 튜토리얼을 추천합니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.