package com.kakarote.crm9.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.kakarote.crm9.erp.admin.entity.AdminRecord;
import com.kakarote.crm9.erp.oa.entity.OaExamine;
import com.kakarote.crm9.erp.oa.entity.OaExamineRecord;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* 获取用户openid及公众号openid,发送模板消息
* create by m4sk
*
*/
public class wechatMsg {
public final static Prop prop = PropKit.use("config/crm9-config.txt");
public static void main(String[] args) {
// wechatMsg wm = new wechatMsg();
// wm.SendWeChatMsg(wm.getToken());
}
/**
* 通过小程序 获取用户的openid
* 不是关注公众号的openid
* 获取openid
* @return token
*/
public static String queryOpenid(String code){
String grant_type = "client_credential";
String appid =prop.get("wx.AppID");
String secret = prop.get("wx.AppSecret");
String getTokenApi="https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";
String tokenJsonStr = doGetPost(getTokenApi,"GET",null);
JSONObject tokenJson = JSONObject.parseObject(tokenJsonStr);
String openid = tokenJson.get("openid").toString();
System.out.println("获取到的TOKEN : "+openid);
return openid;
}
/**
* 回调URL
* 获取用户关注的公众号的openid
* @return 关注的公众号的openid
*/
public static String queryDyOpenid(String code){
//授予形式
String grant_type = "client_credential";
String appid =prop.get("wx.GZHAppID");
String secret = prop.get("wx.GZHSecret");
//接口地址拼接参数
String getTokenApi = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
String tokenJsonStr = doGetPost(getTokenApi,"GET",null);
JSONObject tokenJson = JSONObject.parseObject(tokenJsonStr);
String openid = tokenJson.get("openid").toString();
return openid;
}
/**
* 获取网页授权access_token
* @return token
*/
public static String getAccess_token(String refresh_token){
//授予形式
String grant_type = "client_credential";
String appid =prop.get("wx.AppID");
String secret = prop.get("wx.AppSecret");
//接口地址拼接参数
String getTokenApi = " https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" +appid+
"&grant_type=refresh_token&refresh_token="+refresh_token;
String tokenJsonStr = doGetPost(getTokenApi,"GET",null);
JSONObject tokenJson = JSONObject.parseObject(tokenJsonStr);
String openid = tokenJson.get("openid").toString();
return openid;
}
/**
* 获取模板token
* @return token
*/
public static String getToken(){
//授予形式
String grant_type = "client_credential";
String appid =prop.get("wx.GZHAppID");
String secret = prop.get("wx.GZHSecret");
//接口地址拼接参数
String getTokenApi = "https://api.weixin.qq.com/cgi-bin/token?grant_type="+grant_type+"&appid="+appid+"&secret="+secret;
String tokenJsonStr = doGetPost(getTokenApi,"GET",null);
JSONObject tokenJson = JSONObject.parseObject(tokenJsonStr);
String token = tokenJson.get("access_token").toString();
System.out.println("获取到的TOKEN : "+token);
return token;
}
/***
* 发送流程待审批提醒,
* @param first 流程待审批提醒
* @param keyword1 流程名称
* @param keyword2 申请人
* @param keyword3 申请时间
* @param keyword4 流程摘要
*/
public static void Send_wait(Integer recordid,String openId,String first,String keyword1,String keyword2,String keyword3,String keyword4){
if (openId!=null&&!"".equals(openId)) {
String token = getToken();
//接口地址
String sendMsgApi = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
//openId
String toUser = openId;
//消息模板ID
String template_id = prop.get("wx.template_wait");
String toUrl = "http://weixin.qq.com/download";
//整体参数map
Map<String, Object> paramMap = new HashMap<String, Object>();
//点击消息跳转相关参数map
Map<String, String> miniprogramMap = new HashMap<String, String>();
//消息主题显示相关map
Map<String, Object> dataMap = new HashMap<String, Object>();
String appid =prop.get("wx.AppID");
miniprogramMap.put("appid",appid);//所需跳转到的小程序appid(该小程序appid必须与发模板消息的公众号是绑定关联关系,暂不支持小游戏)
OaExamineRecord oaExamineRecord =OaExamineRecord.dao.findById(recordid);
miniprogramMap.put("pagepath", "/pages/examine/show/index?id="+ oaExamineRecord.getExamineId() + "&category=" + keyword1 + "&recordid=" + recordid);//所需跳转到小程序的具体页面路径,支持带参数,(示例index?foo=bar),要求该小程序已发布,暂不支持小游戏
dataMap.put("first", getValue(first));
dataMap.put("keyword1", getValue(keyword1));
dataMap.put("keyword2", getValue(keyword2));
dataMap.put("keyword3", getValue(keyword3));
dataMap.put("keyword4", getValue(keyword4));
paramMap.put("touser", toUser);
paramMap.put("template_id", template_id);
paramMap.put("url", toUrl);//模板跳转链接(海外帐号没有跳转能力)
paramMap.put("miniprogram", miniprogramMap);
paramMap.put("data", dataMap);
String res=doGetPost(sendMsgApi, "POST", paramMap);
System.out.println("res:" + res);
}
}
/***
* 发送 审批结果通知
* @param first 流程待审批提醒
* @param keyword1 流程名称
* @param keyword2 申请人
* @param keyword3 申请时间
* @param keyword4 流程摘要
* @param keyword5 流程摘要
*/
public static void Send_result(String openId,String first,String keyword1,String keyword2,String keyword3,String keyword4,String keyword5){
if (openId!=null&&!"".equals(openId)) {
String token = getToken();
//接口地址
String sendMsgApi = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
//openId
String toUser = openId;
//消息模板ID
String template_id = prop.get("wx.template_result");
String toUrl = "http://weixin.qq.com/download";
//整体参数map
Map<String, Object> paramMap = new HashMap<String, Object>();
//点击消息跳转相关参数map
Map<String, String> miniprogramMap = new HashMap<String, String>();
//消息主题显示相关map
Map<String, Object> dataMap = new HashMap<String, Object>();
miniprogramMap.put("appid", "");
miniprogramMap.put("pagepath", "");
dataMap.put("first", getValue(first));
dataMap.put("keyword1", getValue(keyword1));
dataMap.put("keyword2", getValue(keyword2));
dataMap.put("keyword3", getValue(keyword3));
dataMap.put("keyword4", getValue(keyword4));
dataMap.put("keyword5", getValue(keyword5));
paramMap.put("touser", toUser);
paramMap.put("template_id", template_id);
paramMap.put("url", toUrl);
paramMap.put("miniprogram", miniprogramMap);
paramMap.put("data", dataMap);
System.out.println(doGetPost(sendMsgApi, "POST", paramMap));
}
}
public static JSONObject getValue(String value) {
// TODO Auto-generated method stub
JSONObject json = new JSONObject();
json.put("value", value);
json.put("color", "#173177");
return json;
}
/**
* 调用接口 post
* @param apiPath
*/
public static String doGetPost(String apiPath,String type,Map<String,Object> paramMap){
OutputStreamWriter out = null;
InputStream is = null;
String result = null;
try{
URL url = new URL(apiPath);// 创建连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod(type) ; // 设置请求方式
connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
connection.connect();
if(type.equals("POST")){
out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
out.append(JSON.toJSONString(paramMap));
out.flush();
out.close();
}
// 读取响应
is = connection.getInputStream();
int length = (int) connection.getContentLength();// 获取长度
if (length != -1) {
byte[] data = new byte[length];
byte[] temp = new byte[512];
int readLen = 0;
int destPos = 0;
while ((readLen = is.read(temp)) > 0) {
System.arraycopy(temp, 0, data, destPos, readLen);
destPos += readLen;
}
result = new String(data, "UTF-8"); // utf-8编码
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static JSONObject doPost(String apiPath,String type,Map<String,Object> paramMap){
OutputStreamWriter out = null;
InputStream is = null;
String result = null;
try{
URL url = new URL(apiPath);// 创建连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod(type) ; // 设置请求方式
connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
connection.connect();
if(type.equals("POST")){
out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
out.append(JSON.toJSONString(paramMap));
out.flush();
out.close();
}
// 读取响应
is = connection.getInputStream();
int length = (int) connection.getContentLength();// 获取长度
if (length != -1) {
byte[] data = new byte[length];
byte[] temp = new byte[512];
int readLen = 0;
int destPos = 0;
while ((readLen = is.read(temp)) > 0) {
System.arraycopy(temp, 0, data, destPos, readLen);
destPos += readLen;
}
result = new String(data, "UTF-8"); // utf-8编码
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return JSONObject.parseObject(result);
}
}
要区分openid是分小程序用户openid,公众号关注以后的用户openid
回调URL这个 ,参考下面,redirect_uri你回调的URL,记住回调URL里面不能出现index.html这种静态的 否则会不能回调生成code
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx63ec015fa8509f66&redirect_uri=https%3a%2f%2fcrm.gxlsss.com%2fapi&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect