微信企业号(三)-发送消息给企业号指定成员

1、通过代码控制微信企业号向指定成员发送消息。

发送消息的URL:https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN


2、发送消息代码

package com.py.weixin.msg;

import com.py.weixin.util.ComUtil;
import com.py.weixin.util.ParamesAPI;

import net.sf.json.JSONObject;


public class TestSendMes {
//	发送消息
public static String SEND_MSG_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN";
	
public static void main(String[] args) {
	//应用ID,账号,部门为"",标签为"",消息类型,内容
    //部门不为"",标签不为"",将会给该部门的每个成员发送消息
	Send_msg("1","username","","","text","hello");

}

/**
 * @Description : 主动发送文字给企业用户
 */
public static int Send_msg(String agentid,String  touser,String toparty,String totag,String msgtype,String content){
	int errCode=0;
	//拼接请求地址
	String requestUrl=SEND_MSG_URL.replace("ACCESS_TOKEN",  ComUtil.getAccessToken(ParamesAPI.corpId, ParamesAPI.corpsecret));
	//需要提交的数据
	String postJson = "{\"agentid\":\"%s\",\"touser\":\"%s\",\"toparty\":\"[1, %s]\",\"totag\":\"%s\",\"msgtype\":\"text\",\"%s\":{\"content\":\"%s\"},\"safe\":\"0\"}";	
	String outputStr=String.format(postJson,agentid,touser,toparty,totag,msgtype, content);
	System.out.println(outputStr);
	//创建成员
	JSONObject jsonObject=ComUtil.httpsRequest(requestUrl, "POST", outputStr);
	if(null!=jsonObject){
		System.out.println(jsonObject.toString()+"=====");
//		    int errcode = jsonObject.getInt("errcode");
//			errCode=jsonObject.getInt("errcode");
			
	}
	return errCode;
}
}

以上测试是一年前写的,微信貌似有改动,以下是亲测的,或者可以下载源码看,源码测试成功过的

package com.kp.qy.util;

import net.sf.json.JSONObject;

/** 
 * @author: py
 * @version:2016年12月31日 上午8:48:29 
 * com.kp.qy.util.TestSendMes.java
 * @Desc 
 */
public class TestSendMes {
//  发送消息  
public static String SEND_MSG_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN";  
      
public static void main(String[] args) {  
    //应用ID,账号,部门为"",标签为"",消息类型,内容  
    //部门不为"",标签不为"",将会给该部门的每个成员发送消息  
    Send_msg("yoyo","","1","text",1,"hello");  
  
}  
  
/**
 * @date 2016年12月31日上午10:05:07
 * @param touser 成员ID列表
 * @param toparty 部门ID列表
 * @param totag 标签ID列表
 * @param msgtype 消息类型,此时固定为:text (支持消息型应用跟主页型应用)
 * @param agentid 企业应用的id,整型。可在应用的设置页面查看
 * @param content 消息内容,最长不超过2048个字节,注意:主页型应用推送的文本消息在微信端最多只显示20个字(包含中英文)
 * @return int 表示是否是保密消息,0表示否,1表示是,默认0
 * @Des: 主动发送文字给企业用户 
 */
public static int Send_msg(String  touser,String toparty,String totag,String msgtype,int agentid,String content){  
    int errCode=0;  
    //拼接请求地址  
    String requestUrl=SEND_MSG_URL.replace("ACCESS_TOKEN",  WechatAccessToken.getAccessToken(Constants.CORPID, Constants.SECRET,1).getToken());  
    //需要提交的数据  
//    String postJson = "{\"agentid\":\"%s\",\"touser\":\"%s\",\"toparty\":\"[1,%s]\",\"totag\":\"%s\",\"msgtype\":\"text\",\"%s\":{\"content\":\"%s\"},\"safe\":\"0\"}";      
//    String postJson = "{\"agentid\":\"%s\",\"touser\":\"%s\",\"toparty\":\"%s\",\"totag\":\"%s\",\"msgtype\":\"text\",\"%s\":{\"content\":\"%s\"},\"safe\":\"0\"}";      
    String postJson = "{\"agentid\":%s,\"touser\": \"%s\",\"toparty\": \"%s\",\"totag\": \"%s\","+
     "\"msgtype\":\"%s\",\"text\": {\"content\": \"%s\"},\"safe\":0}";
    String outputStr=String.format(postJson,agentid,touser,toparty,totag,msgtype,content);  
    System.out.println(outputStr);  
    //创建成员  
    JSONObject jsonObject=HttpRequestUtil.httpRequest(requestUrl, "POST", outputStr);  
    if(null!=jsonObject){  
        System.out.println(jsonObject.toString()+"=====");  
//          int errcode = jsonObject.getInt("errcode");  
//          errCode=jsonObject.getInt("errcode");  
              
    }  
    return errCode;  
}  
}

