먼저 공식 계정에서 발행 한 현금 빨간 봉투의 효과를 살펴 보겠습니다.
가맹점 플랫폼의 인터페이스를 호출해야합니다. 인터페이스 분포 규칙은 다음과 같습니다.
1. 주파수 제한을 보내기 - 기본 1800/min
2. 송신 수의 상한 - 기본 1800/min에 따라 계산됩니다.
3. 상한 금액 - 들어오는 장면 ID에 따라 가맹점 플랫폼 제품 설정에서 기본 상한을 설정하고 적용 할 수 있으며 단위당 최대 4,999 위안 이하
4. "수량"에 대한 다른 제한 사항은 무엇입니까? - 사용자가 그 날을받는 최대 횟수는 기본적으로 10입니다.
5. 수량이 우리의 요구를 충족시킬 수 없다면 어떻게 각 상한을 늘릴 수 있습니까? -최대 금액 제한과 같은 날에 사용자가받는 최대 횟수는 가맹점 플랫폼에서 설정할 수 있습니다.
참고- 빨간색 봉투 양이 200보다 큰 경우 요청 매개 변수 장면 _id를 전달하고 매개 변수 설명이 아래에 표시되어 있습니다.
참고 2- 규제 요건에 따라 새로 적용된 가맹점 계정에 현금 빨간 봉투를 신청할 때 두 가지 조건을 충족해야합니다. 1. 입학 시간은 90 일 2 일을 초과합니다. 30 일 동안 지속적인 정상 거래.
URL을 요청하십시오 https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack
인증서가 필요한지 여부 (자세한 내용은 판매자 인증서 참조)
요청 방법 게시물
요청 데이터 예 :
<xml> <sign> <! 000046545]]> </MCH_BILLNO> <MCH_ID> <! [CDATA [888]]> </MCH_ID> <WXAPPID> <! pid> <send_name> <! [cdata [send_name]]> </send_name> <re_openid> <! E_OPENID> <TALL_AMOUNT> <! [CDATA [200]]> </Total_Amount> <Total_num> <! ATA [부자가되면 축하합니다]> </Wishing> <client_ip> <! 봉투]]]> </wark> <ceence_id> <! [cdata [product_2]]> </scen 000097]]> </COCUME_MCH_ID> <nonce_str> <! O> PostTime%3D123123412%26 ClientVersion%3D234134%26Mobile%3D122344455%26deviceid%3Dios </risk_info> </xml>
인터페이스에는 가맹점 플랫폼의 인증서에 대한 호출이 필요하며, 인증서는 가맹점 플랫폼에서 다운로드해야합니다.
그런 다음 인터페이스에서 인증서를 사용하십시오. 먼저 새로운 weixinssl 클래스를 만듭니다
@ComponentPublic 클래스 weixinssl { / *** 인증서 유형* / @Value ( "$ {werchant.storekey}") 개인 스트링 스토키; / *** 파일 경로*/ @Value ( "$ {werchant.sslfile}") 개인 문자열 sslfile; / *** 판매자 번호*/ @Value ( "$ {werchant.merchantnumber}") 개인 문자열 가맹점; 공개 문자열 getStorekey () {return storekey; } public void setstorekey (String Storekey) {this.storekey = Storekey; } public String getSlFile () {return SSlFile; } public void setsslfile (String sslfile) {this.sslfile = sslfile; } public String getMerchantNumber () {return merchantNumber; } public void setmerchantNumber (String MerchantNumber) {this.MerchantNumber = MerchantNumber; }}httpclientssl 클래스를 캡슐화하여 HTTPS 요청을 구현하여 인증서를 추가하십시오.
@componentpublic class httpclientssl {@autowired private weixinssl weixinssl; // 요청 시간 초과 (밀리 초) 5 초 공개 정적 요청 config requestConfig; // 응답 시간 초과 (밀리 초) 60 초 공개 정적 int http_response_timeout = 60 * 1000; // httpclient 문자 인코딩 public static string encoding = "utf-8"; public static requestConfig getRequestConfig () {return retureConfig.custom (). setConnectTimeout (5 * 1000) .SetConnectionRequestTimeout (http_response_timeout) .build (); } public static void setRequestConfig (requestConfig requestConfig) {httpclientssl.requestConfig = requestConfig; } / *** https 요청 위조 증명서* @return* / public closeblehttpclient defaultsslclient () {sslcontext sslcontext = null; {new sslcontextBuilder (). loadTrustMaterial (null, new trustStrategy () {@override public boolean istrusted (x509certificate [] 체인, String authtype)가 java.security.cert.certicatexception {return false;}}); } catch (nosuchalgorithmexception | keystoreException e) {e.printstacktrace (); } sslConnectionSocketFactory Factory = 새로운 SSLConnectionSocketFactory (SSLContext); return httpclients.custom (). setsslsocketfactory (factory) .build (); } / *** https 인증서 추가 요청* @return* / public closeblehttpclient defaultsslclientfile () {if (this.weixinssl == null) {return this.defaultsslclient (); } fileInputStream inputStream = null; keystore keystore = null; try {// ssl type keystore = keystore.getInstance (weixinssl.getStorekey ()); // SSL 파일 inputStream = new FileInputStream (weixinssl.getsslfile ()); // SSL 비밀번호를 설정합니다 keystore.load (inputStream, weixinssl.getmerchantNumber (). tochararray ()); } catch (keystoreException | nosuchalgorithmexception | chertorexception | ioexception e1) {e1.printstacktrace (); } 마침내 {try {inputStream.close (); } catch (ioexception e) {e.printstacktrace (); }} sslcontext sslcontext = null; {sslcontext = sslcontexts.custom (). loadKeymaterial (keystore, weixinssl.getmerchantNumber (). tochararray ()). build (); } catch (uncoververableKeyException | nosuchalgorithmexception | keystoreException | keyManagementException e) {e.printstacktrace (); } sslConnectionSocketFactory factory = new sslConnectionSocketCocketFactory (sslContext, new String [] { "tlsv1"}, null, sslConnectionSocketFactory.Browser_Compatible_hostname_verifier); return httpclients.custom (). setsslsocketfactory (factory) .build (); } / *** 요청을 보내는 방법 캡슐화* @throws UnsupportedEncodingException* / public string (문자열 URL, 문자열 데이터, closeblehttpclient closeablehttpclient) unsupportedencodingexception {closeablehttpclient 클라이언트 = closeablehttpclient; httppost httppost = new httppost (urldecoder.decode (url, encoding)); httppost.addheader ( "Connection", "Keep-Alive"); httppost.addheader ( "수락", "*/*"); httppost.addheader ( "content-type", "application/x-www-form-urlencoded; charset = utf-8"); httppost.addheader ( "host", "api.mch.weixin.qq.com"); httppost.addheader ( "x- requested-with", "xmlhttprequest"); httppost.addheader ( "캐시 제어", "max-age = 0"); httppost.addheader ( "사용자 에이전트", "Mozilla/4.0 (호환 가능; MSIE 8.0; Windows NT 6.0)"); httppost.setconfig (this.getRequestConfig ()); // set timeout closeblehtttpresponse reponsk = null; // 매개 변수를 엄격한 엔티티에 넣습니다. = 새로운 엄격함 (데이터, 인코딩); entity.setContentEncoding (인코딩); Entity.SetContentType ( "Application/XML"); httppost.setentity (엔티티); try {response = client.execute (httppost); if (response.getStatusline (). getStatusCode () == 200) {httpentity httpentity = (httpentity) response.getentity (); if (response! = null) {return entityUtils.toString (httpentity, 인코딩); }}} catch (ioexception e) {e.printstacktrace (); } return null; }} 이러한 방식으로 HTTPS로 인증서를 요청하는 엔티티 클래스를 캡슐화 한 다음 요청 된 WeChat Red Envelope 인터페이스를 생성합니다.
https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack의 매개 변수 서명 :
/*** 레드 엔벨로프 매개 변수 엔티티 클래스*@Throws UnSupportedEncodingException*/ @componentPublic 클래스 SendRedpack 구현 {/***/private static final long serialversionUid = -1000489228099916099L; 개인 문자열 nonce_str; // random string 개인 문자열 부호; // 서명 개인 문자열 MCH_BILLNO; // 판매자 주문 번호 개인 문자열 mCH_ID; // 판매자 번호 개인 문자열 wxAppid; // 공개 계정 개인 문자열 send_name; // 판매자 이름 RE_OPENID; // 사용자 개인 int total_amount; // private int total _nnum; // red -elevely of red -engronge elevely het elevering het leget het het het het het het het total hefit init. 봉투 축복 개인 문자열 client_ip; // ip 주소 개인 문자열 act_name; // 활동 이름 개인 문자열 비고; // 공개 문자열 getNonce_str () {return nonce_str; } public void setnonce_str (string nonce_str) {this.nonce_str = nonce_str; } public String getSign () {return sign; } public void setSign (문자열 부호) {this.sign = 부호; } public string getMch_billNo () {return MCH_BILLNO; } public void setmch_billno (문자열 mch_billno) {this.mch_billno = mch_billno; } public String getMch_id () {return mch_id; } public void setmch_id (문자열 mch_id) {this.mch_id = mch_id; } public String getwxAppid () {return wxAppid; } public void setwxAppid (String wxAppid) {this.wxappid = wxappid; } public String getSend_name () {return send_name; } public void setsend_name (String send_name) {this.send_name = send_name; } public String getRe_openid () {return re_openid; } public void setre_openid (String re_openid) {this.re_openid = re_openid; } public int getTotal_amount () {return total_amount; } public void settotal_amount (int total_amount) {this.total_amount = total_amount; } public int getTotal_num () {return total_num; } public void settotal_num (int total_num) {this.total_num = total_num; } public String getwishing () {return wising; } public void setwishing (String Wishing) {this.wishing = 소원; } public String getClient_ip () {return client_ip; } public void setclient_ip (String client_ip) {this.client_ip = client_ip; } public String getAct_name () {return act_name; } public void setact_name (String act_name) {this.act_name = act_name; } public String getRemark () {return warting; } public void setRemark (문자열 비고) {this.remark = 비고; }}다음은 빨간색 패킷을 보내는 컨트롤러입니다.
/*** Red Envelope Controller* @author zengliang*/ @controller @requestmapping (value = "/redevelopesreceive") public class redevelopesreceivecontroller {// wechat 고유 식별자 @value ( "$ {weixin.appid}") 개인 문자열 appid; // weChat 개발자 비밀번호 식별자 @Value ( "$ {weixin.appsecret}") public String appsecret; @autowired private sendpack sendredpack; @autowired private httpclientssl httpclientssl; /*** XML 매개 변수 보내기* @Author Zengliang*/@ResponseBody @RequestMapping (value = "/sendxml") public String SendXml (String OpenID, Long Renevelopes_ID, String MCH_BillNo) {redevelopes redenve = redevelopesservice.findone (redenvelopes.findone); XMLUTIL XMLUTIL = NEW XMLUTIL (); sendredpack.setact_name (redenve.getact_name ()); sendredpack.setnonce_str (xmlutil.random ()); sendredpack.setre_openid (OpenID); sendredpack.setclient_ip (redenve.getclient_ip ()); sendredpack.setmch_billno (mch_billno); sendredpack.setmch_id (redenve.getmch_id ()); 문자열 xx = redenve.getRemark (); sendredpack.setRemark (stringUtils.isempty (xx) == false? xx : "빈"); SendRedPack.setSend_name (redenve.getSend_name ()); sendredpack.settotal_amount (redenve.getTotal_amount ()); sendredpack.settotal_num (redenve.getTotal_num ()); sendredpack.setwishing (redenve.getwishing ()); sendredpack.setwxappid (redenve.getwxappidxx ()); // 서명 문자열 생성 params = this.CreatesEndRedPackorDersign (sendRedpack, redenve.getStore_key ()); sendredpack.setsign (params); xmlutil.xstream (). alias ( "xml", sendredpack.getclass ()); // cdata 블록 문자열을 지원하기 위해 xstream을 확장하여 requestxml = xmlutil.xstream (). toxml (sendredpack); 문자열 결과; {result = httpclientssl.send ( "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack", requestxml, httpclientssl.defaultsslclientfile ()); System.out.println ( "성공적인 반환 값"+결과); 반환 결과; } catch (UnsupportedEncodingException e) {e.printstacktrace (); } return null; }/ ** * 서명 생성 * @param redpack * @return */ public string readesEndRedPackOrderSign (sendRedpack redpack, String StoreKey) {StringBuffer sign = new StringBuffer (); Sign.Append ( "act_name ="). Append (redpack.getAct_name ()); Sign.Append ( "& client_ip ="). Append (redpack.getClient_ip ()); sign.append ( "& re_billno ="). append (redpack.getmch_billno ()); Sign.Append ( "& wartment ="). Append (redpack.getmch_id ()); Sign.Append ( "& send_str ="). Append (redpack.getNonce_str ()); sign.append (redpack.getnonce_str ()); Sign.Append ( "& re_openid ="). Append (redpack.getre_openid ()); Sign.Append ( "& wartment ="). 부록 (redpack.getRemark ()); Sign.Append ( "& send_name ="). Append (redpack.getSend_name ()); Sign.Append ( "& total_amount ="). 부록 (redpack.getTotal_amount ()); Sign.Append ( "& total_num ="). Append (redpack.getTotal_num ()); Sign.Append ( "& Wishing ="). Append (redpack.getWishing ()); sign.append ( "& wxappid ="). append (redpack.getwxappid ()); Sign.Append ( "& key ="). Append (StoreKey); return digestutils.md5hex (sign.tostring ()). touppercase (); }}그런 다음 도구 클래스를 사용하여 XML을 구문 분석하여 XML을 구문 분석하여 wechat에 의해 XML을 구문 분석해야합니다.
/** * XML 도구 클래스 * @Author Zengliang */ @componentPublic Class XMLUTIL {/** * PARSING XML에 의해 wechat * @param xml * @return * @Throws Exception */@Suppresswarnings ( "Checked Unchecked") String> parsexml (string xml) (string xml). = New Hashmap <String, String> (); 문서 doc = null; try {doc = documentHelper.parsetext (XML); // 문자열을 XML 요소로 변환하여 rootelt = doc.getRootElement (); // 루트 노드 목록을 가져옵니다 <ementt> list = rootelt.Elements (); (요소 요소 : list) {// tranquility node map.put (element.getName (), element.getText ()); // 노드의 이름은 맵 키이고 텍스트는 맵 값}} catch (documentException e) {e.printstacktrace (); } catch (예외 e) {e.printstacktrace (); } 리턴 맵; } / *** cdata block* / private xstream xstream = new xstream (new xppdriver (new nonamecoder ()) {@override public hierarchicalstreamwriter createWriter (작가 Out) {retep prettyprintwriter (out) {// condents for boolean에 대한 cdata mark를 추가하십시오. @Suppresswarnings ( "rawtypes") public void startNode (문자열 이름, 클래스 클라즈) {super.startNode (이름, clazz)} @override public string encodenode {return name} @override protected void writer (Quickwriter, String text) writer.write.write.write ( "]}; private XStream concationLueNlinExStream = new Xstream (New Domdriver (NULL, NEW XMLFIRDINGLYLYNAMECODER ( "_-", "_"))); public xstream getxstreaminclueunderline () {return incatureNdlinexStream; } public xstream xstream () {return xstream; } / *** 랜덤 번호 생성* @return* / public String random () {String Random = uuid.randomUuid (). toString (). Replace ( "-", ""); 무작위로 반환; }}그런 다음 sendxml 메소드를 호출하여 빨간 봉투를 사용자에게 보냅니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.