控制器部分
- MessboxController.java
package com.Takeaway.controller;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.Takeaway.pojo.Weixinuser;
import com.Takeaway.services.WeixinuserServices;
import com.Takeaway.tools.AesCbuUtil;
import com.Takeaway.tools.HttpRequest;
import com.Takeaway.tools.WxPushServiceQcl;
@SuppressWarnings("deprecation")
@Controller
public class MessboxController {
static String token = "";
@Resource
WeixinuserServices weixinuserServices;
/**
*
* decoding encrypted data to get openid
*
* @param iv
* @param encryptedData
* @param code
* @return
* @throws UnsupportedEncodingException
*
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@RequestMapping(value = "getopenid.html", method = RequestMethod.GET)
@ResponseBody
private Map decodeUserInfo(@Param("weixin_userid") String weixin_userid,
@Param("weixin_rote") String weixin_rote, String iv,
String encryptedData, String code)
throws UnsupportedEncodingException {
Map map = new HashMap();
System.out.println("==============" + encryptedData);
String encryptedData1 = encryptedData.replaceAll(" ", "+");
// login code can not be null
if (code == null || code.length() == 0) {
map.put("status", 0);
map.put("msg", "code 不能为空");
return map;
}
// mini-Program's AppID
String wechatAppId = "wxa88fb8e1435e8a30";
// mini-Program's session-key
String wechatSecretKey = "0eb48af303807fde6f85d42cf02d5b0c";
String grantType = "authorization_code";
// using login code to get sessionId and openId
String params = "appid=" + wechatAppId + "&secret=" + wechatSecretKey
+ "&js_code=" + code + "&grant_type=" + grantType;
// sending request
String sr = HttpRequest.sendGet(
"https://api.weixin.qq.com/sns/jscode2session", params);
// analysis request content
JSONObject json = JSONObject.fromObject(sr);
System.out.println("=================================" + json);
// getting session_key
String sessionKey = json.get("session_key").toString();
// getting open_id
@SuppressWarnings("unused")
String openId = json.get("openid").toString();
// decoding encrypted info with AES
try {
String result = AesCbuUtil.decrypt(encryptedData1, sessionKey, iv,
"UTF-8");
if (null != result && result.length() > 0) {
map.put("status", 1);
map.put("msg", "解密成功");
JSONObject WeixinuserJSON = JSONObject.fromObject(result);
Map WeixinuserInfo = new HashMap();
WeixinuserInfo.put("openId", WeixinuserJSON.get("openId"));
WeixinuserInfo.put("nickName", WeixinuserJSON.get("nickName"));
WeixinuserInfo.put("gender", WeixinuserJSON.get("gender"));
WeixinuserInfo.put("city", WeixinuserJSON.get("city"));
WeixinuserInfo.put("province", WeixinuserJSON.get("province"));
WeixinuserInfo.put("country", WeixinuserJSON.get("country"));
WeixinuserInfo
.put("avatarUrl", WeixinuserJSON.get("avatarUrl"));
WeixinuserInfo.put("unionId", WeixinuserJSON.get("unionId"));
map.put("userInfo", WeixinuserInfo);
if (weixinuserServices
.SelectWeixinuserid((String) WeixinuserJSON
.get("openId")) <= 0) {
if (weixinuserServices.InsertWeixinuser(weixin_userid,
(String) WeixinuserJSON.get("openId"),
(String) WeixinuserJSON.get("nickName"),
weixin_rote) > 0) {
map.put("count", 1);
} else {
map.put("count", 0);
}
}
return map;
}
} catch (Exception e) {
e.printStackTrace();
}
map.put("status", 0);
map.put("msg", "解密失败");
return map;
}
/**
* 查詢
*
* @param rote
* @param response
* @param request
* @return
* @throws Exception
*
*/
@RequestMapping(value = "findlist.html", method = RequestMethod.GET)
@ResponseBody
public JSONArray Objuserid(
@RequestParam(value = "weixin_rote", required = false) String weixin_rote,
HttpServletResponse response, HttpServletRequest request)
throws Exception {
List<Weixinuser> WeixinuserList = null;
WeixinuserList = weixinuserServices.ListWeixinuser(weixin_rote);
JSONArray Weixinuserjson = new JSONArray();
JSONArray JSONWeixinuserArray = JSONArray.fromObject(WeixinuserList);
Weixinuserjson.add(JSONWeixinuserArray);
System.out.println(JSONWeixinuserArray);
return Weixinuserjson;
}
/**
* 修改
*
* @param openid
* @param formid
* @param response
* @param request
* @return
* @throws Exception
*/
@RequestMapping(value = "upfromid.html", method = RequestMethod.GET)
@ResponseBody
public String Upjuserid(
@RequestParam(value = "weixin_openid", required = false) String weixin_openid,
@RequestParam(value = "weixin_fromid", required = false) String weixin_fromid,
HttpServletResponse response, HttpServletRequest request)
throws Exception {
if (weixinuserServices.UpWeixinuserfromid(weixin_openid, weixin_fromid) > 0) {
return "1";
} else {
return "0";
}
}
/**
* 发送模板
*
* @param openid
* @param formid
* @return
* @throws Exception
*/
@RequestMapping(value = "startsending.html", method = RequestMethod.GET)
@ResponseBody
public boolean Fajuserid(
@RequestParam(value = "openid", required = false) String openid,
@RequestParam(value = "formid", required = false) String formid,
@RequestParam(value = "keyword3", required = false) String keyword3,
@RequestParam(value = "keyword4", required = false) String keyword4,
@RequestParam(value = "Template_ids", required = false) String Template_ids,
HttpServletResponse response, HttpServletRequest request)
throws Exception {
SSLSocketFactory.getSocketFactory().setHostnameVerifier(
new AllowAllHostnameVerifier());
WxPushServiceQcl www = new WxPushServiceQcl();
return www.pushOneUser(openid, formid, keyword3, keyword4, Template_ids);
}
}
实体部分
- TemplateData
package com.Takeaway.pojo;
public class TemplateData {
//keyword1:订单类型,keyword2:下单金额,keyword3:配送地址,keyword4:取件地址,keyword5备注
private String value;//,,依次排下去
// private String color;//字段颜色(微信官方已废弃,设置没有效果)
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
- WxMssVo.java
package com.Takeaway.pojo;
import java.util.Map;
public class WxMssVo {
private String touser;//用户openid
private String template_id;//模版id
private String page = "pages/Login/Login";//默认跳到小程序首页
private String form_id;//收集到的用户formid
private Map<String, TemplateData> data;//推送文字
public String getTouser() {
return touser;
}
public void setTouser(String touser) {
this.touser = touser;
}
public String getTemplate_id() {
return template_id;
}
public void setTemplate_id(String template_id) {
this.template_id = template_id;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public String getForm_id() {
return form_id;
}
public void setForm_id(String form_id) {
this.form_id = form_id;
}
public Map<String, TemplateData> getData() {
return data;
}
public void setData(Map<String, TemplateData> data) {
this.data = data;
}
}
- 数据库对应实体Weixinuser.java
package com.Takeaway.pojo;
/**
* 微信用户信息记录
* @author Waitforyou
*
*/
public class Weixinuser {
private int weixin_id;
private int weixin_userid;
private String weixin_openid;
private String weixin_name;
private String weixin_fromid;
private String weixin_rote;
public Weixinuser() {
// TODO Auto-generated constructor stub
}
public int getWeixin_id() {
return weixin_id;
}
public void setWeixin_id(int weixin_id) {
this.weixin_id = weixin_id;
}
public int getWeixin_userid() {
return weixin_userid;
}
public void setWeixin_userid(int weixin_userid) {
this.weixin_userid = weixin_userid;
}
public String getWeixin_openid() {
return weixin_openid;
}
public void setWeixin_openid(String weixin_openid) {
this.weixin_openid = weixin_openid;
}
public String getWeixin_name() {
return weixin_name;
}
public void setWeixin_name(String weixin_name) {
this.weixin_name = weixin_name;
}
public String getWeixin_fromid() {
return weixin_fromid;
}
public void setWeixin_fromid(String weixin_fromid) {
this.weixin_fromid = weixin_fromid;
}
public String getWeixin_rote() {
return weixin_rote;
}
public void setWeixin_rote(String weixin_rote) {
this.weixin_rote = weixin_rote;
}
public Weixinuser(int weixin_id, int weixin_userid, String weixin_openid,
String weixin_name, String weixin_fromid, String weixin_rote) {
super();
this.weixin_id = weixin_id;
this.weixin_userid = weixin_userid;
this.weixin_openid = weixin_openid;
this.weixin_name = weixin_name;
this.weixin_fromid = weixin_fromid;
this.weixin_rote = weixin_rote;
}
}
工具辅助部分
- AesCbuUtil.java
package com.Takeaway.tools;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;
public class AesCbuUtil {
static {
//BouncyCastle是一个开源的加解密解决方案,主页在http://www.bouncycastle.org/
Security.addProvider(new BouncyCastleProvider());
}
/**
* AES解密
*
* @param data //密文,被加密的数据
* @param key //秘钥
* @param iv //偏移量
* @param encodingFormat //解密后的结果需要进行的编码
* @return
* @throws Exception
*/
public static String decrypt(String data, String key, String iv, String encodingFormat) throws Exception {
// initialize();
// String dates =getBase64(data);
// String datese =getFromBase64(dates);
// String num = "F0UkNsu2wPJySLVdD2K/XkUKoGjo3yX5lh/FR58ORa+PVg/gGJ/OW8+CwF8Jk4ONO79MoXArbW1FSnLwzkR/08UWpKuRd/JdiwU2KS4pIcRknEqTq2mSFVNAp6PU6fjYKox7zSwir+TNn2socz/IPyaZ3LPbh7kPExy4MF5g1ON25h3tyKM03/X/YPALNTRaRU1Dzie9DKJ6EcPHAMR8N/gLNMs9aXqvSyIKQ63yhfwuJlrQBVUZJ0/HLL8Wv0dLngxsZAr98B6V0IvkIbZ6eMiK07gvSmtRwWjv7GbCh3eQtnolzZiAPTAAhbOiNvF1K4e+9RTJGJXkps5D1MkNhUgSzmyvCpzuC5hOHvoN/V98ufr8LDl85hOAr71VT5D6fr8l3mpXvleAr9Q1zCzRjvR51Z9C1i7v3RtY1B++prIwjGb2FlkMKf7mPdpWwWEBObdFir+C0MtxF9uOF0QuA4CAoQOM+/9ntUSXbeVazJHO/sfzaSwNgVdr8gu2wUOj";
//被加密的数据
byte[] dataByte = Base64.decodeBase64(data.getBytes());
//加密秘钥
byte[] keyByte = Base64.decodeBase64(key.getBytes());
//偏移量
byte[] ivByte = Base64.decodeBase64(iv.getBytes());
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
//Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
parameters.init(new IvParameterSpec(ivByte));
cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
byte[] resultByte = cipher.doFinal(dataByte);
if (null != resultByte && resultByte.length > 0) {
String result = new String(resultByte, encodingFormat);
return result;
}
return null;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidParameterSpecException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
public static String getBase64(String str) {
byte[] b = null;
String s = null;
try {
b = str.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (b != null) {
s = new BASE64Encoder().encode(b);
}
return s;
}
// 解密
public static String getFromBase64(String s) {
byte[] b = null;
String result = null;
if (s != null) {
BASE64Decoder decoder = new BASE64Decoder();
try {
b = decoder.decodeBuffer(s);
result = new String(b, "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
}
- HttpRequest.java
package com.Takeaway.tools;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
public class HttpRequest {
public static void main(String[] args) {
//发送 GET 请求
String s=HttpRequest.sendGet("http://v.qq.com/x/cover/kvehb7okfxqstmc.html?vid=e01957zem6o", "");
System.out.println(s);
// //发送 POST 请求
// String sr=HttpRequest.sendPost("http://www.toutiao.com/stream/widget/local_weather/data/?city=%E4%B8%8A%E6%B5%B7", "");
// JSONObject json = JSONObject.fromObject(sr);
// System.out.println(json.get("data"));
}
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(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);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
}
- MyX509TrustManager.java
package com.Takeaway.tools;
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 {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
- Sentimentanalysis.java
package com.Takeaway.tools;
import java.util.HashMap;
import com.baidu.aip.nlp.AipNlp;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
* 对评论进行情感分析
*
* @author Waitforyou
*
*/
public class Sentimentanalysis {
public static final String APP_ID = "*****";
public static final String API_KEY = "******";
public static final String SECRET_KEY = "****************";
private static AipNlp instance = null;
public static synchronized AipNlp getInstance() {
if (instance == null) {
instance = new AipNlp(APP_ID, API_KEY, SECRET_KEY);
}
return instance;
}
public static String Startanalysis(String Analysis) {
// 新建一个AipNlp,初始化完成后建议单例使用,避免重复获取access_token:
// AipNlp client = new AipNlp(APP_ID, API_KEY, SECRET_KEY);
AipNlp client = getInstance();
AipNlp client2 = getInstance();
System.out.println("" + client.equals(client2)); // 检验单例使用
// 可选:设置网络连接参数
client.setConnectionTimeoutInMillis(2000);
client.setSocketTimeoutInMillis(60000);
// 可选:设置代理服务器地址, http和socket二选一,或者均不设置
// client.setHttpProxy("proxy_host", proxy_port); // 设置http代理
// client.setSocketProxy("proxy_host", proxy_port); // 设置socket代理
// 可选:设置log4j日志输出格式,若不设置,则使用默认配置
// 也可以直接通过jvm启动参数设置此环境变量
// System.setProperty("aip.log4j.conf",
// "path/to/your/log4j.properties");
// 传入可选参数调用接口
HashMap<String, Object> options = new HashMap<String, Object>();
// 情感倾向分析
org.json.JSONObject res = client.sentimentClassify(Analysis, options);
System.out.println(res.toString(2));
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject)parser.parse(res.toString());
JsonArray array = object.get("items").getAsJsonArray();
JsonObject suJsonObject = array.get(0).getAsJsonObject();
if(Integer.parseInt(suJsonObject.get("sentiment").getAsString())==0){
return "差评";
}else if(Integer.parseInt(suJsonObject.get("sentiment").getAsString())==1){
return "一般";
}else if(Integer.parseInt(suJsonObject.get("sentiment").getAsString())==2){
return "好评";
}else{
return "";
}
}
}
- WxPushServiceQcl.java
package com.Takeaway.tools;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.Takeaway.pojo.TemplateData;
import com.Takeaway.pojo.WxMssVo;
@Service
public class WxPushServiceQcl {
// 用来请求微信的get和post
@Autowired
private RestTemplate restTemplate;
private static String token;
/*
* 微信小程序推送单个用户
*/
public boolean pushOneUser(String openid, String formid,String keyword3, String keyword4,String Template_ids)
throws ClientProtocolException, IOException {
boolean flag=false;
GetUrlS();
// 获取access_token
String access_token = token;
String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send"
+ "?access_token=" + access_token;
System.out.println("==============="+access_token);
// 拼接推送的模版
WxMssVo wxMssVo = new WxMssVo();
wxMssVo.setTouser(openid);// 用户openidTemplate_ids
wxMssVo.setTemplate_id(Template_ids);// 模版id
wxMssVo.setForm_id(formid);// formid
Map<String, TemplateData> m = new HashMap<String, TemplateData>(2);
// keyword1:订单类型,keyword2:下单金额,keyword3:配送地址,keyword4:取件地址,keyword5备注
TemplateData keyword1 = new TemplateData();
keyword1.setValue(keyword3);
m.put("keyword1", keyword1);
TemplateData keyword2 = new TemplateData();
keyword2.setValue(keyword4);
m.put("keyword2", keyword2);
wxMssVo.setData(m);
JSONObject json = JSONObject.fromObject(wxMssVo);
System.out.println("======================"+json);
JSONObject jsonResult=CommonUtil.httpsRequest(url, "POST", String.valueOf(json));
if(jsonResult!=null){
int errorCode=jsonResult.getInt("errcode");
String errorMessage=jsonResult.getString("errmsg");
if(errorCode==0){
flag=true;
}else{
System.out.println("模板消息发送失败:"+errorCode+","+errorMessage);
flag=false;
}
}
return flag;
}
/**
* 获取tocken
* @throws ClientProtocolException
* @throws IOException
*/
public static void GetUrlS() throws ClientProtocolException, IOException {
HttpGet httpGet = new HttpGet(
"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
+ "******" + "&secret="
+ "**********");
HttpClient httpClient = HttpClients.createDefault();
HttpResponse res = httpClient.execute(httpGet);
HttpEntity entity = res.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");
JSONObject jsons = JSONObject.fromObject(result);
String expires_in = jsons.getString("expires_in");
// 缓存
if (Integer.parseInt(expires_in) == 7200) {
// ok
String access_token = jsons.getString("access_token");
System.out.println("access_token:" + access_token);
token = access_token;
} else {
System.out.println("出错获取token失败!");
}
}
}