Java快速ドッキング微信現金お年玉

39008 ワード

ツールパック:
import com.king.kong.tzj.util.MD5Util;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.security.KeyStore;
import java.util.*;

/**
 *       
 */
public class WXRedPack {

    public static final String KEY = "--------  --------";  
    public static final String MCH_ID = "--------   --------";              
    public static final String WXAPPID = "--------   appid--------";            


    /**
     * @param mch_billno        
     * @param openId         openid
     * @param send_name        
     * @param total_amount     
     * @param total_num           
     * @param wishing           
     * @param act_name         
     * @param remark         
     * @param client_ip    Ip  
     * @throws Exception
     */
    public static void sendRedPack(String mch_billno,String openId,String send_name,String total_amount,String total_num,String wishing,String act_name,String remark,String client_ip) throws Exception{
        SortedMap<Object, Object> p = new TreeMap<Object, Object>();
        p.put("nonce_str", String.valueOf(new Date().getTime()));
        p.put("mch_billno", mch_billno);
        p.put("mch_id", MCH_ID);  //   
        p.put("wxappid", WXAPPID);     //    appid
        p.put("re_openid", openId);
        p.put("total_amount", total_amount);
        p.put("total_num", "1");
        p.put("client_ip", client_ip);
        p.put("act_name",act_name);
        p.put("send_name", send_name);
        p.put("wishing", wishing);
        p.put("remark",remark);
        //        ,      200    1    
        if (Integer.valueOf(total_amount).intValue() > 200 || Integer.valueOf(total_amount).intValue() < 1 ){
            p.put("scene_id","PRODUCT_1");
        }
        //    
        sign(p);
        //    
        String reuqestXml = getRequestXml(p);
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        FileInputStream instream = new FileInputStream(new File("------      ------"));
        try {
            keyStore.load(instream, MCH_ID.toCharArray());
        } finally {
            instream.close();
        }

        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore,
                MCH_ID.toCharArray()).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext, new String[] { "TLSv1" }, null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf).build();
        try {

            HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack");

            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

            System.out.println("executing request" + httpPost.getRequestLine());
            //   xml    iso8859-1  ,                    
            StringEntity reqEntity = new StringEntity(new String(reuqestXml.getBytes(), "ISO8859-1"));
            //     
            httpPost.setEntity(reqEntity);
            CloseableHttpResponse response = httpclient.execute(httpPost);
            try {
                HttpEntity entity = response.getEntity();

                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    System.out.println("Response content length: " + entity.getContentLength());
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
                    String text;
                    while ((text = bufferedReader.readLine()) != null) {
                        System.out.println(text);
                    }
                }
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }

    /**
     *     
     * @param params
     * @return
     */
    public static String getRequestXml(SortedMap<Object, Object> params) {
        StringBuffer sb = new StringBuffer();
        sb.append("");
        Set es = params.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 ("nick_name".equalsIgnoreCase(k) || "send_name".equalsIgnoreCase(k) || "wishing".equalsIgnoreCase(k) || "act_name".equalsIgnoreCase(k) || "remark".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
                sb.append(" + k + ">" + " + v + "]]>" + k + ">");
            } else {
                sb.append(" + k + ">" + v + "" + k + ">");
            }
        }
        sb.append("");
        return sb.toString();
    }

    /**
     *       ASCII          
     */
    public static void sign(SortedMap<Object, Object> params) {
        Set<Map.Entry<Object, Object>> entrys = params.entrySet();
        Iterator<Map.Entry<Object, Object>> it = entrys.iterator();
        String result = "";
        while (it.hasNext()) {
            Map.Entry<Object, Object> entry = it.next();
            result += entry.getKey() + "=" + entry.getValue() + "&";
        }
        result += "key=" + KEY;
        String sign = null;
        try {
            sign = MD5Util.encrypt(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        params.put("sign", sign);
    }

}

呼び出し例:
WXRedPack.sendRedPack(order.getOrderNo(),userInfo.getWxid(),"--    --",String.valueOf(value),String.valueOf(1),"     ****,      !","**  ","24             ","139.9.191.218");

微信現金お年玉開発文書の住所:https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_1