微信掃碼二維碼 經過java調公衆號接口發放紅包

最新研究微信紅包接口的問題真是困擾了我很久,由於微信的api 實在是太坑爹了 ,若是沒有大量的測試是行不通的,我是拼湊的全部人的集合才弄明白,接下來跟你們分享一下java 結合jsp ,兩個服務器如何實現 微信掃碼二維碼 而後公衆號發放紅包的例子。javascript

1.準備工做先不說了(好比驗證回調函數服務器域名啊、程序必須部署在80端口等等,開通微信支付等功能,這個微信api 說的很清晰),須要兩個程序 ,一個做爲微信接口的回掉函數程序用來獲取 code(簡稱服務器A),另外一個做爲調取發送紅包的程序(簡稱服務器B)。(java 端jar包就不寫了直接寫方法)html

2.首先在A服務器上部署back.html頁面 ,而後用生成二維碼工具將此頁面路徑生成二維碼,頁面自動受權跳轉到回第二個頁面 getback.htmljava

<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="txt/html; charset=utf-8"/>

<script type="text/javascript" src="jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function () {

window.location.href ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=微信公衆號的appid&redirect_uri=回調函數頁面路勁(個人是getback.html)&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect"

});

</script>
<style>

</style>
</head>
<body>
</body>
</html>

接下來是 getback.html 代碼jquery

 1 <!doctype html>
 2 <html>
 3 <head>
 4 <meta http-equiv="content-type" content="txt/html; charset=utf-8"/>
 5 
 6 <script type="text/javascript" src="jquery-1.8.3.js"></script>
 7 <script type="text/javascript">
 8 $(document).ready(function () {
 9 
10 var code = getQueryString('code');
11 
12 
13 if (code != null) {
14 
15 window.location.href="B服務器路徑的controller方法上?code="+code;
16 
17 }
18 });
19 
20 
21 function getQueryString(name) {
22 var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
23 var r = window.location.search.substr(1).match(reg);
24 if (r != null) return unescape(r[2]);
25 return null;
26 
27 }
28 </script>
29 <style>
30 
31 </style>
32 </head>
33 <body>
34 
35 </body>
36 </html>

這個頁面難點在於獲取code,終於要說的微信最坑的地方了 就是獲取的code 是在回調路徑中隱藏的,api根本就沒有寫,我是經過截取的方法獲取路徑發送給B服務器的。apache

3.controller 我就不寫了,我就寫經過取回來的code如何獲取openid的方法吧 java端個json

public String  getOpenId(String code) {
    String  openid = "";
        String uri="https://api.weixin.qq.com/sns/oauth2/access_token";
        String requestEntity = "appid=" + 你的appid + "&secret=" + 你的祕鑰 + "&code=" + code + "&grant_type=" + 你的grant_type;
        HttpUriRequest httpUriRequest = RequestBuilder.post()
                .setUri(uri)
                .setHeader("Content-Type", "application/x-www-form-urlencoded")
                .addParameter("_type", "json")
                .setEntity(new StringEntity(requestEntity, Charset.forName("utf-8")))
                .build();
        HttpResponse httpResponse = LocalHttpClient.execute(httpUriRequest);
        try {
            String  result = EntityUtils.toString(httpResponse.getEntity());
            JSONObject jsonObject = JSONObject.fromObject(result);
            openid = jsonObject.getString("openid");
            System.out.println(openid);
        } catch (IOException e) {
            e.printStackTrace();
        }
    
    return openid;
};
獲取到openid就離成功不遠了。
4.經過openid發送紅包(不要看個人返回值redenvelope具體需求具體分析)

