微信公众号下发红包功能

不会写文章,直接贴代码。。。。啧啧啧。


package com.sxit.web.weixin;



import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyStore;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;


import javax.net.ssl.SSLContext;


import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.conn.ManagedHttpClientConnectionFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


import com.sxit.web.weixin.vo.WxPayParam;
import com.sxit.web.weixin.wxcom.MD5;
import com.sxit.web.weixin.wxcom.Md5Utils;
public class Weixinpay {


// https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers
public boolean sendMoney(String openid,int money) {

if(money>100){//最高0.9,大于1都是错的,防止有人改
return false;
}
try {

WxPayParam wxPayParam = new WxPayParam();
wxPayParam.setMch_appid("wx71d1fc9fbafd4938");
wxPayParam.setMchid("1239149002");
wxPayParam.setSub_mch_id("");
wxPayParam.setDevice_info("");
wxPayParam.setNonce_str(new SimpleDateFormat("yyyyMMhhHHmmss").format(new Date()));
wxPayParam.setPartner_trade_no(new Date().getTime()+"");
wxPayParam.setOpenid(openid);
wxPayParam.setCheck_name("NO_CHECK");
wxPayParam.setRe_user_name("");
wxPayParam.setAmount(money + "");
wxPayParam.setDesc("test");
wxPayParam.setSpbill_create_ip("203.195.244.64");

System.out.println(wxPayParam.toString());
//加入请求 证书---
 KeyStore trustStore = KeyStore.getInstance("PKCS12");
 //File file=new File("//data//apache-tomcat-8886//webapps//newyoufang//WEB-INF//lib//apiclient_cert.p12");
       FileInputStream instream = new FileInputStream(new File("//data//apache-tomcat-8886//webapps//newyoufang//WEB-INF//lib//apiclient_cert.p12"));
       try {
           trustStore.load(instream, "1239149002".toCharArray());
       } finally {
           instream.close();
       }


       // Trust own CA and all self-signed certs
       SSLContext sslcontext = SSLContexts.custom()
           .loadKeyMaterial(trustStore, "1239149002".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();

// Allow TLSv1 protocol only







String url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
   //=================
//PostMethod post = new PostMethod(url);
HttpPost  post = new HttpPost(url);
//=============
SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
parameters.put("mch_appid",wxPayParam.getMch_appid());
parameters.put("mchid",wxPayParam.getMchid());
// parameters.put("sub_mch_id",wxPayParam.getSub_mch_id());
//parameters.put("device_info",wxPayParam.getDevice_info());
parameters.put("nonce_str",wxPayParam.getNonce_str());

parameters.put("partner_trade_no",wxPayParam.getPartner_trade_no());
parameters.put("openid",wxPayParam.getOpenid());
parameters.put("check_name",wxPayParam.getCheck_name());
//parameters.put("re_user_name",wxPayParam.getRe_user_name());
parameters.put("amount",wxPayParam.getAmount());
parameters.put("desc",wxPayParam.getDesc());
parameters.put("spbill_create_ip",wxPayParam.getSpbill_create_ip());
System.out.println(parameters.toString());
wxPayParam.setSign(this.createSignNew("utf-8", parameters,"shenzhenyoufangyoujia12345678901"));
parameters.put("sign",wxPayParam.getSign());
parameters.put("re_user_name","");
String requestXML = getRequestXml(parameters);
System.out.println(wxPayParam.getSign());
System.out.println(requestXML);
//=======重新封装参数start
List<NameValuePair> listparm = new ArrayList<NameValuePair>();
listparm.add(new BasicNameValuePair("mch_appid", wxPayParam.getMch_appid()));
listparm.add(new BasicNameValuePair("mchid",wxPayParam.getMchid()));
listparm.add(new BasicNameValuePair("nonce_str",wxPayParam.getNonce_str()));
listparm.add(new BasicNameValuePair("partner_trade_no",wxPayParam.getPartner_trade_no()));
listparm.add(new BasicNameValuePair("openid",wxPayParam.getOpenid()));
listparm.add(new BasicNameValuePair("check_name",wxPayParam.getCheck_name()));
listparm.add(new BasicNameValuePair("desc",wxPayParam.getDesc()));
listparm.add(new BasicNameValuePair("spbill_create_ip",wxPayParam.getSpbill_create_ip()));
listparm.add(new BasicNameValuePair("sign",wxPayParam.getSign()));
////////=======重新封装参数end
String info = "";
try {
StringEntity entity = new StringEntity(requestXML);
post.setEntity(entity);
 post.setHeader("Content-Type", "text/xml;charset=ISO-8859-1");
// RequestEntity entity = new StringRequestEntity(requestXML, "text/xml","UTF-8");
//HttpEntity entity  = new HttpClient();
//StringRequestEntity entity= new StringRequestEntity(requestXML, "text/xml","UTF-8");
// UrlEncodedFormEntity entity = new UrlEncodedFormEntity(listparm);
CloseableHttpResponse response = httpclient.execute(post);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity returnEntity = response.getEntity();
if(returnEntity !=null){
info = EntityUtils.toString(returnEntity);
System.out.println(info);
//读取XML
      Map<String, String> resultMap = parseXMl(info);
      if(resultMap.get("return_code").equals("SUCCESS")){
      //插入记录
      return true;
      }else{
      return false;
      }
            

         

//returnEntity.consumeContent();
}
}else{
return false;
}


//post.setRequestEntity(entity);
// client.executeMethod(post);
//int code = post.getStatusCode();
// if (code == HttpStatus.SC_OK)
// info = new String(post.getResponseBodyAsString().getBytes("UTF-8"), "UTF-8");// 接口返回的信息
// System.out.println(info);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
post.releaseConnection();
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
return false;
}


public String createSign(WxPayParam wxPayParam) {
StringBuffer sb = new StringBuffer();
sb.append("amount=" + wxPayParam.getAmount() + "&");
sb.append("check_name=" + wxPayParam.getCheck_name() + "&");
sb.append("desc=" + wxPayParam.getDesc() + "&");
sb.append("mch_appid=" + wxPayParam.getMch_appid() + "&");
sb.append("mchid=" + wxPayParam.getMchid() + "&");
sb.append("nonce_str=" + wxPayParam.getNonce_str() + "&");
sb.append("openid=" + wxPayParam.getOpenid() + "&");
sb.append("partner_trade_no=" + wxPayParam.getPartner_trade_no() + "&");
sb.append("spbill_create_ip=" + wxPayParam.getSpbill_create_ip() + "&");
sb.append("key=shenzhenyoufangyoujia12345678901");
String signMd5 = MD5.md5(sb.toString());
String sign = signMd5.toUpperCase();
return sign;
}

public  String createSignNew(String characterEncoding,SortedMap<Object,Object> parameters,String wxKey){
StringBuffer sb = new StringBuffer();
Set es = parameters.entrySet();
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
Object v = entry.getValue();
if(null != v && !"".equals(v) 
&& !"sign".equals(k) && !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key="+wxKey);
System.out.println(sb.toString());
String sign = Md5Utils.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
return sign;
}


public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flust输出流的缓冲
out.flush();
// 定义BufferedReader输出流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}


} catch (Exception ex) {
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
}
}
return result;
}
public   Map<String, String>  parseXMl(String strXMl) throws Exception{
   
    Map<String,String>  map = new HashMap<String, String>();
    InputStream   inputStream  = new ByteArrayInputStream(strXMl.getBytes("UTF-8"));
    SAXReader   reader  =new SAXReader();
    Document     document =reader.read(inputStream);
        Element   root =document.getRootElement();
        List<Element>  elementList = root.elements();
        for(Element  e :elementList){
        map.put(e.getName(), e.getText());
        }
        inputStream.close();
        inputStream =null;
    return map;
    }