记得更改自己的配置

package com.kp.qy.util;

public class Constants {
	/**
	 * 常量说明:
	 * 此处定义的常量需要持久化,可以保存在数据库中,在需要的地方读取。
	 * 在多企业号中,最好以每个应用来定义。
	 */
	public static final int AGENTID = 1;
	public static final String TOKEN = "";
	public static final String CORPID = "";
	public static final String SECRET = "";
	public static final String encodingAESKey = "";
}


3、工具类

package com.py.weixin.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.py.weixin.weixinapi.MyX509TrustManager;


/**
 * 通用工具类
 * 
 */
public class ComUtil {
	private static Logger log = LoggerFactory.getLogger(ComUtil.class);

	// 凭证获取(GET)
	public final static String token_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=CORPID&corpsecret=CORPSECRET";

	/**
	 * 发送https请求
	 * 
	 * @param requestUrl 请求地址
	 * @param requestMethod 请求方式(GET、POST)
	 * @param outputStr 提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */
	public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
		JSONObject jsonObject = null;
		try {
			// 创建SSLContext对象,并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
			conn.setSSLSocketFactory(ssf);
			
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			// 设置请求方式(GET/POST)
			conn.setRequestMethod(requestMethod);

			// 当outputStr不为null时向输出流写数据
			if (null != outputStr) {
				OutputStream outputStream = conn.getOutputStream();
				// 注意编码格式
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			// 从输入流读取返回内容
			InputStream inputStream = conn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			StringBuffer buffer = new StringBuffer();
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}

			// 释放资源
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			conn.disconnect();
			jsonObject = JSONObject.fromObject(buffer.toString());
		} catch (ConnectException ce) {
			log.error("连接超时:{}", ce);
		} catch (Exception e) {
			log.error("https请求异常:{}", e);
		}
		return jsonObject;
	}

	/**
	 * 获取接口访问凭证
	 * 
	 * @param corpid 凭证
	 * @param corpsecret 密钥
	 * @return
	 */
	public static String getAccessToken(String corpid, String corpsecret) {
		String access_token = "";
		String requestUrl = token_url.replace("CORPID", corpid).replace("CORPSECRET", corpsecret);
		// 发起GET请求获取凭证
		JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);

		if (null != jsonObject) {
			try {
				access_token = jsonObject.getString("access_token");
			} catch (JSONException e) {
				access_token = null;
				// 获取token失败
				log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
			}
		}
		return access_token;
	}
	
}

4、实现X509TrustManager

package com.py.weixin.weixinapi;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;

/**
 * 信任管理器
 * 
 */
public class MyX509TrustManager implements X509TrustManager {

	// 检查客户端证书
	public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
	}

	// 检查服务器端证书
	public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
	}

	// 返回受信任的X509证书数组
	public X509Certificate[] getAcceptedIssuers() {
		return null;
	}
}


5、运行main方法就可以向指定成员发送消息了。


6、源码地址http://download.csdn.net/detail/u014520797/9726045


评论 20
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值