public String   sendRedEnvelopes(String openId,String id) throws Exception {
    String  redenvelope="";
    //具體參數查看具體實體類,實體類中的的參數參考微信的紅包發放接口,這裏你直接用map,進行設置參數也能夠。。。
  
    //轉換成發送給爲微信的參數的xml
    SendRedPackBack sendRedPackBack=new SendRedPackBack();
    sendRedPackBack.setNonce_str(MoneyUtils.buildRandom());
    sendRedPackBack.setMch_billno(MoneyUtils.getOrderNo());
    sendRedPackBack.setMch_id(參數實體裏有我就不舉例子了);
    sendRedPackBack.setWxappid();
    sendRedPackBack.setSend_name();
    sendRedPackBack.setRe_openid(openId);
    sendRedPackBack.setTotal_amount();
    sendRedPackBack.setTotal_num();
    sendRedPackBack.setWishing();
    sendRedPackBack.setClient_ip();
    sendRedPackBack.setAct_name();
    //將實體類轉換爲url形式
    String urlParamsByMap = Tool.getUrlParamsByMap(Tool.toMap(sendRedPackBack));
    //拼接咱們再前期準備好的API密鑰,前期準備第5條
    urlParamsByMap += "&key="+證書祕鑰;
    //進行簽名,須要說明的是,若是內容包含中文的話,要使用utf-8進行md5簽名,否則會簽名錯誤
    String sign = Tool.parseStrToMd5L32(urlParamsByMap).toUpperCase();
    sendRedPackBack.setSign(sign);
    //微信要求按照參數名ASCII字典序排序,這裏巧用treeMap進行字典排序
    TreeMap treeMap = new TreeMap(Tool.toMap(sendRedPackBack));
    //而後轉換成xml格式
    String soapRequestData = Tool.getSoapRequestData(treeMap);
    //發起請求前準備
    RequestBody body = RequestBody.create(MediaType.parse("text/xml;charset=UTF-8"), soapRequestData);
    Request request = new Request.Builder()
            .url("https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack")
            .post(body)
            .build();
    //爲http請求設置證書
    SSLSocketFactory socketFactory = getSSL().getSocketFactory();
    X509TrustManager x509TrustManager = Platform.get().trustManager(socketFactory);
    OkHttpClient okHttpClient = new OkHttpClient.Builder().sslSocketFactory(socketFactory, x509TrustManager).build();
    //獲得輸出內容
    Response response = okHttpClient.newCall(request).execute();
    String content = response.body().string();
    System.out.println(content);
    //解析返回數據
    RedDevelop redDevelop= xmlBean(content,id);
    if(redDevelop.getReturnCode().equals("SUCCESS")){
        if(redDevelop.getResultCode().equals("SUCCESS")){
            redenvelope= String.valueOf(redDevelop.getTotalAmount()/100);
            //保存紅包已經被領取
            newUseRegisterService.setRedPack(id);
        }else {
            redenvelope="fail";//接口調取成功可是獲取openid失敗
        }
    }else {
        redenvelope="fail";//接口調取失敗
    }
    return redenvelope;
}

public  SSLContext getSSL() throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
  
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    String mchId=你的微信商戶id;
    //證書位置本身定義
    FileInputStream instream = new FileInputStream(new File(證書路徑));
    try {
        keyStore.load(instream, mchId.toCharArray());
    } finally {
        instream.close();
    }
    SSLContext sslcontext = SSLContexts.custom()
            .loadKeyMaterial(keyStore, mchId.toCharArray())
            .build();
    return sslcontext;
}