    public  String getRequestXml(SortedMap<Object,Object> parameters){
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set es = parameters.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 ("attach".equalsIgnoreCase(k)||"body".equalsIgnoreCase(k)||"sign".equalsIgnoreCase(k)) {
                sb.append("<"+k+">"+"<![CDATA["+v+"]]></"+k+">");
            }else {
                sb.append("<"+k+">"+v+"</"+k+">");
            }
        }
        sb.append("</xml>");
       return sb.toString();
//        String test="<xml><mch_appid>wx71d1fc9fbafd4938</mch_appid><mchid>1239149002</mchid><nonce_str>20150701013527</nonce_str><partner_trade_no>1436722527829</partner_trade_no><openid>oQVC9t1_bFWqX2bNaGjIk_ShWszs</openid><check_name>OPTION_CHECK</check_name><re_user_name>张三</re_user_name><amount>10</amount><desc>test</desc><spbill_create_ip>203.195.244.64</spbill_create_ip><sign>04F8BFD76749BD3A45220DEF24CC99AC</sign></xml>";
    }


}





/*
 * ====================================================================
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */
package httpstest;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.security.KeyStore;


import javax.net.ssl.SSLContext;


import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;


/**
 * This example demonstrates how to create secure connections with a custom SSL
 * context.
 */
public class ClientCustomSSL {


    public final static void main(String[] args) throws Exception {
        KeyStore keyStore  = KeyStore.getInstance("PKCS12");
        FileInputStream instream = new FileInputStream(new File("D:/10016225.p12"));
        try {
            keyStore.load(instream, "10016225".toCharArray());
        } finally {
            instream.close();
        }


        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, "10016225".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 {


            HttpGet httpget = new HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");


            System.out.println("executing request" + httpget.getRequestLine());


            CloseableHttpResponse response = httpclient.execute(httpget);
            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()));
                    String text;
                    while ((text = bufferedReader.readLine()) != null) {
                        System.out.println(text);
                    }
                   
                }
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值