123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558 |
- package com.ygj.yuemum.service.global;
- import com.alibaba.fastjson.JSON;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import com.ygj.yuemum.component.Constant;
- import com.ygj.yuemum.dao.global.MiniAppInfoDao;
- import com.ygj.yuemum.dao.global.WeChatInfoDao;
- import com.ygj.yuemum.domain.customer.CustomerBooking;
- import com.ygj.yuemum.domain.global.MiniAppInfo;
- import com.ygj.yuemum.domain.global.TemplateData;
- import com.ygj.yuemum.domain.global.WeChatInfo;
- import com.ygj.yuemum.domain.global.WechatTemplate;
- import com.ygj.yuemum.domain.wxmini.WXUser;
- import com.ygj.yuemum.service.wxmini.WXUserService;
- import org.apache.commons.codec.binary.Base64;
- import org.apache.http.HttpStatus;
- import org.apache.http.client.methods.CloseableHttpResponse;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.entity.ContentType;
- 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.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- 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.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.UnsupportedEncodingException;
- import java.net.URL;
- import java.net.URLConnection;
- import java.security.*;
- import java.security.spec.InvalidParameterSpecException;
- import java.text.SimpleDateFormat;
- import java.util.*;
- @Service
- public class WeChatInfoService {
- @Autowired
- private WeChatInfoDao weChatInfoDao;
- @Autowired
- private MiniAppInfoDao miniAppInfoDao;
- @Autowired
- private WXUserService wxUserService;
- public String APPID = Constant.APPID;
- public String APPSECRET = Constant.APPSECRET;
- public String MINIAPPID = Constant.MINIAPPID;
- public String MINIAPPSECRET = Constant.MINIAPPSECRET;
- public String GRANT_TYPE = Constant.GRANT_TYPE;
- public String JSAPI_TICKET_TYPE = Constant.JSAPI_TICKET_TYPE;
- public String ACCESS_TOKEN_URL = Constant.ACCESS_TOKEN_URL;
- public String JSAPI_TICKET_URL = Constant.JSAPI_TICKET_URL;
- public String JSCODE2SESSION = Constant.JSCODE2SESSION;
- public String SENDMESSAGEURL = Constant.SENDMESSAGEURL;
- public String OrderTemplateid = Constant.ORDERTEMPLATEID;
- public String BookingTemplateid = Constant.BOOKINGTEMPLATEID;
- public String ExtractTemplateid = Constant.EXTRACTTEMPLATEID;
- public String WPOPENID = Constant.WPOPENID;
- private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
- String access_Token;
- String expires_in;
- String jsapi_Ticket;
- String noncestr;
- String timeStamp;
- String signaTure;
- String session_key;
- String openid;
- public int WXSendExtractMessage(String wue_applysum, String wue_phone, String wue_bank_card) throws IOException {
- ObjectMapper mapper = new ObjectMapper();
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
- // String resultToken = sendGet("http://yuesuo.yueguanjia.com/modoo-1/getWxPublicSender");
- // Map mapToken = JSON.parseObject(resultToken);
- // String openid = String.valueOf(mapToken.get("wp_openid"));
- Map<String,TemplateData> mapdata = new HashMap<>();
- WechatTemplate wechatTemplate = new WechatTemplate();
- wechatTemplate.setTemplate_id(ExtractTemplateid);
- wechatTemplate.setTouser(WPOPENID);
- // 封装模板数据
- TemplateData first = new TemplateData();
- first.setValue("介绍人发送提现申请!");
- first.setColor("#173177");
- mapdata.put("first", first);
- TemplateData keyword1 = new TemplateData();
- keyword1.setValue(wue_applysum);
- keyword1.setColor("#fc6961");
- mapdata.put("keyword1", keyword1);
- TemplateData keyword2 = new TemplateData();
- keyword2.setValue(sdf.format(new Date()));
- keyword2.setColor("#173177");
- mapdata.put("keyword2", keyword2);
- TemplateData keyword5 = new TemplateData();
- keyword5.setValue("手机号:" +wue_phone+ ",银行卡号:" +wue_bank_card+"。请尽快处理!");
- keyword5.setColor("#173177");
- mapdata.put("remark", keyword5);
- wechatTemplate.setData(mapdata);
- String toString = mapper.writeValueAsString(wechatTemplate);
- String result = "";
- CloseableHttpClient httpClient = HttpClients.createDefault();
- WeChatInfo weChatInfo = weChatInfoDao.getWeChatInfo();
- HttpPost httpPost = new HttpPost(SENDMESSAGEURL+weChatInfo.getAccess_token());
- StringEntity stringEntity = new StringEntity(toString, ContentType.APPLICATION_JSON);
- stringEntity.setContentEncoding("utf-8");
- httpPost.setEntity(stringEntity);
- CloseableHttpResponse response = httpClient.execute(httpPost);
- if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
- result = EntityUtils.toString(response.getEntity(), "utf-8");
- } else {
- return 0;
- }
- return 1;
- }
- public int WXSendOrderMessage(String orderno, String total, String date) throws IOException {
- ObjectMapper mapper = new ObjectMapper();
- // String resultToken = sendGet("http://yuesuo.yueguanjia.com/modoo-1/getWxPublicSender");
- // Map mapToken = JSON.parseObject(resultToken);
- // String openid = String.valueOf(mapToken.get("wp_openid"));
- Map<String,TemplateData> mapdata = new HashMap<>();
- WechatTemplate wechatTemplate = new WechatTemplate();
- wechatTemplate.setTemplate_id(OrderTemplateid);
- wechatTemplate.setTouser(WPOPENID);
- // 封装模板数据
- TemplateData first = new TemplateData();
- first.setValue("用户设备租赁单在线支付成功!");
- first.setColor("#173177");
- mapdata.put("first", first);
- TemplateData keyword1 = new TemplateData();
- keyword1.setValue(orderno);
- keyword1.setColor("#fc6961");
- mapdata.put("keyword1", keyword1);
- TemplateData keyword2 = new TemplateData();
- keyword2.setValue(total);
- keyword2.setColor("#173177");
- mapdata.put("keyword2", keyword2);
- TemplateData keyword3 = new TemplateData();
- keyword3.setValue(date);
- keyword3.setColor("#173177");
- mapdata.put("keyword3", keyword3);
- TemplateData keyword5 = new TemplateData();
- keyword5.setValue("请尽快完善订单及时发货");
- keyword5.setColor("#173177");
- mapdata.put("remark", keyword5);
- wechatTemplate.setData(mapdata);
- String toString = mapper.writeValueAsString(wechatTemplate);
- String result = "";
- CloseableHttpClient httpClient = HttpClients.createDefault();
- WeChatInfo weChatInfo = weChatInfoDao.getWeChatInfo();
- HttpPost httpPost = new HttpPost(SENDMESSAGEURL+weChatInfo.getAccess_token());
- StringEntity stringEntity = new StringEntity(toString, ContentType.APPLICATION_JSON);
- stringEntity.setContentEncoding("utf-8");
- httpPost.setEntity(stringEntity);
- CloseableHttpResponse response = httpClient.execute(httpPost);
- if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
- result = EntityUtils.toString(response.getEntity(), "utf-8");
- } else {
- return 0;
- }
- return 1;
- }
- public int WXSendYSOrderMessage(String orderno, String total, String date,String type) throws IOException {
- ObjectMapper mapper = new ObjectMapper();
- // String resultToken = sendGet("http://yuesuo.yueguanjia.com/modoo-1/getWxPublicSender");
- // Map mapToken = JSON.parseObject(resultToken);
- // String openid = String.valueOf(mapToken.get("wp_openid"));
- Map<String,TemplateData> mapdata = new HashMap<>();
- WechatTemplate wechatTemplate = new WechatTemplate();
- wechatTemplate.setTemplate_id(OrderTemplateid);
- wechatTemplate.setTouser(WPOPENID);
- // 封装模板数据
- TemplateData first = new TemplateData();
- if (type.equals("2")) {
- first.setValue("用户支付订单首付款成功!");
- first.setColor("#173177");
- } else if (type.equals("3")) {
- first.setValue("用户支付订单尾款成功!");
- first.setColor("#173177");
- }
- mapdata.put("first", first);
- TemplateData keyword1 = new TemplateData();
- keyword1.setValue(orderno);
- keyword1.setColor("#fc6961");
- mapdata.put("keyword1", keyword1);
- TemplateData keyword2 = new TemplateData();
- keyword2.setValue(total);
- keyword2.setColor("#173177");
- mapdata.put("keyword2", keyword2);
- TemplateData keyword3 = new TemplateData();
- keyword3.setValue(date);
- keyword3.setColor("#173177");
- mapdata.put("keyword3", keyword3);
- TemplateData keyword5 = new TemplateData();
- keyword5.setValue("请尽快安排顾问跟进!");
- keyword5.setColor("#173177");
- mapdata.put("remark", keyword5);
- wechatTemplate.setData(mapdata);
- String toString = mapper.writeValueAsString(wechatTemplate);
- String result = "";
- CloseableHttpClient httpClient = HttpClients.createDefault();
- WeChatInfo weChatInfo = weChatInfoDao.getWeChatInfo();
- HttpPost httpPost = new HttpPost(SENDMESSAGEURL+weChatInfo.getAccess_token());
- StringEntity stringEntity = new StringEntity(toString, ContentType.APPLICATION_JSON);
- stringEntity.setContentEncoding("utf-8");
- httpPost.setEntity(stringEntity);
- CloseableHttpResponse response = httpClient.execute(httpPost);
- if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
- result = EntityUtils.toString(response.getEntity(), "utf-8");
- } else {
- return 0;
- }
- return 1;
- }
- public int WXSendBookingMessage(CustomerBooking customerBooking) throws IOException {
- ObjectMapper mapper = new ObjectMapper();
- // String resultToken = sendGet("http://yuesuo.yueguanjia.com/modoo-1/getWxPublicSender");
- // Map mapToken = JSON.parseObject(resultToken);
- // String openid = String.valueOf(mapToken.get("wp_openid"));
- WechatTemplate wechatTemplate = new WechatTemplate();
- wechatTemplate.setTemplate_id(BookingTemplateid);
- wechatTemplate.setTouser(WPOPENID);
- Map<String,TemplateData> mapdata = new HashMap<>();
- // 封装模板数据
- TemplateData first = new TemplateData();
- if(customerBooking.getBk_type().equals(4) && customerBooking.getBk_introducer_phone() != null && customerBooking.getBk_introducer_phone() != ""){
- first.setValue("顾问预约信息!介绍人手机:"+customerBooking.getBk_introducer_phone()+",介绍人顾问:"+customerBooking.getBk_introducer_consultant()+"!");
- first.setColor("#173177");
- } else if(customerBooking.getBk_type().equals(1) && customerBooking.getBk_introducer_phone() != null && customerBooking.getBk_introducer_phone() != "") {
- first.setValue("套餐预约信息!介绍人手机:"+customerBooking.getBk_introducer_phone()+",介绍人顾问:"+customerBooking.getBk_introducer_consultant()+"!");
- first.setColor("#173177");
- } else {
- first.setValue("预约信息!");
- first.setColor("#173177");
- }
- mapdata.put("first", first);
- TemplateData keyword2 = new TemplateData();
- keyword2.setValue(customerBooking.getBk_phone());
- keyword2.setColor("#fc6961");
- mapdata.put("keyword2", keyword2);
- TemplateData keyword3 = new TemplateData();
- keyword3.setValue(customerBooking.getBk_date());
- keyword3.setColor("#173177");
- mapdata.put("keyword3", keyword3);
- if(customerBooking.getBk_type().equals(1)){
- TemplateData keyword4 = new TemplateData();
- keyword4.setValue("套餐预约,套餐名称:"+customerBooking.getBk_desc());
- keyword4.setColor("#173177");
- mapdata.put("keyword4", keyword4);
- }
- if(customerBooking.getBk_type().equals(4)){
- TemplateData keyword4 = new TemplateData();
- keyword4.setValue("顾问预约,"+"预产期:"+customerBooking.getBk_duedate());
- keyword4.setColor("#173177");
- mapdata.put("keyword4", keyword4);
- }
- if(customerBooking.getBk_type().equals(5)){
- TemplateData keyword4 = new TemplateData();
- keyword4.setValue("设备返还预约,租赁单编号:"+customerBooking.getBk_desc());
- keyword4.setColor("#173177");
- mapdata.put("keyword4", keyword4);
- }
- TemplateData keyword5 = new TemplateData();
- keyword5.setValue("请尽快安排跟进!");
- keyword5.setColor("#173177");
- mapdata.put("remark", keyword5);
- wechatTemplate.setData(mapdata);
- String toString = mapper.writeValueAsString(wechatTemplate);
- String result = "";
- CloseableHttpClient httpClient = HttpClients.createDefault();
- WeChatInfo weChatInfo = weChatInfoDao.getWeChatInfo();
- HttpPost httpPost = new HttpPost(SENDMESSAGEURL+weChatInfo.getAccess_token());
- StringEntity stringEntity = new StringEntity(toString, ContentType.APPLICATION_JSON);
- stringEntity.setContentEncoding("utf-8");
- httpPost.setEntity(stringEntity);
- CloseableHttpResponse response = httpClient.execute(httpPost);
- if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
- result = EntityUtils.toString(response.getEntity(), "utf-8");
- } else {
- return 0;
- }
- return 1;
- }
- public int SaveWeChatInfo() {
- SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- try {
- //access_token
- String resultToken = sendGet(ACCESS_TOKEN_URL + "?grant_type=" + GRANT_TYPE + "&appid=" + APPID + "&secret=" + APPSECRET);
- Map mapToken = JSON.parseObject(resultToken);
- access_Token = String.valueOf(mapToken.get("access_token"));
- expires_in = String.valueOf(mapToken.get("expires_in"));
- //get jsApi_ticket
- String resultJsapi = sendGet(JSAPI_TICKET_URL + "?access_token=" + access_Token + "&type=" + JSAPI_TICKET_TYPE);
- Map mapJsapi = JSON.parseObject(resultJsapi);
- jsapi_Ticket = String.valueOf(mapJsapi.get("ticket"));
- //保存到数据库中
- WeChatInfo weChatInfo = new WeChatInfo();
- weChatInfo.setAccess_token(access_Token);
- weChatInfo.setJsapi_ticket(jsapi_Ticket);
- weChatInfo.setUpdate_time(dateFormat.format(new Date()));
- weChatInfoDao.updateWeChatInfo(weChatInfo);
- } catch (Exception ex) {
- ex.printStackTrace();
- return 0;
- }
- return 1;
- }
- public int SaveMiniAppInfo() {
- SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- try {
- //access_token
- String resultToken = sendGet(ACCESS_TOKEN_URL + "?grant_type=" + GRANT_TYPE + "&appid=" + MINIAPPID + "&secret=" + MINIAPPSECRET);
- Map mapToken = JSON.parseObject(resultToken);
- access_Token = String.valueOf(mapToken.get("access_token"));
- expires_in = String.valueOf(mapToken.get("expires_in"));
- //保存到数据库中
- MiniAppInfo miniAppInfo = new MiniAppInfo();
- miniAppInfo.setAccess_token(access_Token);
- miniAppInfo.setJsapi_ticket(jsapi_Ticket);
- miniAppInfo.setUpdate_time(dateFormat.format(new Date()));
- miniAppInfoDao.updateMiniAppInfo(miniAppInfo);
- } catch (Exception ex) {
- ex.printStackTrace();
- return 0;
- }
- return 1;
- }
- public Map<String, String> getWXOpenid(String js_code) {
- Map<String, String> result = new HashMap<>();
- String resultToken = sendGet(JSCODE2SESSION + "?grant_type=authorization_code" + "&appid=" + MINIAPPID + "&secret=" + MINIAPPSECRET + "&js_code=" + js_code);
- Map mapToken = JSON.parseObject(resultToken);
- session_key = String.valueOf(mapToken.get("session_key"));
- openid = String.valueOf(mapToken.get("openid"));
- //save database
- //检查用户是否已经注册,注册返回手机号等信息,没注册返回openid作为用户名
- //新用户 insert ,没有手机返回openid 有手机返回手机号等信息
- WXUser ckeckwxUser = wxUserService.getWXUser(openid);
- if(ckeckwxUser != null) {
- result.put("openid", openid);
- result.put("type","2");
- result.put("nickName",ckeckwxUser.getXu_name());
- result.put("phone",ckeckwxUser.getXu_phone());
- } else {
- WXUser wxUser = new WXUser();
- wxUser.setXu_openid(openid);
- wxUser.setXu_sessionkey(session_key);
- UUID id=UUID.randomUUID();
- String[] idd=id.toString().split("-");
- String lsid = "YSLS"+idd[1];
- wxUser.setXu_name(lsid);
- wxUserService.insertWXUser(wxUser);
- result.put("openid", openid);
- result.put("type","1");
- result.put("nickName",lsid);
- }
- result.put("session_key", session_key);
- return result;
- }
- public Map<String, String> getWeChatInfo(String url) {
- WeChatInfo weChatInfo = weChatInfoDao.getWeChatInfo();
- Map<String, String> result = new HashMap<>();
- String timestamp = getTimestamp();
- String noncestr = getNoncestr();
- String signature = SHA1(jointString(weChatInfo.getJsapi_ticket(), noncestr, timestamp, url));
- result.put("timestamp", timestamp);
- result.put("nonceStr", noncestr);
- result.put("signature", signature);
- result.put("appid", APPID);
- result.put("jsapi_ticket", weChatInfo.getJsapi_ticket());
- return result;
- }
- //-----------------------------------
- public static String jointString(String jsapi_Ticket, String noncestr, String timestamp, String url) {
- String sb = new String();
- sb += "jsapi_ticket=" + jsapi_Ticket + "&";
- sb += "noncestr=" + noncestr + "&";
- sb += "timestamp=" + timestamp + "&";
- sb += "url=" + url;
- return sb;
- }
- public static String SHA1(String str) {
- try {
- MessageDigest digest = java.security.MessageDigest
- .getInstance("SHA-1"); //如果是SHA加密只需要将"SHA-1"改成"SHA"即可
- digest.update(str.getBytes());
- byte messageDigest[] = digest.digest();
- // Create Hex String
- StringBuffer hexStr = new StringBuffer();
- // 字节数组转换为 十六进制 数
- for (int i = 0; i < messageDigest.length; i++) {
- String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
- if (shaHex.length() < 2) {
- hexStr.append(0);
- }
- hexStr.append(shaHex);
- }
- return hexStr.toString();
- } catch (NoSuchAlgorithmException e) {
- e.printStackTrace();
- }
- return null;
- }
- public static String getTimestamp() {
- return Long.toString(System.currentTimeMillis() / 1000);
- }
- public static String getNoncestr() {
- return UUID.randomUUID().toString();
- }
- public static String sendGet(String url) {
- String result = "";
- StringBuilder jsonStr = new StringBuilder();
- BufferedReader in = null;
- try {
- String urlNameString = url;
- 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();
- //ConstantUtil.UTF_CODE 编码格式
- InputStreamReader reader = new InputStreamReader(connection.getInputStream());
- char[] buff = new char[1024];
- int length = 0;
- while ((length = reader.read(buff)) != -1) {
- result = new String(buff, 0, length);
- jsonStr.append(result);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- // 使用finally块来关闭输入流
- finally {
- try {
- if (in != null) {
- in.close();
- }
- } catch (Exception e2) {
- e2.printStackTrace();
- }
- }
- return jsonStr.toString();
- }
- public String getWxDecrypt(String encrypdata,String ivdata, String openid) {
- WXUser wxUser = wxUserService.getWXUser(openid);
- String str="";
- try {
- str = decrypt(encrypdata,wxUser.getXu_sessionkey(),ivdata,"UTF-8");
- } catch (Exception e) {
- e.printStackTrace();
- }
- return str;
- }
- public static String decrypt(String data, String key, String iv, String encodingFormat) throws Exception {
- // initialize();
- //被加密的数据
- byte[] dataByte = Base64.decodeBase64(data);
- //加密秘钥
- byte[] keyByte = Base64.decodeBase64(key);
- //偏移量
- byte[] ivByte = Base64.decodeBase64(iv);
- try {
- Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
- Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
- 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;
- }
- }
|