//這部分是將調取成功後的xml返回值轉成實體繼續保存,實體就不提供了
public RedDevelop xmlBean(String content,String id){

    RedDevelop redDevelop=new RedDevelop();
    Document dom= null;
    try {
        dom = DocumentHelper.parseText(content);
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    Element root=dom.getRootElement();
    String returnCode=root.element("return_code").getText();
    String returnMsg=root.element("return_msg").getText();
    String resultCode=root.element("result_code").getText();
    String errCode=root.element("err_code").getText();
    String errCodeDes=root.element("err_code_des").getText();
    String mchBillno=root.element("mch_billno").getText();
    String mchId=root.element("mch_id").getText();
    String wxappid=root.element("wxappid").getText();
    String reOpenid=root.element("re_openid").getText();
    String totalAmount=root.element("total_amount").getText();
    redDevelop.setReturnCode(returnCode);
    redDevelop.setReturnMsg(returnMsg);
    redDevelop.setResultCode(resultCode);
    redDevelop.setErrCode(errCode);
    redDevelop.setErrCodeDes(errCodeDes);
    redDevelop.setMchBillno(mchBillno);
    redDevelop.setMchId(mchId);
    redDevelop.setWxappid(wxappid);
    redDevelop.setReOpenid(reOpenid);
    redDevelop.setTotalAmount(Integer.valueOf(totalAmount));
    redDevelop.setRegisterId(id);
    redDevelopService.save(redDevelop);
    return redDevelop;
}
實體類:
package com.sgepm.modules.marketing.entity;

import com.sgepm.common.persistence.DataEntity;


/**
 * Created by zxw on 2018-7-27
 */
public class SendRedPackBack {
    private String nonce_str; //隨機字符串
    private String sign;      //簽名
    private String mch_billno;//商戶訂單號
    private String mch_id;      //商戶號
    private String mchId;      //商戶號
    private String wxappid;     //公衆帳號appid
    private String send_name;       //商戶名稱
    private String re_openid;       //用戶openid
    private Integer total_amount;        //付款金額 單位分
    private Integer total_num;    //付款人數
    private String wishing;         //紅包祝福語
    private String client_ip;       //調用接口的機器Ip地址
    private String act_name;        //活動名稱
    private String remark;          //備註
    private String scene_id;        //場景id
    private String risk_info;       //活動信息
    private String consume_mch_id;  //資金受權商戶號

    public SendRedPackBack() {
    }

    public SendRedPackBack(String nonce_str, String mch_billno, String mch_id, String wxappid, String send_name, String re_openid, Integer total_amount, Integer total_num, String wishing, String client_ip, String act_name) {
        this.nonce_str = nonce_str;
        this.mch_billno = mch_billno;
        this.mch_id = mch_id;
        this.wxappid = wxappid;
        this.send_name = send_name;
        this.re_openid = re_openid;
        this.total_amount = total_amount;
        this.total_num = total_num;
        this.wishing = wishing;
        this.client_ip = client_ip;
        this.act_name = act_name;
    }


    public String 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(String sign) {
        this.sign = sign;
    }

    public String getMch_billno() {
        return mch_billno;
    }

    public void setMch_billno(String mch_billno) {
        this.mch_billno = mch_billno;
    }

    public String getMch_id() {
        return mch_id;
    }

    public void setMch_id(String 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 Integer getTotal_amount() {
        return total_amount;
    }

    public void setTotal_amount(Integer total_amount) {
        this.total_amount = total_amount;
    }

    public Integer getTotal_num() {
        return total_num;
    }

    public void setTotal_num(Integer total_num) {
        this.total_num = total_num;
    }

    public String getWishing() {
        return wishing;
    }

    public void setWishing(String wishing) {
        this.wishing = 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 remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    public String getScene_id() {
        return scene_id;
    }

    public void setScene_id(String scene_id) {
        this.scene_id = scene_id;
    }

    public String getRisk_info() {
        return risk_info;
    }

    public void setRisk_info(String risk_info) {
        this.risk_info = risk_info;
    }

    public String getConsume_mch_id() {
        return consume_mch_id;
    }

    public void setConsume_mch_id(String consume_mch_id) {
        this.consume_mch_id = consume_mch_id;
    }

    public String getMchId() {
        return mchId;
    }

    public void setMchId(String mchId) {
        this.mchId = mchId;
    }


}
工具類:
package com.sgepm.common.utils.weixin;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.Args;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;


public class MoneyUtils {
   private static String appid = "";// 應用ID
   private static String appsecret = "";// 應用密鑰
   private static String partner = "";// 微信支付商戶號
   private static String partnerkey = "";// 財付通初始密�?
   private static String charset = "";

   /**
    * 隨機16爲數值
    * 
    * @return
    */
   public static String buildRandom() {
      String currTime = TenpayUtil.getCurrTime();
      String strTime = currTime.substring(8, currTime.length());
      int num = 1;
      double random = Math.random();
      if (random < 0.1) {
         random = random + 0.1;
      }
      for (int i = 0; i < 4; i++) {
         num = num * 10;
      }
      return (int) ((random * num)) + strTime;
   }

   /**
    * 獲取ip
    * 
    * @param request
    * @return
    */
   public static String getIpAddr(HttpServletRequest request) {
      String ip = request.getHeader("x-forwarded-for");
      if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
         ip = request.getHeader("PRoxy-Client-IP");
      }
      if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
         ip = request.getHeader("WL-Proxy-Client-IP");
      }
      if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
         ip = request.getRemoteAddr();
      }
      if (null == ip) {
         ip = "";
      }
      if (StringUtils.isNotEmpty(ip)) {
         String[] ipArr = ip.split(",");
         if (ipArr.length > 1) {
            ip = ipArr[0];
         }
      }
      return ip;
   }

   /**
    * 建立md5摘要,規則是:按參數名稱a-z排序,遇到空值的參數不參加簽名。 sign
    */
   public static String createSign(Map<String, Object> map) {
      SortedMap<String, String> packageParams = new TreeMap<String, String>();
      for (Map.Entry<String, Object> m : map.entrySet()) {
         packageParams.put(m.getKey(), m.getValue().toString());
      }

      StringBuffer sb = new StringBuffer();
      Set<?> es = packageParams.entrySet();
      Iterator<?> it = es.iterator();
      while (it.hasNext()) {
         Map.Entry entry = (Map.Entry) it.next();
         String k = (String) entry.getKey();
         String v = (String) entry.getValue();
         if (!StringUtils.isEmpty(v) && !"sign".equals(k) && !"key".equals(k)) {
            sb.append(k + "=" + v + "&");
         }
      }
      sb.append("key=" + partnerkey);
       
      
      String sign = MD5Util.MD5Encode(sb.toString(), charset).toUpperCase();
      return sign;
   }

   public static String getOrderNo() {
      String order = partner
            + new SimpleDateFormat("yyyyMMdd").format(new Date());
      Random r = new Random();
      for (int i = 0; i < 10; i++) {
         order += r.nextInt(9);
      }
      return order;
   }

   /*
    * public static void main(String[] args) {
    * System.out.println(getOrderNo()); }
    */

   final static String KEYSTORE_FILE = "D:/works/cert/apiclient_cert.p12";
// final static String KEYSTORE_PASSWORD = "CDATA[簽名錯誤";
   
   public static String doSendMoney(String url, String data) throws Exception {
      KeyStore keyStore  = KeyStore.getInstance("PKCS12");
       FileInputStream instream = new FileInputStream(new File(KEYSTORE_FILE));//P12文件目錄
//    InputStream instream = MoneyUtils.class.getResourceAsStream("/apiclient_cert.p12");
        try {
            keyStore.load(instream, "pamtpamtpamtpamtpamtpamtpamtpamt".toCharArray());//這裏寫密碼..默認是你的MCHID
        } finally {
            instream.close();
        }
        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, "pamtpamtpamtpamtpamtpamtpamtpamt".toCharArray())//這裏也是寫密碼的
                .build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
              SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        try {
           HttpPost httpost = new HttpPost(url); // 設置響應頭信息
           httpost.addHeader("Connection", "keep-alive");
           httpost.addHeader("Accept", "*/*");
           httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
           httpost.addHeader("Host", "api.mch.weixin.qq.com");
           httpost.addHeader("X-Requested-With", "XMLHttpRequest");
           httpost.addHeader("Cache-Control", "max-age=0");
           httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
          httpost.setEntity(new StringEntity(data, "UTF-8"));
            CloseableHttpResponse response = httpclient.execute(httpost);
            try {
                HttpEntity entity = response.getEntity();
                String jsonStr = toStringInfo(response.getEntity(),"UTF-8");
                
                //微信返回的報文時GBK,直接使用httpcore解析亂碼
              //  String jsonStr = EntityUtils.toString(response.getEntity(),"UTF-8");
                EntityUtils.consume(entity);
               return jsonStr;
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
   }
   
   private static String toStringInfo(HttpEntity entity, String defaultCharset) throws Exception, IOException{
      final InputStream instream = entity.getContent();
       if (instream == null) {
           return null;
       }
       try {
           Args.check(entity.getContentLength() <= Integer.MAX_VALUE,
                   "HTTP entity too large to be buffered in memory");
           int i = (int)entity.getContentLength();
           if (i < 0) {
               i = 4096;
           }
           Charset charset = null;
           
           if (charset == null) {
               charset = Charset.forName(defaultCharset);
           }
           if (charset == null) {
               charset = HTTP.DEF_CONTENT_CHARSET;
           }
           final Reader reader = new InputStreamReader(instream, charset);
           final CharArrayBuffer buffer = new CharArrayBuffer(i);
           final char[] tmp = new char[1024];
           int l;
           while((l = reader.read(tmp)) != -1) {
               buffer.append(tmp, 0, l);
           }
           return buffer.toString();
       } finally {
           instream.close();
       }
   }
   
   public static String createXML(Map<String, Object> map){
      String xml = "<xml>";
      Set<String> set = map.keySet();
      Iterator<String> i = set.iterator();
      while(i.hasNext()){
         String str = i.next();
         xml+="<"+str+">"+"<![CDATA["+map.get(str)+"]]>"+"</"+str+">";
      }
      xml+="</xml>";
      return xml;
   }
}

 

package com.sgepm.common.utils.weixin;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

/**
 * Created by  on 2016/9/6.
 */
public class Tool {


    /**
     * 獲取訂單號
     * @return
     */
    public static String getOrderNum(){

        return String.valueOf(System.currentTimeMillis())+getRandom4();

    }


    /**
     * 獲取一個4位隨機數
     * @return
     */
    public static int getRandom4(){
        int x = RandomUtils.nextInt(1000,9999);
        return x;
    }

    /**
     * 獲取UUID
     * @return
     */
    public static String returnUUID() {
        return parseStrToMd5L32(UUID.randomUUID().toString());
    }

    /**
     * 獲取md5
     * @param str
     * @return
     */
    public static String parseStrToMd5L32(String str) {
        return parseStrToMd5L32(str,"utf-8");
    }

    public static String parseStrToMd5L32(String str, String charset) {
        String reStr = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(str.getBytes(charset));
            StringBuffer stringBuffer = new StringBuffer();
            for (byte b : bytes) {
                int bt = b & 0xff;
                if (bt < 16) {
                    stringBuffer.append(0);
                }
                stringBuffer.append(Integer.toHexString(bt));
            }
            reStr = stringBuffer.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return reStr;
    }

    /**
     * 將map轉換成url
     * @param map
     * @return
     */
    public static String getUrlParamsByMap(Map<String, String> map) {
        if (map == null) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        map = new TreeMap<String, String>(map);
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if(entry.getValue() == null){
                continue;
            }
            sb.append(entry.getKey() + "=" + entry.getValue());
            sb.append("&");
        }
        String s = sb.toString();
        if (s.endsWith("&")) {
            s = StringUtils.substringBeforeLast(s, "&");
        }
        return s;
    }

    /**
     * Sha1加密方法
     */
    public static String getSha1(String decript) {
        try {
            MessageDigest digest = MessageDigest
                    .getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字節數組轉換爲 十六進制 數
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }


    public static Map toMap(Object bean) {
        Class<? extends Object> clazz = bean.getClass();
        Map<Object, Object> returnMap = new HashMap<Object, Object>();
        BeanInfo beanInfo = null;
        try {
            beanInfo = Introspector.getBeanInfo(clazz);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (int i = 0; i < propertyDescriptors.length; i++) {
                PropertyDescriptor descriptor = propertyDescriptors[i];
                String propertyName = descriptor.getName();
                if (!propertyName.equals("class")) {
                    Method readMethod = descriptor.getReadMethod();
                    Object result = null;
                    result = readMethod.invoke(bean, new Object[0]);
                    if (null != propertyName) {
                        propertyName = propertyName.toString();
                    }
                    if (null != result) {
                        result = result.toString();
                        returnMap.put(propertyName, result);
                    }
                }
            }
        } catch (IntrospectionException e) {
            System.out.println("分析類屬性失敗");
        } catch (IllegalAccessException e) {
            System.out.println("實例化 JavaBean 失敗");
        } catch (IllegalArgumentException e) {
            System.out.println("映射錯誤");
        } catch (InvocationTargetException e) {
            System.out.println("調用屬性的 setter 方法失敗");
        }
        return returnMap;
    }

    /**
     * 湊成xml格式字符串
     *
     * @return
     */
    public static String getSoapRequestData(Map<String, String> map) throws JSONException {

        StringBuffer sb = new StringBuffer();

        sb.append("<xml>");

        for (Map.Entry<String, String> entry : map.entrySet()) {

            sb.append("<" + entry.getKey() + ">" + entry.getValue() + "</" + entry.getKey() + ">");
        }

        sb.append("</xml>");
        return sb.toString();
    }


}
接口返回類:
package com.sgepm.modules.marketing.entity;

import org.hibernate.validator.constraints.Length;
import com.sgepm.modules.sys.entity.Office;

import com.sgepm.common.persistence.DataEntity;

/**
 * 紅包管理Entity
 * @author zxw
 * @version 2018-08-02
 */
public class RedDevelop extends DataEntity<RedDevelop> {
   
   private static final long serialVersionUID = 1L;
   private String returnCode;    // 返回狀態碼
   private String returnMsg;     // 返回信息
   private String resultCode;    // 業務結果
   private String errCode;       // 錯誤代碼
   private String errCodeDes;    // 錯誤代碼描述
   private String mchBillno;     // 商戶訂單號
   private String mchId;     // 商戶號
   private String wxappid;       // 公衆帳號appid
   private String reOpenid;      // 用戶openid
   private Integer totalAmount;      // 付款金額
   private String sendListid;    // 微信單號
   private String registerId;    //註冊人id
   private Office office;    // 歸屬機構
   
   public RedDevelop() {
      super();
   }

   public RedDevelop(String id){
      super(id);
   }

   @Length(min=0, max=16, message="返回狀態碼長度必須介於 0 和 16 之間")
   public String getReturnCode() {
      return returnCode;
   }

   public void setReturnCode(String returnCode) {
      this.returnCode = returnCode;
   }
   
   @Length(min=0, max=128, message="返回信息長度必須介於 0 和 128 之間")
   public String getReturnMsg() {
      return returnMsg;
   }

   public void setReturnMsg(String returnMsg) {
      this.returnMsg = returnMsg;
   }
   
   @Length(min=0, max=16, message="業務結果長度必須介於 0 和 16 之間")
   public String getResultCode() {
      return resultCode;
   }

   public void setResultCode(String resultCode) {
      this.resultCode = resultCode;
   }
   
   @Length(min=0, max=32, message="錯誤代碼長度必須介於 0 和 32 之間")
   public String getErrCode() {
      return errCode;
   }

   public void setErrCode(String errCode) {
      this.errCode = errCode;
   }
   
   @Length(min=0, max=128, message="錯誤代碼描述長度必須介於 0 和 128 之間")
   public String getErrCodeDes() {
      return errCodeDes;
   }

   public void setErrCodeDes(String errCodeDes) {
      this.errCodeDes = errCodeDes;
   }
   
   @Length(min=0, max=28, message="商戶訂單號長度必須介於 0 和 28 之間")
   public String getMchBillno() {
      return mchBillno;
   }

   public void setMchBillno(String mchBillno) {
      this.mchBillno = mchBillno;
   }
   
   @Length(min=0, max=32, message="商戶號長度必須介於 0 和 32 之間")
   public String getMchId() {
      return mchId;
   }

   public void setMchId(String mchId) {
      this.mchId = mchId;
   }
   
   @Length(min=0, max=32, message="公衆帳號appid長度必須介於 0 和 32 之間")
   public String getWxappid() {
      return wxappid;
   }

   public void setWxappid(String wxappid) {
      this.wxappid = wxappid;
   }
   
   @Length(min=0, max=32, message="用戶openid長度必須介於 0 和 32 之間")
   public String getReOpenid() {
      return reOpenid;
   }

   public void setReOpenid(String reOpenid) {
      this.reOpenid = reOpenid;
   }
   
   public Integer getTotalAmount() {
      return totalAmount;
   }

   public void setTotalAmount(Integer totalAmount) {
      this.totalAmount = totalAmount;
   }
   
   @Length(min=0, max=32, message="微信單號長度必須介於 0 和 32 之間")
   public String getSendListid() {
      return sendListid;
   }

   public void setSendListid(String sendListid) {
      this.sendListid = sendListid;
   }
   
   public Office getOffice() {
      return office;
   }

   public void setOffice(Office office) {
      this.office = office;
   }

   public String getRegisterId() {
      return registerId;
   }

   public void setRegisterId(String registerId) {
      this.registerId = registerId;
   }
}
6.這就是所有過程若是有遺漏你們多多體諒,畢竟這些是我用好長時間整理出來的 但願對大家有幫助 曬幾張圖片

 

相關文章
相關標籤/搜索