Commit 711c202a by liangkaiping

copy

parent a2461ecf
<?xml version="1.0"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.yizhi</groupId>
<artifactId>cloud-wechat</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>com.yizhi</groupId>
<artifactId>cloud-wechat-api</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.yizhi</groupId>
<artifactId>cloud-orm</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.yizhi</groupId>
<artifactId>cloud-core</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.yizhi</groupId>
<artifactId>cloud-common-api</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.9</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
package com.yizhi.wechat.application.feign;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* @ClassName AccessTokenController
* @Description TODO
* @Author shengchenglong
* @DATE 2020/11/25 22:42
* @Version 1.0
*/
@FeignClient(name = "wechat", contextId = "AccessTokenClient")
public interface AccessTokenClient {
@GetMapping("weixin/accessToken/get")
String getAccessToken(@RequestParam("appId") String appId);
}
package com.yizhi.wechat.application.feign;
import com.yizhi.wechat.application.vo.wechat.MiniProgramVo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* 小程序获取信息
* @author lingye
* @date 2020年1月3日
*/
@FeignClient(name = "wechat", contextId = "MiniProgramClient")
public interface MiniProgramClient {
/**
* 获取小程序
* @param appId
* @param code
* @return
*/
@GetMapping(value = "/miniProgram/get")
MiniProgramVo getMiniProgram(
@RequestParam(name = "appId",required = true) String appId,
@RequestParam(name = "code",required = true) String code,
@RequestParam(name = "headImg", required = false) String headImg
);
}
package com.yizhi.wechat.application.feign;
import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.wechat.application.vo.wechat.domain.PublicPlatformConfigVo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
/**
* 配置信息feign接口
*
* @author lly
* @date 2018-12-5
*/
@FeignClient(name = "wechat", contextId = "PublicConfigClient")
public interface PublicConfigClient {
/**
* 添加服务号的配置信息
*
* @param publicPlatformConfig
* @return
*/
@PostMapping(value = "/publicPlatformConfig/insert")
PublicPlatformConfigVo insertPublicPlatformConfigInfo(@RequestBody PublicPlatformConfigVo publicPlatformConfig);
/**
* 查询
*
* @param id
* @return
*/
@GetMapping(value = "/publicPlatformConfig/get")
PublicPlatformConfigVo getPublicPlatformConfigInfo(@RequestParam(value = "id") Long id);
/**
* 修改
*
* @param publicPlatformConfig
* @return
*/
@PostMapping(value = "/publicPlatformConfig/update")
PublicPlatformConfigVo updatePublicPlatformConfigInfo(@RequestBody PublicPlatformConfigVo publicPlatformConfig);
/**
* 查询列表
*
* @param pageSize
* @param pageNo
* @param name
* @return
*/
@GetMapping(value = "/publicPlatformConfig/list")
Page<PublicPlatformConfigVo> getPublicPlatformConfigs(@RequestParam(value = "pageNo", required = true, defaultValue = "1") Integer pageNo,
@RequestParam(value = "pageSize", required = true, defaultValue = "10") Integer pageSize,
@RequestParam(value = "name") String name);
/**
* 删除配置信息
*
* @param ids
* @return
*/
@GetMapping(value = "/publicPlatformConfig/delete")
boolean deletePublicPlatformConfig(@RequestBody List<Long> ids);
/**
* 获取配置信息
*
* @param publicPlatformConfig
* @return
*/
@PostMapping(value = "/publicPlatformConfig/getInfo")
PublicPlatformConfigVo findPublicPlatformConfig(@RequestBody PublicPlatformConfigVo publicPlatformConfig);
}
package com.yizhi.wechat.application.feign;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* @Date 2020/11/26 10:56 上午
* @Author lvjianhui
**/
@FeignClient(name = "wechat", contextId = "WeChatTokenClient",path = "/wechat")
public interface WeChatTokenClient {
@GetMapping("/appid/accesstoken/get")
public String getWechatAccessTokenByAppId(@RequestParam("appId") String appId,
@RequestParam(value = "agentId",required = false) String agentId);
}
package com.yizhi.wechat.application.feign;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Map;
/**
* 微信
*
* @author lingye
*/
@FeignClient(name = "wechat", contextId = "WeChatUserClient")
public interface WeChatUserClient {
/**
* 获取token
*
* @param weChatUserId
* @param appId
* @param agentId
* @return
*/
@GetMapping(value = "/wechat/token")
Map<String, Object> getWeChatUserInfoToken(@RequestParam(name = "weChatUserId", required = true) String weChatUserId,
@RequestParam(name = "appId", required = true) String appId,
@RequestParam(name = "agentId", required = false) String agentId
);
/**
* 自定义项目获取用户
* @param weChatUserId 用户openId
* @param appId appid
* @param agentId
* @param orgId 组织id
* @return
*/
@GetMapping(value = "/custom/project/token")
Map<String, Object> getToken(@RequestParam(name = "weChatUserId", required = true) String weChatUserId,
@RequestParam(name = "appId", required = true) String appId,
@RequestParam(name = "agentId", required = false) String agentId,
@RequestParam(name = "orgId", required = true) Long orgId
);
}
package com.yizhi.wechat.application.feign;
import com.yizhi.wechat.application.vo.wechat.SuiteTicketVO;
import com.yizhi.wechat.application.vo.wechat.WechatProviderVO;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
@FeignClient(name = "wechat", contextId = "WechatProviderClient")
public interface WechatProviderClient {
/**
* @param signature
* @param timestamp
* @param nonce
* @param echostr
* @return
*/
@ResponseBody
@GetMapping(value = "/provider/get")
String checkToken(@RequestParam(name = "msg_signature") String signature,
@RequestParam(name = "timestamp") String timestamp,
@RequestParam(name = "nonce") String nonce,
@RequestParam(name = "echostr") String echostr
);
/**
*
* @param wechatProviderVO
* @return
*/
@PostMapping(value = "/provider/handle")
Object handlerMessage(@RequestBody WechatProviderVO wechatProviderVO);
@RequestMapping(value = "/provider/callback", method = RequestMethod.GET)
String callBack(@RequestParam(name = "msg_signature") String signature,
@RequestParam(name = "timestamp") String timestamp,
@RequestParam(name = "nonce") String nonce,
@RequestParam(name = "echostr") String echostr
);
/**
* 获取微信服务商的 suite_ticket
* @param suiteTicketVO
* @return
*/
@PostMapping(value = "/provider/suite/receive", produces = {"application/xml;charset=UTF-8"})
String suiteReceive(@RequestBody SuiteTicketVO suiteTicketVO);
}
\ No newline at end of file
package com.yizhi.wechat.application.feign;
import com.yizhi.wechat.application.vo.wechat.domain.PublicPlatformConfigVo;
import com.yizhi.wechat.application.vo.wechat.domain.TrAccountUserinfoVo;
import com.yizhi.wechat.application.vo.wechat.domain.UserInfoVo;
import com.yizhi.wechat.application.vo.wechat.*;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@FeignClient(name = "wechat", contextId = "WeiXinClient")
public interface WeiXinClient {
/**
* 查询用户与微信公众号绑定的状态
*
* @param wechatUserId 用户微信id
* @return 关联关系实体
*/
@ResponseBody
@GetMapping(value = "/wechat/get/user")
TrAccountUserinfoVo queryUserInWechat(
@RequestParam(name = "wechatUserId") String wechatUserId
, @RequestParam(name = "companyId") Long companyId
);
/**
* 获取微信公众服务号用户的信息
*
* @param appid APPID
* @param code CODE
*/
@RequestMapping(value = "/wechat/get/wechatuser", method = RequestMethod.GET)
public WechatUserInfoVO getUserInfo(@RequestParam(value = "code") String code,
@RequestParam(value = "appid") String appid,
@RequestParam(value = "agentId", required = false) String agentId,
@RequestParam(value = "source", required = false) Integer source
);
/**
* 保存微信id和系统用户id的关系
*
* @param wechatUserId 用户的微信di
* @param accountId 系统账号的id
* @return TrAccountInfo
*/
@RequestMapping(value = "/trAccountUserinfo/save/accountinfo", method = RequestMethod.GET)
public TrAccountUserinfoVO saveTrAccountUserinfo(@RequestParam(value = "wechatUserId", required = true) String wechatUserId,
@RequestParam(value = "accountId", required = true) Long accountId,
@RequestParam(value = "siteId", required = true) Long siteId,
@RequestParam(value = "companyId", required = true) Long companyId,
@RequestParam(value = "terminalType", required = false) Integer terminalType);
/**
* 获取用户的签名
*
* @param agentId 机构Id
* @param url
* @return
*/
@RequestMapping(value = "/wechat/get/signature", method = RequestMethod.GET)
public SignatureVO getSignature(
@RequestParam(name = "appid") String appid,
@RequestParam(name = "url") String url,
@RequestParam(name = "agentId") String agentId);
/**
* 获取授权token
*
* @param publicPlatformConfig 参数实体
* @return
*/
@GetMapping(value = "/wechat/get/token")
public String getChatAccessToken(PublicPlatformConfigVo publicPlatformConfig);
/**
* 获取公众号的配置信息
*
* @param appid
* @return
*/
@RequestMapping(value = "/wechat/get/platformconfig", method = RequestMethod.GET)
public PublicPlatformConfigVo getPlatformconfig(@RequestParam(value = "appid") String appid,
@RequestParam(value = "agentId") String agentId);
/**
* 保存token到redis
*/
@PostMapping(value = "/wechat/save/token")
public void saveAccessTokenToRedis();
/**
* 删除
*
* @param ids 用户id列表
* @return
*/
@PostMapping(value = "/trAccountUserinfo/del/relations")
public ResponseVO delRelation(@RequestBody List<Long> ids);
/**
* 新增平台配置信息
*
* @param publicPlatformConfigVO
* @return
*/
@PostMapping(value = "/publicPlatformConfig/insert")
public boolean insertPublicPlatformConfigInfo(@RequestBody PublicPlatformConfigVO publicPlatformConfigVO);
/**
* 通过用户的id获取微信openId
*
* @param accountId
* @return
*/
@GetMapping(value = "/trAccountUserinfo/get/wechatid")
public String getWechatIdbyAccountId(@RequestParam(name = "accountId") Long accountId);
/**
* TODO 8月底撤掉
*
* @return
*/
@PostMapping(value = "/wechat/update/user")
boolean updateUserInWechat(@RequestBody TrAccountUserinfoVo trAccountUserinfo
);
/**
* job 定期执行任务把
* jsapiticket 放到redis中
*
* @date 2018-8-20 20:47:53
*/
@PostMapping(value = "/wechat/save/jsapiticket")
public void saveJsApiTicket();
/**
* 获取组织列表和用户信息
*
* @param accessToken
* @param wechatUserId
* @return
*/
@GetMapping(value = "/wechat/get/getWechatUser")
public WeChatUserVO getWechatUser(@RequestParam(name = "accessToken") String accessToken,
@RequestParam(name = "wechatUserId") String wechatUserId);
/**
* 获取用户的关联关系
*
* @return
*/
@PostMapping(value = "/trAccountUserinfo/relation/get")
TrAccountUserinfoVo getAccountUserInfo(@RequestBody TrAccountUserinfoVo trAccountUserinfo);
/**
* 保存关联关系
*
* @param userInfoVO
* @return
*/
@PostMapping(value = "/trAccountUserinfo/save")
TrAccountUserinfoVO saveWechatUserInfo(@RequestBody TrAccountUserinfoVO userInfoVO);
/**
* 用户停用
*
* @param userInfo
* @return
*/
@PostMapping(value = "/trAccountUserinfo/stop")
Boolean updateTrAccountUserInfo(@RequestBody TrAccountUserinfoVo userInfo);
@PostMapping(value = "/trAccountUserinfo/unbind/weChatUserId")
Boolean unbindAccountByWeChatUserId(@RequestParam(name = "weChatUserId", required = true) String weChatUserId);
/**
* 批量解绑用户 by weChatUserId
*
* @param code
* @param appId
* @param agentId
* @return
*/
@PostMapping(value = "/trAccountUserinfo/unbind/batch/weChatUserId")
Boolean unbindAccount(
@RequestParam(value = "code") String code,
@RequestParam(value = "appId") String appId,
@RequestParam(value = "agentId", required = false) String agentId);
/**
* 批量解绑用户
* @param accountIds 用户id
* @return··
*/
@PostMapping(value = "/trAccountUserinfo/unbindUser")
Boolean unbindUser(@RequestBody List<Long> accountIds);
@PostMapping(value = "/trAccountUserinfo/get/bind/relation")
Map<Long,TrAccountUserinfoVo> getUserRelations(@RequestBody List<Long> accountIds);
/**
* 获取绑定关系
* @param authorizeUsersVO
* @return
*/
@PostMapping(value = "/trAccountUserinfo/get/bind/relation")
Map<Long,TrAccountUserinfoVo> getUserRelations(@RequestBody AuthorizeUsersVO authorizeUsersVO);
/**
* 获取微信用户的信息
* @param wechatIds
* @return
*/
@PostMapping("wechat/get/userInfo/wechatIds")
Map<String, UserInfoVo> getWeChatUserInfoList(@RequestBody List<String> wechatIds);
}
\ No newline at end of file
package com.yizhi.wechat.application.utils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
public class ElementUtils {
private Element root = null;
/**
* 根据xml格式的字符串建document
* @param sMsg
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
*/
public ElementUtils(String sMsg) throws ParserConfigurationException, IOException, SAXException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
StringReader sr = new StringReader(sMsg);
InputSource is = new InputSource(sr);
Document document = db.parse(is);
root = document.getDocumentElement();
}
/**
* 根据tagName获取内容
* @param tagName
* @return
*/
public String get(String tagName){
return root.getElementsByTagName(tagName).item(0).getTextContent();
}
}
\ No newline at end of file
package com.yizhi.wechat.application.utils;
public class FormatUtils {
/**
* 接收请求格式封装
* @param msg
* @return
*/
public static String getReqData(InMsgEntity msg){
return "<xml><ToUserName><![CDATA["+msg.getToUserName()+"]]></ToUserName><Encrypt><![CDATA[" +msg.getEncrypt()+
"]]></Encrypt><AgentID><![CDATA["+msg.getAgentID()+"]]></AgentID></xml>";
}
/**
* 发送文字消息格式封装
* @param content
* @return
*/
public static String getTextRespData(String content){
return "<xml><MsgType><![CDATA[text]]></MsgType><Content><![CDATA["+content+"]]></Content></xml>";
}
}
\ No newline at end of file
package com.yizhi.wechat.application.utils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author admmin
* @web
* @Description: 文件下载 POST GET
*/
public class HttpClientUtils {
/**
* 最大线程池
*/
public static final int THREAD_POOL_SIZE = 5;
public interface HttpClientDownLoadProgress {
public void onProgress(int progress);
}
public static HttpClientUtils httpClientDownload;
public ExecutorService downloadExcutorService;
public HttpClientUtils() {
downloadExcutorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
}
public static HttpClientUtils getInstance() {
if (httpClientDownload == null) {
httpClientDownload = new HttpClientUtils();
}
return httpClientDownload;
}
/**
* 下载文件
*
* @param url
* @param filePath
*/
public void download(final String url, final String filePath) {
downloadExcutorService.execute(new Runnable() {
@Override
public void run() {
httpDownloadFile(url, filePath, null, null);
}
});
}
/**
* 下载文件
*
* @param url
* @param filePath
* @param progress 进度回调
*/
public void download(final String url, final String filePath,
final HttpClientDownLoadProgress progress) {
downloadExcutorService.execute(new Runnable() {
@Override
public void run() {
httpDownloadFile(url, filePath, progress, null);
}
});
}
/**
* 下载文件
*
* @param url
* @param filePath
*/
public void httpDownloadFile(String url, String filePath,
HttpClientDownLoadProgress progress, Map<String, String> headMap) {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpGet = new HttpGet(url);
setGetHead(httpGet, headMap);
CloseableHttpResponse response1 = httpclient.execute(httpGet);
try {
System.out.println(response1.getStatusLine());
HttpEntity httpEntity = response1.getEntity();
long contentLength = httpEntity.getContentLength();
InputStream is = httpEntity.getContent();
// 根据InputStream 下载文件
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int r = 0;
long totalRead = 0;
while ((r = is.read(buffer)) > 0) {
output.write(buffer, 0, r);
totalRead += r;
if (progress != null) {// 回调进度
progress.onProgress((int) (totalRead * 100 / contentLength));
}
}
FileOutputStream fos = new FileOutputStream(filePath);
output.writeTo(fos);
output.flush();
output.close();
fos.close();
EntityUtils.consume(httpEntity);
} finally {
response1.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* get请求
*
* @param url
* @return
*/
public String httpGet(String url) {
return httpGet(url, null);
}
/**
* http get请求
*
* @param url
* @return
*/
public String httpGet(String url, Map<String, String> headMap) {
String responseContent = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response1 = httpclient.execute(httpGet);
setGetHead(httpGet, headMap);
try {
System.out.println(response1.getStatusLine());
HttpEntity entity = response1.getEntity();
responseContent = getRespString(entity);
System.out.println("debug:" + responseContent);
EntityUtils.consume(entity);
} finally {
response1.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
public String httpPost(String url, Map<String, String> paramsMap) {
return httpPost(url, paramsMap, null);
}
/**
* http的post请求
*
* @param url
* @param paramsMap
* @return
*/
public String httpPost(String url, Map<String, String> paramsMap,
Map<String, String> headMap) {
String responseContent = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(url);
setPostHead(httpPost, headMap);
setPostParams(httpPost, paramsMap);
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
responseContent = getRespString(entity);
EntityUtils.consume(entity);
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("responseContent = " + responseContent);
return responseContent;
}
/**
* 设置POST的参数
*
* @param httpPost
* @param paramsMap
* @throws Exception
*/
public void setPostParams(HttpPost httpPost, Map<String, String> paramsMap)
throws Exception {
if (paramsMap != null && paramsMap.size() > 0) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<String> keySet = paramsMap.keySet();
for (String key : keySet) {
nvps.add(new BasicNameValuePair(key, paramsMap.get(key)));
}
// httpPost.setEntity(new UrlEncodedFormEntity(nvps));
httpPost.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));
}
}
/**
* 设置http的HEAD
*
* @param httpPost
* @param headMap
*/
public void setPostHead(HttpPost httpPost, Map<String, String> headMap) {
if (headMap != null && headMap.size() > 0) {
Set<String> keySet = headMap.keySet();
for (String key : keySet) {
httpPost.addHeader(key, headMap.get(key));
}
}
}
/**
* 设置http的HEAD
*
* @param httpGet
* @param headMap
*/
public void setGetHead(HttpGet httpGet, Map<String, String> headMap) {
if (headMap != null && headMap.size() > 0) {
Set<String> keySet = headMap.keySet();
for (String key : keySet) {
httpGet.addHeader(key, headMap.get(key));
}
}
}
/**
* 上传文件
*
* @param serverUrl
* 服务器地址
* @param localFilePath
* 本地文件路径
* @param serverFieldName
* @param params
* @return
* @throws Exception
*/
/**
* 将返回结果转化为String
*
* @param entity
* @return
* @throws Exception
*/
public String getRespString(HttpEntity entity) throws Exception {
if (entity == null) {
return null;
}
InputStream is = entity.getContent();
StringBuffer strBuf = new StringBuffer();
byte[] buffer = new byte[4096];
int r = 0;
while ((r = is.read(buffer)) > 0) {
strBuf.append(new String(buffer, 0, r, "UTF-8"));
}
return strBuf.toString();
}
public static String sendGet(String url, String accessToken) {
String result = "";
BufferedReader in = null;// 读取响应输入流
StringBuffer sb = new StringBuffer();// 存储参数
String params = "";// 编码之后的参数
try {
// 编码请求参数
// if (parameters.size() == 1) {
// for (String name : parameters.keySet()) {
// sb.append(name).append("=").append(java.net.URLEncoder.encode(parameters.get(name), "UTF-8"));
// }
// params = sb.toString();
// } else {
// for (String name : parameters.keySet()) {
// sb.append(name).append("=").append(java.net.URLEncoder.encode(parameters.get(name), "UTF-8")).append("&");
// }
// String temp_params = sb.toString();
// params = temp_params.substring(0, temp_params.length() - 1);
// }
String full_url = url ;
System.out.println(full_url);
// 创建URL对象
java.net.URL connURL = new java.net.URL(full_url);
// 打开URL连接(建立了一个与服务器的tcp连接,并没有实际发送http请求!)
URLConnection urlConnection = connURL.openConnection();
java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) urlConnection;
// 设置通用请求属性(如果已存在具有该关键字的属性,则用新值改写其值。)
httpConn.setRequestProperty("Accept", "*/*");
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
httpConn.setRequestProperty("authorization", accessToken);
// 建立实际的连接(远程对象变为可用。远程对象的头字段和内容变为可访问)
httpConn.connect();
// 响应头部获取
Map<String, List<String>> headers = httpConn.getHeaderFields();
// 遍历所有的响应头字段
for (String key : headers.keySet()) {
System.out.println(key + "\t:\t" + headers.get(key));
}
// 定义BufferedReader输入流来读取URL的响应,并设置编码方式
in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
String line;
// 读取返回的内容
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}
package com.yizhi.wechat.application.utils;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="xml")
@XmlAccessorType(XmlAccessType.FIELD)
public class InMsgEntity {
/**
* 接收的应用id,可在应用的设置页面获取
*/
@XmlElement(name = "AgentID")
private String agentID;
/**
* 经过加密的密文
*/
@XmlElement(name = "Encrypt")
private String encrypt;
/**
* 发送方帐号
*/
@XmlElement(name="ToUserName")
private String toUserName;
public String getAgentID() {
return agentID;
}
public void setAgentID(String agentID) {
this.agentID = agentID;
}
public String getEncrypt() {
return encrypt;
}
public void setEncrypt(String encrypt) {
this.encrypt = encrypt;
}
public String getToUserName() {
return toUserName;
}
public void setToUserName(String toUserName) {
this.toUserName = toUserName;
}
}
\ No newline at end of file
package com.yizhi.wechat.application.utils;
import okhttp3.*;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
/**
* Create BY poplar ON 2020/3/28
*/
public class OkHttpUtils {
public static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");
private static final MediaType contentType = MediaType.parse("application/json;charset=utf-8");
public static String doRequest1(String url, Map<String, String> head, Map<String, Object> params, String requestMethod) {
OkHttpClient client = new OkHttpClient();
FormBody.Builder build = new FormBody.Builder();
Iterator<Map.Entry<String, Object>> iterator = params.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> entry = iterator.next();
build.add(entry.getKey(), entry.getValue().toString());
}
RequestBody requestBody = build.build();
head = checkHead(head);
Request request = null;
if (requestMethod.equalsIgnoreCase("GET")) {
request = new okhttp3.Request.Builder().url(url).headers(Headers.of(head)).get().build();
} else {
request = new okhttp3.Request.Builder().url(url).headers(Headers.of(head)).post(requestBody).build();
}
String str = "";
try {
Response response = client.newCall(request).execute();
str = response.body().string();
} catch (IOException e) {
e.printStackTrace();
return "错误";
}
return str;
}
public static String doRequest2(String url, @NotNull Map<String, String> head, String json) {
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = RequestBody.create(contentType, json);
head = checkHead(head);
Request request = new okhttp3.Request.Builder().url(url).headers(Headers.of(head)).post(requestBody).build();
try {
Response response = client.newCall(request).execute();
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
return "错误";
}
}
//这么做只是未来避免NPE异常
private static Map<String, String> checkHead(Map<String, String> head) {
if (Objects.isNull(head)) {
HashMap<String, String> map = new HashMap<>(1);
map.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4093.3 Safari/537.36");
head = map;
}
return head;
}
public static String httpGet(String url) {
OkHttpClient httpClient = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
try {
Response response = httpClient.newCall(request).execute();
// 返回的是string 类型,json的mapper可以直接处理
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static String httpPost(String url, String json, String authorization) throws IOException {
OkHttpClient httpClient = new OkHttpClient();
RequestBody requestBody = RequestBody.create(JSON, json);
Request request = new Request.Builder().url(url).addHeader("Authorization", "Basic " + authorization).post(requestBody).build();
Response response = httpClient.newCall(request).execute();
return response.body().string();
}
}
\ No newline at end of file
package com.yizhi.wechat.application.vo.wechat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
import java.util.List;
/**
* <p>
* 用户
* </p>
*
* @author moniyin
* @since 2018-03-12
*/
@Data
@ApiModel(value = "AccountVO", description = "用户对象传输类")
public class AccountVO {
@ApiModelProperty(value = "id")
private Long id;
@ApiModelProperty(value = "账号名称")
private String name;
@ApiModelProperty(value = "头像")
private String headPortrait;
@ApiModelProperty(value = "是否开通")
private Boolean enabled;
@ApiModelProperty(value = "是否锁定")
private Boolean locked;
@ApiModelProperty(value = "座机")
private String telephone;
@ApiModelProperty(value = "手机号")
private String mobile;
@ApiModelProperty(value = "邮箱地址")
private String email;
@ApiModelProperty(value = "过期类型(1长期,2周期,对应字段:startTime,endTime,3天数,对应字段:expiredTime)")
private Integer expiredType;
@ApiModelProperty(value = "是否是第一次登录")
private Boolean firstLogin;
@ApiModelProperty(value = "第一次登录时间")
private Date firstLoginTime;
@ApiModelProperty(value = "上一次登录时间")
private Date lastLoginTime;
@ApiModelProperty(value = "账户锁定时间")
private Date lockedTime;
@ApiModelProperty(value = "账号生效时间")
private Date enabledTime;
@ApiModelProperty(value = "账户过期时间")
private Date expiredTime;
@ApiModelProperty(value = "盐")
private String salt;
@ApiModelProperty(value = "开始时间")
private Date startTime;
@ApiModelProperty(value = "结束时间")
private Date endTime;
@ApiModelProperty(value = "性别(‘M’:男,'F':女)")
private String sex;
@ApiModelProperty(value = "职位")
private String position;
@ApiModelProperty(value = "微信")
private String wechat;
@ApiModelProperty(value = "微信图片")
private String wechatPic;
@ApiModelProperty(value = "有效天数")
private Integer validDays;
@ApiModelProperty(value = "全名")
private String fullName;
@ApiModelProperty(value = "工号")
private String workNum;
@ApiModelProperty(value = "账号描述")
private String description;
@ApiModelProperty(value = "部门id")
private Long orgId;
@ApiModelProperty(value = "部门名称")
private String orgName;
@ApiModelProperty(value = "部门全名称")
private String orgFullName;
@ApiModelProperty(value = "公司id")
private Long companyId;
@ApiModelProperty(value = "公司名称")
private String companyName;
@ApiModelProperty(value = "企业地址")
private String companyAddress;
@ApiModelProperty(value = "app注册id")
private String appRegistrationId;
@ApiModelProperty(value = "备注1")
private String remarkFirst;
@ApiModelProperty(value = "备注2")
private String remarkSecond;
@ApiModelProperty(value = "备注3")
private String remarkThird;
@ApiModelProperty(value = "是否绑定微信,true 绑定,false 未绑定")
private Boolean bindWeChat;
}
package com.yizhi.wechat.application.vo.wechat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;
/**
* @Author: XieHaijun
* @Description:
* @Date: Created in 18:59 2018/5/7
* @Modified By
*/
@Data
@ApiModel(value = "AuthorizeUsersVO", description = "授权用户")
public class AuthorizeUsersVO {
@ApiModelProperty(value = "角色ID")
private long roleId;
@ApiModelProperty(value = "授权用户id列表")
private List<Long> userIds;
}
package com.yizhi.wechat.application.vo.wechat;
/**
* 常量类
* @author lilingye
* @since 2018-9-25 11:43:16
*/
public final class Constants {
/**
* 刪除標記
*/
public static final int DEL_FLAG = 0;
public static final String ZERO = "0";
public static final String ONE = "1";
public static final String TWO = "2";
public static final String nullStr = "null";
public static final int YES_FLAG = 1;
public static final int NO_FLAG = 0;
public static final int THREE = 3;
public static final int FIVE = 5;
/**
* access_token
*/
public static final String ACCESS_TOKEN = "access_token";
public static final int REDIS_INVALID_TIME = 3600;
}
package com.yizhi.wechat.application.vo.wechat;
import lombok.Data;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@Data
@XmlRootElement(name="xml")
@XmlAccessorType(XmlAccessType.FIELD)
public class InstructVO {
/**
* 接收的应用id,可在应用的设置页面获取
*/
@XmlElement(name = "SuiteId")
private String suiteId;
/**
* 经过加密的密文
*/
@XmlElement(name = "InfoType")
private String infoType;
/**
* 发送方帐号
*/
@XmlElement(name = "TimeStamp")
private String timestamp;
@XmlElement(name = "SuiteTicket")
private String suitetTcket;
}
\ No newline at end of file
package com.yizhi.wechat.application.vo.wechat;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 接口返回vo
*
* @author lingye
* @date 2020年1月3日
*/
@Data
public class MiniProgramVo {
@ApiModelProperty(value = "小程序用户的openId")
private String openId;
@ApiModelProperty(value = "小程序用户的unionId")
private String unionId;
@ApiModelProperty(value = "用户id")
private Long accountId;
@ApiModelProperty(value = "是否跳转到")
private Boolean ret;
@ApiModelProperty(value = "返回code")
private String code;
@ApiModelProperty(value = "返回msg")
private String msg;
}
package com.yizhi.wechat.application.vo.wechat;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.FieldFill;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
*
* </p>
*
* @author lilingye
* @since 2018-7-30
*/
@Data
@Api(tags = "PublicPlatformConfig", description = "")
public class PublicPlatformConfigVO {
@ApiModelProperty(value = "公众号名称")
private String name;
@ApiModelProperty(value = "公众号类型 0:企业服务号,1微信服务号")
private String type;
@ApiModelProperty(value = "秘钥")
private String appId;
@ApiModelProperty(value = "秘钥(公众号服务APPsecret和企业服务CorpSecret)")
private String secret;
@ApiModelProperty(value = "企业应用的id")
private String agentId;
@ApiModelProperty(value = "0 不增加新用户, 1 增加新用户到系统")
private Integer isAddedUser;
@ApiModelProperty(value = "站点code")
private String siteCode;
@ApiModelProperty(value = "企业code")
private String companyCode;
@ApiModelProperty(value = "url")
private String url;
}
package com.yizhi.wechat.application.vo.wechat;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* <p>
*
* </p>
*
* @author lilingye
* @since 2018年7月31日17:23:03
*/
@Data
public class ResponseVO {
@ApiModelProperty(value = "返回code")
private String code;
@ApiModelProperty(value = "返回信息")
private String msg;
}
package com.yizhi.wechat.application.vo.wechat;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 签名返回参数
* @author lilingye
*/
@Data
@Api(tags = "SignatrueVO", description = "签名返回参数")
public class SignatureVO {
// 签名
@ApiModelProperty(value = "SHA1的签名")
private String signnatrue;
// 时间戳
@ApiModelProperty(value = "时间戳")
private String timestamp;
// 随机数
@ApiModelProperty(value = "随机数")
private String noncestr;
}
package com.yizhi.wechat.application.vo.wechat;
import com.yizhi.wechat.application.utils.InMsgEntity;
import lombok.Data;
/**
* 类
*
* @author lingye
* @date 2020-8-4
*/
@Data
public class SuiteTicketVO {
private InMsgEntity inMsgEntity;
private String msg_signature;
private String timestamp;
private String nonce;
}
package com.yizhi.wechat.application.vo.wechat;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.FieldFill;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
*
* </p>
*
* @author lilingye
* @since 2018-04-29
*/
@Data
@Api(tags = "TrAccountUserinfoVO", description = "用户数信息返回")
public class TrAccountUserinfoVO {
@ApiModelProperty(value = "主键 唯一标识")
private Long id;
@ApiModelProperty(value = "用户id")
private Long accountId;
@ApiModelProperty(value = "微信公众号服务id")
private String wechatuserid;
@ApiModelProperty(value = "微信公众号服务unionId")
private String unionId;
@ApiModelProperty(value = "站点Id")
private Long siteId;
@ApiModelProperty(value = "企业id")
private Long companyId;
@ApiModelProperty(value = "用类型 0 普通微信公众号用户 1企业微信服务号用户,2 小程序")
private Integer type;
@ApiModelProperty(value = "绑定到开放平台标志 0 未绑定 1 已经绑定")
private Integer bindType;
@ApiModelProperty(value = "创建时间")
private Date createTime;
@ApiModelProperty(value = "是否删除 0 未删除 1删除")
private Integer isDeleted;
@ApiModelProperty(value = "0 不增加新用户, 1 增加新用户到系统")
private Integer isAddedUser;
@ApiModelProperty(value = "用户头像")
private String headImgUrl;
@ApiModelProperty(value = "返回code")
private String code;
}
package com.yizhi.wechat.application.vo.wechat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* @date 2018-8-20
* @author lilingye
*/
@Data
public class WTicketVO implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "服务号的appid")
private String appid;
@ApiModelProperty(value = "服务号的ticket")
private String ticket;
@ApiModelProperty(value = "代理id")
private String agentId;
@ApiModelProperty(value = "添加到reids的时间")
private Date createTime;
}
package com.yizhi.wechat.application.vo.wechat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
@Data
public class WTokenVO implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "服务号的appid")
private String appid;
@ApiModelProperty(value = "服务号的accessToken")
private String accessToken;
@ApiModelProperty(value = "添加到reids的时间")
private Date createTime;
}
package com.yizhi.wechat.application.vo.wechat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
/**
* <p>
*
* </p>
*
* @author lilingye
* @since 2018-04-29
*/
@Data
public class WUserInfoVO {
@ApiModelProperty(value = "表唯一标识id")
private Long id;
@ApiModelProperty(value = "用户的唯一标识")
private String wechatuserid;
@ApiModelProperty(value = "用户昵称")
private String nickname;
@ApiModelProperty(value = "性别。0表示未定义,1表示男性,2表示女性")
private Integer sex;
@ApiModelProperty(value = "省份")
private String province;
@ApiModelProperty(value = "城市")
private String city;
@ApiModelProperty(value = "国家")
private String country;
@ApiModelProperty(value = "用户头像")
private String headimgurl;
@ApiModelProperty(value = "用户特权信息,json 数组,如微信沃卡用户为(chinaunicom)")
private String privilege;
@ApiModelProperty(value = "只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。")
private String unionId;
@ApiModelProperty(value = "企业成员手机号,仅在用户同意snsapi_privateinfo授权时返回")
private String mobile;
@ApiModelProperty(value = "企业成员邮箱")
private String email;
@ApiModelProperty(value = "企业 员工个人二维码,扫描可添加为外部联系人")
private String qrCode;
@ApiModelProperty(value = "0 普通微信用户 1企业微信用户")
private Integer userType;
@ApiModelProperty(value = "创建时间")
private Date createTime;
@ApiModelProperty(value = "电话号码")
private String telephone;
@ApiModelProperty("英文名称")
private String englishName;
@ApiModelProperty(value = "职位")
private String position;
@ApiModelProperty(value = "部门id")
private String departmentId;
@ApiModelProperty(value = "0有效,1删除")
private Integer isDeleted;
@ApiModelProperty(value = "主部门")
private String mainDepartmentId;
}
package com.yizhi.wechat.application.vo.wechat;
import com.yizhi.core.application.context.RequestContext;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;
/**
* 新增企业微信用户VO
*
* @author lilingye
* @date 2018年8月20日14:28:45
*/
@Data
public class WeChatUserVO {
@ApiModelProperty(value = "组织名称")
private List<String> orgNames;
@ApiModelProperty(value = "新增用户VO参数")
private AccountVO accountVO;
@ApiModelProperty(value = "上下文信息")
private RequestContext context;
@ApiModelProperty(value = "corpId")
private String corpId;
}
package com.yizhi.wechat.application.vo.wechat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
public class WechatAccountVO {
@ApiModelProperty(value = "用户的唯一标识")
private String wechatuserid;
@ApiModelProperty(value = "用户昵称")
private String nickname;
@ApiModelProperty(value = "用户id")
private Long accountId;
@ApiModelProperty(value = "工号")
private String workNum;
@ApiModelProperty(value = "真实姓名")
private String fullName;
}
package com.yizhi.wechat.application.vo.wechat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 微信部门
* @date 2018-8-17 11:54:34
* @author lilingye
*/
@Data
public class WechatOrg {
@ApiModelProperty(value = "部门id")
private Long id;
@ApiModelProperty(value = "当前部门名称")
private String name;
@ApiModelProperty(value = "父级id")
private Long parentId;
@ApiModelProperty(value = "顺序")
private Long orderId;
}
package com.yizhi.wechat.application.vo.wechat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 传参的信息
* @author lilingye
* @since 2018-5-21 16:00:00
*/
@Data
public class WechatParamVO {
@ApiModelProperty(value = "user_ticket信息")
private String user_ticket;
}
package com.yizhi.wechat.application.vo.wechat;
import com.yizhi.wechat.application.utils.InMsgEntity;
import lombok.Data;
@Data
public class WechatProviderVO {
private InMsgEntity msg;
private String signature;
private String timestamp;
private String nonce;
}
package com.yizhi.wechat.application.vo.wechat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 返回类
* @author lly
* @date 2018-11-15 11:46:35
*/
@Data
public class WechatUserInfoVO {
@ApiModelProperty(value = " 返回code 0 错误数据 1 正常返回")
private Integer code;
@ApiModelProperty(value = "返回信息")
private String msg;
@ApiModelProperty(value = "微信用户信息返回VO")
private WUserInfoVO wUserInfoVO;
}
package com.yizhi.wechat.application.vo.wechat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;
/**
* 参数Vo
* @author ll
* @data
*/
@Data
public class Wparam {
@ApiModelProperty(value = "id的列表")
private List<Long> ids;
}
package com.yizhi.wechat.application.vo.wechat.domain;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.FieldFill;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
*
* </p>
*
* @author lilingye
* @since 2018-04-29
*/
@Data
@Api(tags = "PublicPlatformConfig", description = "")
public class PublicPlatformConfigVo {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "唯一标识 主键")
private Long id;
@ApiModelProperty(value = "公众号名称")
private String name;
@ApiModelProperty(value = "公众号类型")
private String type;
@ApiModelProperty(value = "秘钥")
@TableField("app_id")
private String appId;
@ApiModelProperty(value = "秘钥(公众号服务APPsecret和企业服务CorpSecret)")
private String secret;
@ApiModelProperty(value = "企业应用的id")
private String agentId;
@TableField(value = "create_time", fill = FieldFill.INSERT)
private Date createTime;
@ApiModelProperty(value = "0 不增加新用户, 1 增加新用户到系统")
private Integer isAddedUser;
@ApiModelProperty(value = "是否删除 0未删除 1已删除")
private Integer isDeleted;
@ApiModelProperty(value = "站点code")
private String siteCode;
@ApiModelProperty(value = "企业code")
private String companyCode;
@ApiModelProperty(value = "企业名称")
@TableField("company_name")
private String companyName;
@ApiModelProperty(value = "站点名称")
private String siteName;
@ApiModelProperty(value = "url")
private String url;
@ApiModelProperty(value = "是否绑定开放平台")
private Integer openPlateFormBind;
@ApiModelProperty(value = "开放品台名称")
private String openPlatformName;
@ApiModelProperty(value = "开放平台id")
private String openPlatformId;
}
package com.yizhi.wechat.application.vo.wechat.domain;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.FieldFill;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
* 第三方应用suite_ticket 表
* </p>
*
* @author lingye
* @since 2020-08-05
*/
@Data
@Api(tags = "SuiteTicket", description = "第三方应用suite_ticket 表")
public class SuiteTicketVo {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "主键")
private Long id;
@ApiModelProperty(value = "suite_id")
private String suiteId;
@ApiModelProperty(value = "suiteticket")
private String suiteTicket;
@ApiModelProperty(value = "创建时间")
private Date createTime;
@ApiModelProperty(value = "更新时间")
@TableField(value = "update_time", fill = FieldFill.INSERT)
private Date updateTime;
@ApiModelProperty(value = "删除标记 1删除 0 未删除")
private Integer deleted;
}
package com.yizhi.wechat.application.vo.wechat.domain;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.FieldFill;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
*
* </p>
*
* @author lilingye
* @since 2018-04-29
*/
@Data
@Api(tags = "TrAccountUserinfo", description = "")
public class TrAccountUserinfoVo{
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "主键 唯一标识")
private Long id;
@ApiModelProperty(value = "用户id")
private Long accountId;
@ApiModelProperty(value = "微信公众号服务id")
private String wechatuserid;
@ApiModelProperty(value = "站点Id")
private Long siteId;
@ApiModelProperty(value = "企业id")
private Long companyId;
@ApiModelProperty(value = "用类型 0 普通微信公众号用户 1企业微信服务号用户")
private Integer type;
private Date createTime;
@ApiModelProperty(value = "是否删除 0 未删除 1删除")
private Integer isDeleted;
private Date updateTime;
@ApiModelProperty(value = "更新人的id")
private Long updateById;
@ApiModelProperty(value = "创建人id")
private Long createById;
private String unionId;
}
package com.yizhi.wechat.application.vo.wechat.domain;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.FieldFill;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
* 用户信息表
* </p>
*
* @author lilingye
* @since 2018-08-20
*/
@Data
@Api(tags = "UserInfo", description = "用户信息表")
public class UserInfoVo{
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "表唯一标识id")
private Long id;
@ApiModelProperty(value = "用户的唯一标识")
private String wechatuserid;
@ApiModelProperty(value = "用户昵称")
private String nickname;
@ApiModelProperty(value = "性别。0表示未定义,1表示男性,2表示女性")
private Integer sex;
@ApiModelProperty(value = "省份")
private String province;
@ApiModelProperty(value = "城市")
private String city;
@ApiModelProperty(value = "国家")
private String country;
@ApiModelProperty(value = "用户头像")
private String headimgurl;
@ApiModelProperty(value = "用户特权信息,json 数组,如微信沃卡用户为(chinaunicom)")
private String privilege;
@ApiModelProperty(value = "只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。")
private String unionId;
@ApiModelProperty(value = "企业成员手机号,仅在用户同意snsapi_privateinfo授权时返回")
private String mobile;
@ApiModelProperty(value = "企业成员邮箱")
private String email;
@ApiModelProperty(value = "电话号码")
private String telephone;
@ApiModelProperty(value = "英文名称")
@TableField("english_name")
private String englishName;
@ApiModelProperty(value = "职位")
private String position;
@ApiModelProperty(value = "企业 员工个人二维码,扫描可添加为外部联系人")
private String qrCode;
@ApiModelProperty(value = "1 普通微信用户 0企业微信用户")
private Integer userType;
@ApiModelProperty(value = "创建时间")
private Date createTime;
@ApiModelProperty(value = "0有效,1删除")
private Integer isDeleted;
@ApiModelProperty(value = "第三方应用id")
private String corpId;
@ApiModelProperty(value = "企业 员工个人二维码,扫描可添加为外部联系人")
private String userId;
@ApiModelProperty(value = "安装应用的设备Id")
private String deviceId;
}
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<parent>
<groupId>com.yizhi</groupId>
<artifactId>cloud-wechat</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.yizhi</groupId>
<artifactId>cloud-wechat-service</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.yizhi</groupId>
<artifactId>cloud-orm</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.yizhi</groupId>
<artifactId>cloud-core</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.yizhi</groupId>
<artifactId>cloud-common-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.yizhi</groupId>
<artifactId>cloud-util</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.yizhi</groupId>
<artifactId>cloud-wechat-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.yizhi</groupId>
<artifactId>cloud-system-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-jackson</artifactId>
<version>10.10.1</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
package com.yizhi.application;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
/**
* <p>
* 代码生成器演示
* </p>
*/
public class MybatisCodeGenerator {
/**
* <p>
* MySQL 生成演示
* </p>
*/
public static void main(String[] args) {
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir("D://mybatis-auto-code");
gc.setFileOverride(true);
gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false
gc.setEnableCache(false);// XML 二级缓存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(false);// XML columList
gc.setAuthor("fulan");
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setTypeConvert(new MySqlTypeConvert() {
// 自定义数据库表字段类型转换【可选】
@Override
public DbColumnType processTypeConvert(String fieldType) {
System.out.println("转换类型:" + fieldType);
// 注意!!processTypeConvert 存在默认类型转换,如果不是你要的效果请自定义返回、非如下直接返回。
return super.processTypeConvert(fieldType);
}
});
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("fulan123");
dsc.setUrl("jdbc:mysql://180.169.149.5:11306/cloud_system?characterEncoding=utf8");
mpg.setDataSource(dsc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setTablePrefix(new String[] { "" });// 此处可以修改为您的表前缀
strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
strategy.setInclude(new String[] { "account"}); // 需要生成的表
strategy.setEntityLombokModel(true);
mpg.setStrategy(strategy);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.yizhi.application");
pc.setModuleName("");
mpg.setPackageInfo(pc);
// 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
this.setMap(map);
}
};
List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
// 调整 xml 生成目录演示
focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return "/develop/code/xml/" + tableInfo.getEntityName() + ".xml";
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
TemplateConfig tc = new TemplateConfig();
tc.setXml(null);
tc.setEntity("/template/entity.java.vm");
mpg.setTemplate(tc);
// 执行生成
mpg.execute();
}
}
\ No newline at end of file
package com.yizhi.application;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("wechatService")
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.yizhi.application"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("微信对接")
//版本
.version("1.0")
.build();
}
}
package com.yizhi.application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@PropertySource(value = {"classpath:wechat-url.properties"}, ignoreResourceNotFound = true)
@EnableTransactionManagement
@SpringBootApplication
@EnableFeignClients(basePackages = {"com.yizhi"})
@ComponentScan(basePackages = {"com.yizhi"})
public class WechatApplication {
public static void main(String[] args) {
SpringApplication.run(WechatApplication.class, args);
}
}
package com.yizhi.application.aes;
@SuppressWarnings("serial")
public class AesException extends Exception {
public final static int OK = 0;
public final static int ValidateSignatureError = -40001;
public final static int ParseXmlError = -40002;
public final static int ComputeSignatureError = -40003;
public final static int IllegalAesKey = -40004;
public final static int ValidateCorpidError = -40005;
public final static int EncryptAESError = -40006;
public final static int DecryptAESError = -40007;
public final static int IllegalBuffer = -40008;
//public final static int EncodeBase64Error = -40009;
//public final static int DecodeBase64Error = -40010;
//public final static int GenReturnXmlError = -40011;
private int code;
private static String getMessage(int code) {
switch (code) {
case ValidateSignatureError:
return "签名验证错误";
case ParseXmlError:
return "xml解析失败";
case ComputeSignatureError:
return "sha加密生成签名失败";
case IllegalAesKey:
return "SymmetricKey非法";
case ValidateCorpidError:
return "corpid校验失败";
case EncryptAESError:
return "aes加密失败";
case DecryptAESError:
return "aes解密失败";
case IllegalBuffer:
return "解密后得到的buffer非法";
// case EncodeBase64Error:
// return "base64加密错误";
// case DecodeBase64Error:
// return "base64解密错误";
// case GenReturnXmlError:
// return "xml生成失败";
default:
return null; // cannot be
}
}
public int getCode() {
return code;
}
AesException(int code) {
super(getMessage(code));
this.code = code;
}
}
package com.yizhi.application.aes;
import java.util.ArrayList;
class ByteGroup {
ArrayList<Byte> byteContainer = new ArrayList<Byte>();
public byte[] toBytes() {
byte[] bytes = new byte[byteContainer.size()];
for (int i = 0; i < byteContainer.size(); i++) {
bytes[i] = byteContainer.get(i);
}
return bytes;
}
public ByteGroup addBytes(byte[] bytes) {
for (byte b : bytes) {
byteContainer.add(b);
}
return this;
}
public int size() {
return byteContainer.size();
}
}
/**
* 对企业微信发送给企业后台的消息加解密示例代码.
*
* @copyright Copyright (c) 1998-2014 Tencent Inc.
*/
// ------------------------------------------------------------------------
package com.yizhi.application.aes;
import java.nio.charset.Charset;
import java.util.Arrays;
/**
* 提供基于PKCS7算法的加解密接口.
*/
class PKCS7Encoder {
static Charset CHARSET = Charset.forName("utf-8");
static int BLOCK_SIZE = 32;
/**
* 获得对明文进行补位填充的字节.
*
* @param count 需要进行填充补位操作的明文字节个数
* @return 补齐用的字节数组
*/
static byte[] encode(int count) {
// 计算需要填充的位数
int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE);
if (amountToPad == 0) {
amountToPad = BLOCK_SIZE;
}
// 获得补位所用的字符
char padChr = chr(amountToPad);
String tmp = new String();
for (int index = 0; index < amountToPad; index++) {
tmp += padChr;
}
return tmp.getBytes(CHARSET);
}
/**
* 删除解密后明文的补位字符
*
* @param decrypted 解密后的明文
* @return 删除补位字符后的明文
*/
static byte[] decode(byte[] decrypted) {
int pad = (int) decrypted[decrypted.length - 1];
if (pad < 1 || pad > 32) {
pad = 0;
}
return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad);
}
/**
* 将数字转化成ASCII码对应的字符,用于对明文进行补码
*
* @param a 需要转化的数字
* @return 转化得到的字符
*/
static char chr(int a) {
byte target = (byte) (a & 0xFF);
return (char) target;
}
}
/**
* 对企业微信发送给企业后台的消息加解密示例代码.
*
* @copyright Copyright (c) 1998-2014 Tencent Inc.
*/
// ------------------------------------------------------------------------
package com.yizhi.application.aes;
import java.security.MessageDigest;
import java.util.Arrays;
/**
* SHA1 class
*
* 计算消息签名接口.
*/
class SHA1 {
/**
* 用SHA1算法生成安全签名
* @param token 票据
* @param timestamp 时间戳
* @param nonce 随机字符串
* @param encrypt 密文
* @return 安全签名
* @throws AesException
*/
public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws AesException
{
try {
String[] array = new String[] { token, timestamp, nonce, encrypt };
StringBuffer sb = new StringBuffer();
// 字符串排序
Arrays.sort(array);
for (int i = 0; i < 4; i++) {
sb.append(array[i]);
}
String str = sb.toString();
// SHA1签名生成
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(str.getBytes());
byte[] digest = md.digest();
StringBuffer hexstr = new StringBuffer();
String shaHex = "";
for (int i = 0; i < digest.length; i++) {
shaHex = Integer.toHexString(digest[i] & 0xFF);
if (shaHex.length() < 2) {
hexstr.append(0);
}
hexstr.append(shaHex);
}
return hexstr.toString();
} catch (Exception e) {
e.printStackTrace();
throw new AesException(AesException.ComputeSignatureError);
}
}
}
/**
* 对企业微信发送给企业后台的消息加解密示例代码.
*
* @copyright Copyright (c) 1998-2014 Tencent Inc.
*/
// ------------------------------------------------------------------------
/**
* 针对org.apache.commons.codec.binary.Base64,
* 需要导入架包commons-codec-1.9(或commons-codec-1.8等其他版本)
* 官方下载地址:http://commons.apache.org/proper/commons-codec/download_codec.cgi
*/
package com.yizhi.application.aes;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 提供接收和推送给企业微信消息的加解密接口(UTF8编码的字符串).
* <ol>
* <li>第三方回复加密消息给企业微信</li>
* <li>第三方收到企业微信发送的消息,验证消息的安全性,并对消息进行解密。</li>
* </ol>
* 说明:异常java.security.InvalidKeyException:illegal Key Size的解决方案
* <ol>
* <li>在官方网站下载JCE无限制权限策略文件(JDK7的下载地址:
* http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html</li>
* <li>下载后解压,可以看到local_policy.jar和US_export_policy.jar以及readme.txt</li>
* <li>如果安装了JRE,将两个jar文件放到%JRE_HOME%\lib\security目录下覆盖原来的文件</li>
* <li>如果安装了JDK,将两个jar文件放到%JDK_HOME%\jre\lib\security目录下覆盖原来文件</li>
* </ol>
*/
public class WXBizMsgCrypt {
static Charset CHARSET = Charset.forName("utf-8");
Base64 base64 = new Base64();
byte[] aesKey;
String token;
String receiveid;
private Logger logger = LoggerFactory.getLogger(WXBizMsgCrypt.class);
/**
* 构造函数
* @param token 企业微信后台,开发者设置的token
* @param encodingAesKey 企业微信后台,开发者设置的EncodingAESKey
* @param receiveid, 不同场景含义不同,详见文档
*
* @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息
*/
public WXBizMsgCrypt(String token, String encodingAesKey, String receiveid) throws AesException {
if (encodingAesKey.length() != 43) {
throw new AesException(AesException.IllegalAesKey);
}
this.token = token;
this.receiveid = receiveid;
aesKey = Base64.decodeBase64(encodingAesKey + "=");
}
// 生成4个字节的网络字节序
byte[] getNetworkBytesOrder(int sourceNumber) {
byte[] orderBytes = new byte[4];
orderBytes[3] = (byte) (sourceNumber & 0xFF);
orderBytes[2] = (byte) (sourceNumber >> 8 & 0xFF);
orderBytes[1] = (byte) (sourceNumber >> 16 & 0xFF);
orderBytes[0] = (byte) (sourceNumber >> 24 & 0xFF);
return orderBytes;
}
// 还原4个字节的网络字节序
int recoverNetworkBytesOrder(byte[] orderBytes) {
int sourceNumber = 0;
for (int i = 0; i < 4; i++) {
sourceNumber <<= 8;
sourceNumber |= orderBytes[i] & 0xff;
}
return sourceNumber;
}
// 随机生成16位字符串
String getRandomStr() {
String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 16; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
/**
* 对明文进行加密.
*
* @param text 需要加密的明文
* @return 加密后base64编码的字符串
* @throws AesException aes加密失败
*/
String encrypt(String randomStr, String text) throws AesException {
ByteGroup byteCollector = new ByteGroup();
byte[] randomStrBytes = randomStr.getBytes(CHARSET);
byte[] textBytes = text.getBytes(CHARSET);
byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length);
byte[] receiveidBytes = receiveid.getBytes(CHARSET);
// randomStr + networkBytesOrder + text + receiveid
byteCollector.addBytes(randomStrBytes);
byteCollector.addBytes(networkBytesOrder);
byteCollector.addBytes(textBytes);
byteCollector.addBytes(receiveidBytes);
// ... + pad: 使用自定义的填充方式对明文进行补位填充
byte[] padBytes = PKCS7Encoder.encode(byteCollector.size());
byteCollector.addBytes(padBytes);
// 获得最终的字节流, 未加密
byte[] unencrypted = byteCollector.toBytes();
try {
// 设置加密模式为AES的CBC模式
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
// 加密
byte[] encrypted = cipher.doFinal(unencrypted);
// 使用BASE64对加密后的字符串进行编码
String base64Encrypted = base64.encodeToString(encrypted);
return base64Encrypted;
} catch (Exception e) {
e.printStackTrace();
throw new AesException(AesException.EncryptAESError);
}
}
/**
* 对密文进行解密.
*
* @param text 需要解密的密文
* @return 解密得到的明文
* @throws AesException aes解密失败
*/
String decrypt(String text) throws AesException {
logger.info("需要解密的text = {}", text);
byte[] original;
try {
// 设置解密模式为AES的CBC模式
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec key_spec = new SecretKeySpec(aesKey, "AES");
IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16));
cipher.init(Cipher.DECRYPT_MODE, key_spec, iv);
// 使用BASE64对密文进行解码
byte[] encrypted = Base64.decodeBase64(text);
// 解密
original = cipher.doFinal(encrypted);
} catch (Exception e) {
e.printStackTrace();
throw new AesException(AesException.DecryptAESError);
}
String xmlContent, from_receiveid;
try {
// 去除补位字符
byte[] bytes = PKCS7Encoder.decode(original);
// 分离16位随机字符串,网络字节序和receiveid
byte[] networkOrder = Arrays.copyOfRange(bytes, 16, 20);
int xmlLength = recoverNetworkBytesOrder(networkOrder);
xmlContent = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), CHARSET);
from_receiveid = new String(Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length),
CHARSET);
} catch (Exception e) {
e.printStackTrace();
throw new AesException(AesException.IllegalBuffer);
}
// receiveid不相同的情况
if (!from_receiveid.equals(receiveid)) {
logger.info("from_receiveid = {}, receiveid={}", from_receiveid, receiveid);
throw new AesException(AesException.ValidateCorpidError);
}
return xmlContent;
}
/**
* 将企业微信回复用户的消息加密打包.
* <ol>
* <li>对要发送的消息进行AES-CBC加密</li>
* <li>生成安全签名</li>
* <li>将消息密文和安全签名打包成xml格式</li>
* </ol>
*
* @param replyMsg 企业微信待回复用户的消息,xml格式的字符串
* @param timeStamp 时间戳,可以自己生成,也可以用URL参数的timestamp
* @param nonce 随机串,可以自己生成,也可以用URL参数的nonce
*
* @return 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串
* @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息
*/
public String EncryptMsg(String replyMsg, String timeStamp, String nonce) throws AesException {
// 加密
String encrypt = encrypt(getRandomStr(), replyMsg);
// 生成安全签名
if (timeStamp == "") {
timeStamp = Long.toString(System.currentTimeMillis());
}
String signature = SHA1.getSHA1(token, timeStamp, nonce, encrypt);
// System.out.println("发送给平台的签名是: " + signature[1].toString());
// 生成发送的xml
String result = XMLParse.generate(encrypt, signature, timeStamp, nonce);
return result;
}
/**
* 检验消息的真实性,并且获取解密后的明文.
* <ol>
* <li>利用收到的密文生成安全签名,进行签名验证</li>
* <li>若验证通过,则提取xml中的加密消息</li>
* <li>对消息进行解密</li>
* </ol>
*
* @param msgSignature 签名串,对应URL参数的msg_signature
* @param timeStamp 时间戳,对应URL参数的timestamp
* @param nonce 随机串,对应URL参数的nonce
* @param postData 密文,对应POST请求的数据
*
* @return 解密后的原文
* @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息
*/
public String DecryptMsg(String msgSignature, String timeStamp, String nonce, String postData)
throws AesException {
// 密钥,公众账号的app secret
// 提取密文
Object[] encrypt = XMLParse.extract(postData);
logger.info("提取的密文={}", JSON.toJSONString(encrypt));
// 验证安全签名
String signature = SHA1.getSHA1(token, timeStamp, nonce, encrypt[1].toString());
// 和URL中的签名比较是否相等
// System.out.println("第三方收到URL中的签名:" + msg_sign);
// System.out.println("第三方校验签名:" + signature);
if (!signature.equals(msgSignature)) {
logger.error("传参签名:" + msgSignature + "----解密签名:" + signature);
throw new AesException(AesException.ValidateSignatureError);
}
// 解密
String result = decrypt(encrypt[1].toString());
return result;
}
/**
* 验证URL
* @param msgSignature 签名串,对应URL参数的msg_signature
* @param timeStamp 时间戳,对应URL参数的timestamp
* @param nonce 随机串,对应URL参数的nonce
* @param echoStr 随机串,对应URL参数的echostr
*
* @return 解密之后的echostr
* @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息
*/
public String VerifyURL(String msgSignature, String timeStamp, String nonce, String echoStr)
throws AesException {
String signature = SHA1.getSHA1(token, timeStamp, nonce, echoStr);
if (!signature.equals(msgSignature)) {
throw new AesException(AesException.ValidateSignatureError);
}
String result = decrypt(echoStr);
return result;
}
}
\ No newline at end of file
/**
* 对企业微信发送给企业后台的消息加解密示例代码.
*
* @copyright Copyright (c) 1998-2014 Tencent Inc.
*/
// ------------------------------------------------------------------------
package com.yizhi.application.aes;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
/**
* XMLParse class
*
* 提供提取消息格式中的密文及生成回复消息格式的接口.
*/
class XMLParse {
/**
* 提取出xml数据包中的加密消息
* @param xmltext 待提取的xml字符串
* @return 提取出的加密消息字符串
* @throws AesException
*/
public static Object[] extract(String xmltext) throws AesException {
Object[] result = new Object[3];
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
String FEATURE = null;
// This is the PRIMARY defense. If DTDs (doctypes) are disallowed, almost all XML entity attacks are prevented
// Xerces 2 only - http://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl
FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
dbf.setFeature(FEATURE, true);
// If you can't completely disable DTDs, then at least do the following:
// Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-general-entities
// Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-general-entities
// JDK7+ - http://xml.org/sax/features/external-general-entities
FEATURE = "http://xml.org/sax/features/external-general-entities";
dbf.setFeature(FEATURE, false);
// Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-parameter-entities
// Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities
// JDK7+ - http://xml.org/sax/features/external-parameter-entities
FEATURE = "http://xml.org/sax/features/external-parameter-entities";
dbf.setFeature(FEATURE, false);
// Disable external DTDs as well
FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
dbf.setFeature(FEATURE, false);
// and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks"
dbf.setXIncludeAware(false);
dbf.setExpandEntityReferences(false);
// And, per Timothy Morgan: "If for some reason support for inline DOCTYPEs are a requirement, then
// ensure the entity settings are disabled (as shown above) and beware that SSRF attacks
// (http://cwe.mitre.org/data/definitions/918.html) and denial
// of service attacks (such as billion laughs or decompression bombs via "jar:") are a risk."
// remaining parser logic
DocumentBuilder db = dbf.newDocumentBuilder();
StringReader sr = new StringReader(xmltext);
InputSource is = new InputSource(sr);
Document document = db.parse(is);
Element root = document.getDocumentElement();
NodeList nodelist1 = root.getElementsByTagName("Encrypt");
NodeList nodelist2 = root.getElementsByTagName("ToUserName");
result[0] = 0;
result[1] = nodelist1.item(0).getTextContent();
result[2] = nodelist2.item(0).getTextContent();
return result;
} catch (Exception e) {
e.printStackTrace();
throw new AesException(AesException.ParseXmlError);
}
}
/**
* 生成xml消息
* @param encrypt 加密后的消息密文
* @param signature 安全签名
* @param timestamp 时间戳
* @param nonce 随机字符串
* @return 生成的xml字符串
*/
public static String generate(String encrypt, String signature, String timestamp, String nonce) {
String format = "<xml>\n" + "<Encrypt><![CDATA[%1$s]]></Encrypt>\n"
+ "<MsgSignature><![CDATA[%2$s]]></MsgSignature>\n"
+ "<TimeStamp>%3$s</TimeStamp>\n" + "<Nonce><![CDATA[%4$s]]></Nonce>\n" + "</xml>";
return String.format(format, encrypt, signature, timestamp, nonce);
}
}
package com.yizhi.application.controller;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.yizhi.application.domain.PublicPlatformConfig;
import com.yizhi.application.service.IAccessTokenService;
import com.yizhi.application.service.IPublicPlatformConfigService;
import com.yizhi.wechat.application.vo.wechat.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @ClassName AccessTokenController
* @Description TODO
* @Author shengchenglong
* @DATE 2020/11/25 22:42
* @Version 1.0
*/
@RestController
@RequestMapping("/weixin/accessToken")
public class AccessTokenController {
@Autowired
private IAccessTokenService accessTokenService;
@Autowired
private IPublicPlatformConfigService publicPlatformConfigService;
@GetMapping("get")
public String getAccessToken(@RequestParam("appId") String appId) {
PublicPlatformConfig publicPlatformConfig = new PublicPlatformConfig();
publicPlatformConfig.setIsDeleted(Constants.NO_FLAG);
publicPlatformConfig.setAppId(appId);
EntityWrapper<PublicPlatformConfig> ew = new EntityWrapper<>(publicPlatformConfig);
publicPlatformConfig = publicPlatformConfigService.selectOne(ew);
if (publicPlatformConfig == null) {
return null;
}
return accessTokenService.getAccessToken(publicPlatformConfig);
}
}
package com.yizhi.application.controller;
import com.alibaba.fastjson.JSON;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.application.domain.PublicPlatformConfig;
import com.yizhi.application.domain.TrAccountUserinfo;
import com.yizhi.application.orm.id.IdGenerator;
import com.yizhi.application.service.IPublicPlatformConfigService;
import com.yizhi.system.application.vo.domain.Account;
import com.yizhi.system.application.system.remote.AccountClient;
import com.yizhi.system.application.system.remote.SiteClient;
import com.yizhi.util.application.encrypt.ShaEncrypt;
import com.yizhi.system.application.vo.AccountVO;
import com.yizhi.wechat.application.vo.wechat.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 自定义项目定义届酷狗
*
* @author lingye
* @date 2020-3-23 17:49:01
*/
@RestController
@RequestMapping(value = "/custom/project")
public class CustomProjectController {
public static final Logger LOGGER = LoggerFactory.getLogger(CustomProjectController.class);
@Autowired
private SiteClient siteClient;
@Autowired
private AccountClient accountClient;
@Autowired
private UserInfoController userInfoController;
@Autowired
private IPublicPlatformConfigService iPublicPlatformConfigService;
@Autowired
private WeChatUserController weChatUserController;
@Value("${wechat.account.initializtion.pwd}")
private String password;
@Autowired
IdGenerator idGenerator;
@GetMapping(value = "/token")
public Map<String, Object> getToken(@RequestParam(name = "weChatUserId", required = true) String weChatUserId,
@RequestParam(name = "appId", required = true) String appId,
@RequestParam(name = "agentId", required = false) String agentId,
@RequestParam(name = "orgId", required = true) Long orgId
) {
RequestContext context = ContextHolder.get();
LOGGER.info("请求的上下文信息:{}", JSON.toJSON(context));
Map<String, Object> retMap = new HashMap<String, Object>(16);
retMap.put("returnCode", 1);
//获取企业的信息
Long siteId = context.getSiteId();
String siteCode = context.getSiteCode();
Long companyId = context.getCompanyId();
String companyCode = context.getCompanyCode();
TrAccountUserinfo trAccountUserinfo = userInfoController.queryUserInWechat(weChatUserId, companyId);
PublicPlatformConfig platformConfig = null;
List<PublicPlatformConfig> pubConfigs = iPublicPlatformConfigService.getPubConfigs(appId, agentId);
LOGGER.info("公众号配置所有列表:{}", JSON.toJSON(pubConfigs));
if (pubConfigs == null) {
retMap.put("returnCode", 2);
return retMap;
}
for (PublicPlatformConfig config : pubConfigs) {
if (companyCode.equals(config.getCompanyCode()) && siteCode.equals(config.getSiteCode())) {
platformConfig = config;
break;
}
}
if (platformConfig == null) {
// 公众号配置的站点和链接的站点不匹配
retMap.put("returnCode", 2);
return retMap;
}
LOGGER.info("公众号配置:{}", JSON.toJSON(platformConfig));
AccountVO accountVO = new AccountVO();
if (null != trAccountUserinfo) {
accountVO = accountClient.findById(trAccountUserinfo.getAccountId());
LOGGER.info("当前用户的信息accountVO:{}", accountVO);
retMap.put("userInfo", accountVO);
weChatUserController.addUserLoginLog(companyId, siteId, accountVO, Constants.FIVE);
return retMap;
} else {
Account account = new Account();
account.setId(idGenerator.generate());
account.setName(weChatUserId);
account.setCompanyId(companyId);
account.setOrgId(orgId);
account.setPassword(ShaEncrypt.encryptNewPassword(password));
account.setCreateTime(new Date());
account.setCreateByName("system");
Account user = accountClient.saveThirdAccount(account);
BeanUtils.copyProperties(user, accountVO);
// 生成站点访问权限
siteClient.relateAccountSite(siteId, account.getCompanyId(), siteCode);
//绑定用户
weChatUserController.bindCompanyWeChatUser(weChatUserId, companyId, siteId, account.getId(),4);
LOGGER.info("当前用户的信息accountVO:{}", accountVO);
retMap.put("userInfo", accountVO);
weChatUserController.addUserLoginLog(companyId, siteId, accountVO, Constants.FIVE);
return retMap;
}
}
}
package com.yizhi.application.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.application.domain.PublicPlatformConfig;
import com.yizhi.application.domain.TrAccountUserinfo;
import com.yizhi.application.service.IPublicPlatformConfigService;
import com.yizhi.application.service.ITrAccountUserinfoService;
import com.yizhi.application.task.UpdateUserInfoService;
import com.yizhi.wechat.application.utils.HttpClientUtils;
import com.yizhi.wechat.application.vo.wechat.Constants;
import com.yizhi.wechat.application.vo.wechat.MiniProgramVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* 第三方用户信息获取类
*
* @author lingye
* @date 2020-1-2
*/
@RestController
@RequestMapping(value = "/miniProgram")
public class MiniProgramController {
public static final Logger LOGGER = LoggerFactory.getLogger(MiniProgramController.class);
HttpClientUtils httpClientUtils = new HttpClientUtils();
@Value("${cloud.min.program.base_url}")
private String baseUrl;
@Autowired
private IPublicPlatformConfigService iPublicPlatformConfigService;
@Autowired
private ITrAccountUserinfoService iTrAccountUserinfoService;
@Autowired
private UpdateUserInfoService updateUserInfoService;
@GetMapping(value = "/get")
public MiniProgramVo getMiniProgram(
@RequestParam(name = "appId", required = true) String appId,
@RequestParam(name = "code", required = true) String code,
@RequestParam(name = "headImg", required = false) String headImg
) {
RequestContext context = ContextHolder.get();
LOGGER.info("上下文信息:{}", JSON.toJSON(context));
// 获取配置信息
LOGGER.info("签名接口参数appId:" + appId);
PublicPlatformConfig publicPlatformConfig = iPublicPlatformConfigService.getPubConfig(appId, null);
String url = baseUrl + "?appid=" + appId + "&secret=" + publicPlatformConfig.getSecret() + "&js_code=" + code + "&grant_type=authorization_code";
String ret = httpClientUtils.httpGet(url);
LOGGER.info("获取unionId 和 openId 的结果:{}", JSON.toJSON(ret));
JSONObject retJson = JSONObject.parseObject(ret);
MiniProgramVo miniProgramVo = new MiniProgramVo();
// String errcode = retJson.getString("errcode");
// if (!Constants.ZERO.equals(errcode)) {
// String errMsg = retJson.getString("errmsg");
// miniProgramVo.setCode(errcode);
// miniProgramVo.setMsg(errMsg);
// return miniProgramVo;
// }
boolean result = false;
TrAccountUserinfo userInfo = new TrAccountUserinfo();
String openId = null;
String unionId = null;
TrAccountUserinfo account = null;
if (publicPlatformConfig.getOpenPlateFormBind() == 1) {
unionId = retJson.getString("unionid");
LOGGER.info("获取到的unionId:{}", unionId);
if (unionId != null) {
miniProgramVo.setUnionId(unionId);
userInfo.setUnionId(unionId);
account = findBindWeChat(userInfo, context.getCompanyId());
} else {
result = false ;
}
} else {
openId = retJson.getString("openid");
LOGGER.info("获取到的openId:{}", openId);
if (openId != null) {
miniProgramVo.setOpenId(openId);
userInfo.setWechatuserid(openId);
account = findBindWeChat(userInfo, context.getCompanyId());
} else {
result = false ;
}
}
// 异步新增用户信息到用户表
updateUserInfoService.addMiniProgramUserInfo(openId, unionId);
LOGGER.info("返回的关系表:{}",JSON.toJSON(account));
miniProgramVo.setCode(Constants.ZERO);
miniProgramVo.setAccountId(account != null ? account.getAccountId() : 0L);
if (null != account) {
updateUserInfoService.taskUpdateMiniUserInfo(account.getAccountId(), headImg);
result = true;
}
miniProgramVo.setRet(result);
return miniProgramVo;
}
public TrAccountUserinfo findBindWeChat(TrAccountUserinfo userInfo,Long companyId){
userInfo.setIsDeleted(0);
userInfo.setCompanyId(companyId);
return iTrAccountUserinfoService.findBindWechat(userInfo);
}
}
package com.yizhi.application.controller;
import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.application.domain.PublicPlatformConfig;
import com.yizhi.application.service.IPublicPlatformConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author lilingye
* @since 2018-04-29
*/
@RestController
@RequestMapping("/publicPlatformConfig")
public class PublicPlatformConfigController {
@Autowired
private IPublicPlatformConfigService publicPlatformConfigService;
/**
* 添加服务号的配置信息
*
* @param publicPlatformConfig
* @return
*/
@PostMapping(value = "/insert")
public PublicPlatformConfig insertPublicPlatformConfigInfo(@RequestBody PublicPlatformConfig publicPlatformConfig) {
return publicPlatformConfigService.insertPublicPlatformConfigInfo(publicPlatformConfig);
}
/**
* 查询
*
* @return
*/
@GetMapping(value = "/get")
public PublicPlatformConfig getPublicPlatformConfigInfo(@RequestParam(value = "id") Long id) {
return publicPlatformConfigService.selectById(id);
}
/**
* 修改服务号的配置信息
*
* @return
*/
@PostMapping(value = "/update")
public PublicPlatformConfig updatePublicPlatformConfigInfo(@RequestBody PublicPlatformConfig publicPlatformConfig) {
publicPlatformConfigService.updateById(publicPlatformConfig);
return publicPlatformConfigService.selectById(publicPlatformConfig.getId());
}
/**
* 查询list
*
* @return
*/
@GetMapping(value = "/list")
public Page<PublicPlatformConfig> getPublicPlatformConfigs(@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
@RequestParam(value = "name", required = false) String name) {
return publicPlatformConfigService.findPublicConfigList(pageNo, pageSize, name);
}
/**
* 删除
*
* @param ids
* @return
*/
@GetMapping(value = "/delete")
public boolean deletePublicPlatformConfig(@RequestBody List<Long> ids) {
return publicPlatformConfigService.deleteBatchIds(ids);
}
@PostMapping(value = "/getInfo")
public PublicPlatformConfig findPublicPlatformConfig(@RequestBody PublicPlatformConfig publicPlatformConfig) {
return publicPlatformConfigService.getPublicPlatformConfig(publicPlatformConfig);
}
}
package com.yizhi.application.controller;
import com.alibaba.fastjson.JSON;
import com.yizhi.core.application.cache.RedisCache;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Api(tags = "微信登录接口")
@RequestMapping("/mytest/")
public class TestRedis {
@Autowired
RedisCache redisCache;
@GetMapping(value = "/get")
public Object getUser(
@RequestParam(name = "paramUser", required = false) String paramUser
) {
Object pwdTime = redisCache.hget("account:pwd", paramUser);
return JSON.toJSONString(pwdTime);
}
@GetMapping(value = "/set")
public Boolean setUser(
@RequestParam(name = "paramUser", required = false) String paramUser,
@RequestParam(name = "time", required = false) Integer time
) {
boolean pwd = redisCache.hset("account:pwd", paramUser, "pwd", time);
return pwd;
}
@GetMapping(value = "/setredis")
public Boolean seRetUser(
@RequestParam(name = "paramUser", required = false) String paramUser,
@RequestParam(name = "time", required = false) Integer time
) {
boolean hset = redisCache.hset("pwd" + paramUser, "pwd"+paramUser, paramUser, time);
return hset;
}
@GetMapping(value = "/getRedis")
public Object getRetUser(
@RequestParam(name = "paramUser", required = false) String paramUser
) {
Object o = redisCache.hget("pwd" + paramUser,"pwd"+paramUser);
System.out.println("返回:" + JSON.toJSON(o));
return o;
}
}
package com.yizhi.application.controller;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.yizhi.application.domain.TrAccountUserinfo;
import com.yizhi.application.domain.UserInfo;
import com.yizhi.application.orm.util.DomainConverter;
import com.yizhi.application.orm.util.QueryUtil;
import com.yizhi.application.service.ITrAccountUserinfoService;
import com.yizhi.application.service.IUserInfoService;
import com.yizhi.application.service.impl.UserInfoServiceImpl;
import com.yizhi.system.application.system.remote.AccountClient;
import com.yizhi.wechat.application.vo.wechat.AccountVO;
import com.yizhi.wechat.application.vo.wechat.AuthorizeUsersVO;
import com.yizhi.wechat.application.vo.wechat.Constants;
import com.yizhi.wechat.application.vo.wechat.ResponseVO;
import com.yizhi.wechat.application.vo.wechat.TrAccountUserinfoVO;
import com.yizhi.wechat.application.vo.wechat.WechatUserInfoVO;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.poi.util.ArrayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.util.stream.Collectors;
/**
* <p>
* 前端控制器
* </p>
*
* @author lilingye
* @since 2018-04-29
*/
@Log4j2
@RestController
@RequestMapping("/trAccountUserinfo")
public class TrAccountUserinfoController {
@Autowired
private ITrAccountUserinfoService iTrAccountUserinfoService;
@Autowired
private AccountClient accountClient;
@Autowired
private UserInfoController userInfoController;
@Autowired
private IUserInfoService userInfoService;
@Autowired
DomainConverter domainConverter;
/**
* 保存微信id和系统用户id的关系
*
* @param wechatUserId 用户的微信di
* @param accountId 系统账号的id
* @return TrAccountInfo
*/
@RequestMapping(value = "/save/accountinfo", method = RequestMethod.GET)
public TrAccountUserinfoVO saveTrAccountUserinfo(@RequestParam(value = "wechatUserId", required = true) String wechatUserId,
@RequestParam(value = "unionId", required = false) String unionId,
@RequestParam(value = "accountId", required = true) Long accountId,
@RequestParam(value = "siteId", required = true) Long siteId,
@RequestParam(value = "companyId", required = true) Long companyId,
@RequestParam(value = "terminalType", required = false) Integer terminalType
) {
log.info("保存微信wechatId 和未木云账号的关系:");
log.info("参数wechatuserid:" + wechatUserId + ";参数accountId:" + accountId + ";参数siteId:" + siteId);
log.info("companyId:" + companyId);
TrAccountUserinfoVO trAccountUserinfoVO = new TrAccountUserinfoVO();
trAccountUserinfoVO.setWechatuserid(wechatUserId);
trAccountUserinfoVO.setAccountId(accountId);
trAccountUserinfoVO.setSiteId(siteId);
trAccountUserinfoVO.setCompanyId(companyId);
trAccountUserinfoVO.setType(terminalType);
return iTrAccountUserinfoService.saveAccount(trAccountUserinfoVO);
}
/**
* 解绑用户和微信的绑定关心
*
* @param ids 用户id
* @return
*/
@PostMapping(value = "/del/relations")
public ResponseVO delRelation(@RequestBody List<Long> ids) {
TrAccountUserinfo trAccountUserinfo = new TrAccountUserinfo();
TrAccountUserinfo accountUserinfo = new TrAccountUserinfo();
List<TrAccountUserinfo> trAccountUserinfoList = new ArrayList<TrAccountUserinfo>();
// 初始化存放用户id的
List<Long> accountIds = new ArrayList<Long>();
Date date = new Date();
for (Long id : ids
) {
accountUserinfo.setAccountId(id);
accountUserinfo.setIsDeleted(0);
trAccountUserinfo = iTrAccountUserinfoService.selectOne(QueryUtil.condition(accountUserinfo));
if (trAccountUserinfo != null) {
trAccountUserinfo.setIsDeleted(1);
trAccountUserinfo.setUpdateTime(date);
trAccountUserinfoList.add(trAccountUserinfo);
} else {
accountIds.add(id);
}
}
StringBuffer sb = new StringBuffer();
sb.append("共操作").append(ids.size()).append("条,")
.append("成功").append(ids.size() - accountIds.size()).append("条,")
.append("失败").append(accountIds.size()).append("条。");
//查询用户的列表
List<AccountVO> accountVOS = null;
if (accountIds.size() > 0) {
List<com.yizhi.system.application.vo.AccountVO> accountVOS1 = accountClient.findByIds(accountIds);
accountVOS = domainConverter.toDOList(accountVOS1,AccountVO.class);
}
if (CollectionUtils.isNotEmpty(accountVOS)) {
sb.append("失败原因:");
for (int i = 0; i < accountVOS.size(); i++) {
if (i != accountVOS.size()) {
sb.append(accountVOS.get(i).getName()).append(",");
} else {
sb.append(accountVOS.get(i).getName());
}
}
sb.append(" 未绑定微信,不需要解绑!");
}
// 初始化返回对象
ResponseVO responseVO = new ResponseVO();
if (CollectionUtils.isNotEmpty(trAccountUserinfoList)) {
boolean flag = iTrAccountUserinfoService.updateBatchById(trAccountUserinfoList);
responseVO.setCode("1");
responseVO.setMsg(sb.toString());
return responseVO;
} else {
responseVO.setCode("0");
responseVO.setMsg("您操作解绑的账号均未绑定微信,请重新选择!");
return responseVO;
}
}
/**
* 通过用户的id获取微信openId
*
* @param accountId
* @return
*/
@GetMapping(value = "/get/wechatid")
public String getWechatIdbyAccountId(@RequestParam(name = "accountId") Long accountId) {
TrAccountUserinfo trAccountUserinfo = new TrAccountUserinfo();
trAccountUserinfo.setIsDeleted(0);
trAccountUserinfo.setAccountId(accountId);
trAccountUserinfo = this.iTrAccountUserinfoService.selectOne(QueryUtil.condition(trAccountUserinfo));
if (trAccountUserinfo != null) {
return trAccountUserinfo.getWechatuserid();
} else {
return null;
}
}
@PostMapping(value = "/relation/get")
public TrAccountUserinfo getAccountUserInfo(@RequestBody TrAccountUserinfo trAccountUserinfo) {
trAccountUserinfo.setIsDeleted(0);
EntityWrapper<TrAccountUserinfo> condition = QueryUtil.condition(trAccountUserinfo);
List<TrAccountUserinfo> trAccountUserinfos = iTrAccountUserinfoService.selectList(condition);
if (CollectionUtils.isEmpty(trAccountUserinfos)){
return null;
}
return trAccountUserinfos.get(0);
}
/**
* 保存wechatId和accountId
*
* @param userInfoVO
* @return
*/
@PostMapping(value = "/save")
public TrAccountUserinfoVO saveWechatUserInfo(@RequestBody TrAccountUserinfoVO userInfoVO) {
return iTrAccountUserinfoService.saveAccount(userInfoVO);
}
/**
* 修改关联关系
*
* @param trAccountUserinfo
* @return
*/
@PostMapping(value = "/stop")
public Boolean updateTrAccountUserInfo(@RequestBody TrAccountUserinfo trAccountUserinfo) {
trAccountUserinfo.setIsDeleted(0);
EntityWrapper<TrAccountUserinfo> condition = QueryUtil.condition(trAccountUserinfo);
TrAccountUserinfo userInfo = iTrAccountUserinfoService.selectOne(condition);
if (userInfo != null) {
return iTrAccountUserinfoService.updateTrAccountUserInfo(userInfo);
} else {
return true;
}
}
/**
* 根据微信weChatUserId解绑
*
* @param weChatUserId
* @return
*/
@PostMapping(value = "/unbind/weChatUserId")
public Boolean unbindAccountByWeChatUserId(@RequestParam(name = "weChatUserId", required = true) String weChatUserId) {
return iTrAccountUserinfoService.unbindAccountByWeChatUserId(weChatUserId);
}
/**
* 根据微信weChatUserId解绑
*
* @return
*/
@PostMapping(value = "/unbind/batch/weChatUserId")
public Boolean unbindAccount(
@RequestParam(value = "code") String code,
@RequestParam(value = "appId") String appId,
@RequestParam(value = "agentId", required = false) String agentId) {
WechatUserInfoVO userInfo = userInfoController.getUserInfo(code, appId, agentId,null);
log.info("获取到的用户信息:" + userInfo);
if (null != userInfo) {
return iTrAccountUserinfoService.unbindAccountByWeChatUserId(userInfo.getWUserInfoVO().getWechatuserid());
}
return false;
}
/**
* 批量解绑用户
* @param accountIds
* @return
*/
@PostMapping(value = "/unbindUser")
public Boolean unbindUser(@RequestBody List<Long> accountIds) {
TrAccountUserinfo trAccountUserinfo = new TrAccountUserinfo();
trAccountUserinfo.setIsDeleted(Constants.NO_FLAG);
EntityWrapper<TrAccountUserinfo> condition = QueryUtil.condition(trAccountUserinfo);
condition.in("account_id", accountIds);
List<TrAccountUserinfo> trAccountUserInfoList = iTrAccountUserinfoService.selectList(condition);
Date date = new Date();
if (CollectionUtils.isNotEmpty(trAccountUserInfoList)) {
trAccountUserInfoList.parallelStream().map(accountUser -> {
accountUser.setIsDeleted(Constants.YES_FLAG);
accountUser.setUpdateTime(date);
return accountUser;
}).collect(Collectors.toList());
iTrAccountUserinfoService.updateBatchById(trAccountUserInfoList);
return Boolean.TRUE;
}
return Boolean.FALSE;
}
/**
* 获取用户的绑定关系
* @param authorizeUsersVO
* @return
*/
@PostMapping(value = "/get/bind/relation")
public Map<Long,TrAccountUserinfo> getUserRelations(@RequestBody AuthorizeUsersVO authorizeUsersVO) {
TrAccountUserinfo trAccountUserinfo = new TrAccountUserinfo();
trAccountUserinfo.setIsDeleted(Constants.NO_FLAG);
trAccountUserinfo.setCompanyId(authorizeUsersVO.getRoleId());
EntityWrapper<TrAccountUserinfo> condition = QueryUtil.condition(trAccountUserinfo);
condition.in("account_id", authorizeUsersVO.getUserIds());
// condition.ne("type",3);
List<TrAccountUserinfo> trAccountUserInfoList = iTrAccountUserinfoService.selectList(condition);
List<UserInfo> userInfos = null;
if (!CollectionUtils.isEmpty(trAccountUserInfoList)) {
List<String> userInfoWechatUserIds =
trAccountUserInfoList.stream().map(TrAccountUserinfo::getWechatuserid).collect(Collectors.toList());
log.info("wechatUserId:{}", ArrayUtils.toString(userInfoWechatUserIds.toArray()));
EntityWrapper<UserInfo> entityWrapper = new EntityWrapper<>();
entityWrapper.eq("is_deleted", Constants.DEL_FLAG);
entityWrapper.in("wechatuserid", userInfoWechatUserIds);
userInfos = userInfoService.selectList(entityWrapper);
//获取用户微信昵称信息
log.info("userInfoIds:{}", ArrayUtils.toString(userInfos.toArray()));
}
if (!CollectionUtils.isEmpty(userInfos)){
Map<String,String> userInfoMap = userInfos.stream().collect(
Collectors.toMap(UserInfo::getWechatuserid, UserInfo::getNickname,(s,a)->s)
);
for (TrAccountUserinfo accountUserinfos: trAccountUserInfoList) {
log.info("用户昵称:"+userInfoMap.get(accountUserinfos.getWechatuserid()));
if (userInfoMap.get(accountUserinfos.getWechatuserid()) == null) {
accountUserinfos.setWechatuserid("");
} else {
accountUserinfos.setWechatuserid(userInfoMap.get(accountUserinfos.getWechatuserid()));
}
}
}
Map<Long, TrAccountUserinfo> entityMap= trAccountUserInfoList.stream().collect(
Collectors.toMap(TrAccountUserinfo::getAccountId, TrAccountUserinfo->TrAccountUserinfo, (s, a) -> s));
return entityMap;
}
}
package com.yizhi.application.controller;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.yizhi.core.application.cache.RedisCache;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.application.domain.PublicPlatformConfig;
import com.yizhi.application.domain.TrAccountUserinfo;
import com.yizhi.application.domain.UserInfo;
import com.yizhi.application.orm.util.QueryUtil;
import com.yizhi.application.service.*;
import com.yizhi.wechat.application.vo.wechat.*;
import com.yizhi.wechat.application.vo.wechat.AccountVO;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* <p>
* 前端控制器
* </p>
*
* @author lilingye
* @since 2018-04-29
*/
@RestController
@RequestMapping("/wechat")
public class UserInfoController {
private static final Logger LOGGER = LoggerFactory.getLogger(UserInfoController.class);
@Autowired
private IUserInfoService iUserInfoService;
@Autowired
private IPublicPlatformConfigService iPublicPlatformConfigService;
@Autowired
private ITrAccountUserinfoService iTrAccountUserinfoService;
@Autowired
private RedisCache redisCache;
@Autowired
private ICwechatService cwechatService;
@Autowired
IAccessTokenService accessTokenService;
@Autowired
IProviderUserInfoService providerUserInfoService;
/**
* 查询用户是否在微信服务中绑定
*
* @param wechatUserId
* @return
*/
@GetMapping(value = "/get/user")
public TrAccountUserinfo queryUserInWechat(
@RequestParam(name = "wechatUserId") String wechatUserId,
@RequestParam(name = "companyId") Long companyId
) {
// 获取id
TrAccountUserinfo trAccountUserinfo = iTrAccountUserinfoService.findAccount(wechatUserId, companyId);
if (trAccountUserinfo != null) {
LOGGER.info("wechatUserId为:" + wechatUserId + ",存在数据库表中");
return trAccountUserinfo;
} else {
LOGGER.info("wechatUserId为:" + wechatUserId + ",不存在数据库表中");
return null;
}
}
/**
* 获取微信公众服务号用户的信息
*
* @param appid 微信公众号的appid
* @param code 条用微信api获取的code
*/
@RequestMapping(value = "/get/wechatuser", method = RequestMethod.GET)
public WechatUserInfoVO getUserInfo(
@RequestParam(value = "code") String code,
@RequestParam(value = "appid") String appid,
@RequestParam(value = "agentId", required = false) String agentId,
@RequestParam(value = "source", required = false) Integer source
) {
LOGGER.info("-------------------------------------------");
LOGGER.info("企业的appid:{}", appid);
LOGGER.info("参数code:{}", code);
LOGGER.info("参数agentId:{}", agentId);
LOGGER.info("请求时间:{}",JSON.toJSON(new Date()));
LOGGER.info("--------------------------------------------");
WechatUserInfoVO userInfoVO = new WechatUserInfoVO();
List<PublicPlatformConfig> pubConfigs = iPublicPlatformConfigService.getPubConfigs(appid, agentId);
LOGGER.info("公众号配置所有列表:{}", JSON.toJSON(pubConfigs));
if (CollectionUtils.isEmpty(pubConfigs)) {
LOGGER.info("公众号配置获取为空,请检查参数!!!");
return userInfoVO;
}
PublicPlatformConfig publicPlatformConfig = pubConfigs.get(0);
// 获取微信公众号维护的配置信息
// PublicPlatformConfig publicPlatformConfig = iPublicPlatformConfigService.getPubConfig(appid, agentId);
if ("0".equals(publicPlatformConfig.getType())) {
// 企业服务号
userInfoVO = getCUserInfo(code, appid, publicPlatformConfig.getSecret(), agentId,source);
} else if ("1".equals(publicPlatformConfig.getType())) {
// 微信服务号
userInfoVO = iUserInfoService.getWeChatUserInfo(appid, publicPlatformConfig.getSecret(), code,source);
} else if ("2".equals(publicPlatformConfig.getType())) {
userInfoVO = providerUserInfoService.getProviderInfoDetail(appid,code);
}
return userInfoVO;
}
/**
* 获取微信企业服务号用户的信息
*
* @param appid 企业的CorpID
* @param code 调用微信api获取的code
*/
@ResponseBody
@RequestMapping(value = "/get/cwechatuser", method = RequestMethod.GET)
public WechatUserInfoVO getCUserInfo(
@RequestParam(value = "code", required = true) String code,
@RequestParam(value = "appid", required = true) String appid,
@RequestParam(value = "secret") String secret,
@RequestParam(value = "agentId",required = false) String agentId,
@RequestParam(value = "source" ,required = false) Integer source
) {
LOGGER.info("企业服务号的传来参数appid" + appid);
LOGGER.info("传来的参数code:" + code);
LOGGER.info("传来的参数secret:" + secret);
WUserInfoVO userInfoVO = new WUserInfoVO();
// 组装实体 提供参数
PublicPlatformConfig publicPlatformConfig = new PublicPlatformConfig();
publicPlatformConfig.setAppId(appid);
publicPlatformConfig.setAgentId(agentId);
publicPlatformConfig.setSecret(secret);
return iUserInfoService.getCompanyWechatUserInfo(publicPlatformConfig, code,source);
}
/**
* 获取的签名
*
* @param url
* @since 2018-5-23 17:45:32
*/
@ResponseBody
@RequestMapping(value = "/get/signature", method = RequestMethod.GET)
public SignatureVO getSignature(
@RequestParam(name = "appid") String appid,
@RequestParam(name = "url") String url,
@RequestParam(name = "agentId") String agentId
) {
// 获取配置信息
LOGGER.info("签名接口参数appid:" + appid + ";接口参数agentId:" + agentId + ";接口参数 url:" + url);
PublicPlatformConfig publicPlatformConfig = iPublicPlatformConfigService.getPubConfig(appid, agentId);
LOGGER.info("服务号的类型为:" + publicPlatformConfig);
if (publicPlatformConfig != null) {
LOGGER.info("服务号的类型为:" + publicPlatformConfig.getType());
} else {
LOGGER.error("配置信息查询未空,请检查传参是否正确!!!");
return null;
}
// 首先获取access——token
String access_token = getChatAccessToken(publicPlatformConfig);
LOGGER.info("access_token:" + access_token);
return iUserInfoService.getSignature(access_token, url, publicPlatformConfig);
}
/**
* 获取授权的AccessToken
*
* @return
* @since 2018-5-25 14:35:32
*/
@ResponseBody
@GetMapping(value = "/get/token")
public String getChatAccessToken(@RequestBody PublicPlatformConfig publicPlatformConfig) {
String redisKey = null;
if ("0".equals(publicPlatformConfig.getType())) {
redisKey = (publicPlatformConfig.getAppId() + publicPlatformConfig.getAgentId()).trim();
LOGGER.info("类型为0 的redisKey:" + redisKey);
} else if ("1".equals(publicPlatformConfig.getType())) {
LOGGER.info("类型为1 的redisKey:" + redisKey);
redisKey = publicPlatformConfig.getAppId().trim();
} else if ("2".equals(publicPlatformConfig.getType())){
redisKey = publicPlatformConfig.getAppId().trim();
}
LOGGER.info("redisKey的值:" + redisKey);
//从缓存中获取token
Object tokenVO = redisCache.hget(redisKey, redisKey);
LOGGER.info("类型为0 的redisKey:" + redisKey);
// 声明token
String access_token = null;
// 判断缓存中的redis存在
if (tokenVO != null) {
//获取token
Object tokenJSON = JSON.toJSON(tokenVO);
LOGGER.info("查看缓存中的access_token信息:" + tokenJSON.toString());
LOGGER.info(JSON.parseObject(tokenJSON.toString()).getString("accessToken"));
String accessToken = JSON.parseObject(tokenJSON.toString()).getString("accessToken");
if (!"".equals(accessToken) && !"null".equals(accessToken) && accessToken != null) {
LOGGER.info("accessToken值存在");
return JSON.parseObject(tokenJSON.toString()).getString("accessToken");
} else {
//生成新的token
LOGGER.info("accessToken值不在在,重新获取");
return getAccessToken(publicPlatformConfig);
}
} else {
// 生成新的token
return getAccessToken(publicPlatformConfig);
}
}
/**
* 获取公众号的配置信息
*
* @param appid 公众号的appdId
* @return
* @since 2018-5-25 14:35:24
*/
@RequestMapping(value = "/get/platformconfig", method = RequestMethod.GET)
public PublicPlatformConfig getPlatformconfig(@RequestParam(value = "appid") String appid,
@RequestParam(value = "agentId") String agentId) {
// 获取微信公众号维护的配置信息
PublicPlatformConfig publicPlatformConfig = iPublicPlatformConfigService.getPubConfig(appid, agentId);
if (publicPlatformConfig != null) {
return publicPlatformConfig;
} else {
return null;
}
}
/**
* JOB 执行任务
* 从微信接口中获取token和jsapiticket存放到缓存Redis中
*/
@PostMapping(value = "/save/token")
public void saveAccessTokenToRedis() {
List<PublicPlatformConfig> publicPlatformConfigList = iPublicPlatformConfigService.getPlatformInfos();
for (PublicPlatformConfig platformConfig : publicPlatformConfigList
) {
try {
// 调用微信提供的API接口获取access_token 并存在redis中
String accessToken = accessTokenService.insetWeChatAccessToken(platformConfig);
accessTokenService.addJsApiTicket(accessToken, platformConfig);
} catch (Exception e) {
LOGGER.info(e + "");
}
}
}
/**
* 获取token
* @param publicPlatformConfig
* @return
*/
@PostMapping("/get/weChatToken")
public String getWeChatAccessToken(PublicPlatformConfig publicPlatformConfig) {
return accessTokenService.getAccessToken(publicPlatformConfig);
}
/**
* 生成新的accessToken存在redis中
*
* @param publicPlatformConfig 配置类
* @return String
* @Date 2018年7月23日16:28:54
* @author lilingye
*/
public String getAccessToken(PublicPlatformConfig publicPlatformConfig) {
Date nowDate = new Date();
WTokenVO wTokenVO = new WTokenVO();
wTokenVO.setAppid(publicPlatformConfig.getAppId());
wTokenVO.setCreateTime(nowDate);
wTokenVO.setAccessToken(publicPlatformConfig.getAgentId());
// 调用微信接口获取token 并存在redis中
String access_token = iUserInfoService.getAccessToken(publicPlatformConfig);
LOGGER.info("appid的值是" + publicPlatformConfig.getAppId());
LOGGER.info("secret值是" + publicPlatformConfig.getSecret());
LOGGER.info("type值是" + publicPlatformConfig.getType());
LOGGER.info("生成的access_token的值:" + access_token);
String redisKey = null;
if ("0".equals(publicPlatformConfig.getType())) {
redisKey = (publicPlatformConfig.getAppId() + publicPlatformConfig.getAgentId()).trim();
} else {
redisKey = publicPlatformConfig.getAppId();
}
if (!"null".equals(access_token) && null != access_token && !"".equals(access_token)) {
wTokenVO.setAccessToken(access_token);
redisCache.hset(redisKey, redisKey, JSON.toJSONString(wTokenVO), 3600);
return access_token;
} else {
return access_token;
}
}
/**
* @return
*/
@PostMapping(value = "/update/user")
public boolean updateUserInWechat(@RequestBody TrAccountUserinfo trAccountUserinfo
) {
// 获取id
RequestContext context = ContextHolder.get();
trAccountUserinfo.setCompanyId(context.getSiteId());
LOGGER.info("=====================================================================");
LOGGER.info("公司id" + context.getSiteId());
LOGGER.info("=====================================================================");
LOGGER.info("更新siteId");
return iTrAccountUserinfoService.updateById(trAccountUserinfo);
}
/**
* 获取企业用户信息
*
* @param accessToken
* @param wechatUserId
* @return 用户详细信息
* @date 2018-8-22 10:05:41
*/
@GetMapping(value = "/get/getWechatUser")
public WeChatUserVO getWechatUser(@RequestParam(name = "accessToken") String accessToken,
@RequestParam(name = "wechatUserId") String wechatUserId) {
LOGGER.info("参数accessToken:" + accessToken + ";wechatUserId是:" + wechatUserId);
WeChatUserVO weChatUserVO = new WeChatUserVO();
// 获取企业微信的微信的信息
WUserInfoVO wUserInfoVO = cwechatService.getCwechatUserDetail(accessToken, wechatUserId);
Long orgId = null;
LOGGER.info("拿到的企业部门id:" + wUserInfoVO.getDepartmentId());
if (!"".equals(wUserInfoVO.getDepartmentId())) {
orgId = Long.valueOf(wUserInfoVO.getDepartmentId());
// 获取目前组织的名称列表
List<String> orgNameList = cwechatService.getCwechatOrg(accessToken, orgId);
weChatUserVO.setOrgNames(orgNameList);
AccountVO accountVO = new AccountVO();
accountVO.setName(wUserInfoVO.getWechatuserid());
accountVO.setEmail(wUserInfoVO.getEmail());
accountVO.setMobile(wUserInfoVO.getMobile());
accountVO.setPosition(wUserInfoVO.getPosition());
accountVO.setSex(wUserInfoVO.getSex() == 1 ? "M" : "F");
accountVO.setHeadPortrait(wUserInfoVO.getHeadimgurl());
accountVO.setFullName(wUserInfoVO.getNickname());
accountVO.setTelephone(wUserInfoVO.getTelephone());
accountVO.setWechat(wechatUserId);
weChatUserVO.setAccountVO(accountVO);
if (CollectionUtils.isNotEmpty(orgNameList)) {
LOGGER.info("获取组织列表返回正常!");
return weChatUserVO;
} else {
LOGGER.info("获取组织列表返回异常!");
return null;
}
} else {
LOGGER.info("获取组织列表返回异常!");
return null;
}
}
/**
* 根据 wechatIds 获取用户微信用信息
* @param weChatIds
* @return
*/
@PostMapping(value = "/get/userInfo/wechatIds")
public Map<String, UserInfo> getWeChatUserInfoList(@RequestBody List<String> weChatIds) {
UserInfo userInfo = new UserInfo();
userInfo.setIsDeleted(Constants.NO_FLAG);
EntityWrapper<UserInfo> condition = QueryUtil.condition(userInfo);
condition.in("wechatuserid", weChatIds);
try {
List<UserInfo> trAccountUserInfoList = iUserInfoService.selectList(condition);
if (CollectionUtils.isEmpty(trAccountUserInfoList)) {
return null;
}
Map<String, UserInfo> userInfoMap = trAccountUserInfoList.stream()
.collect(Collectors.toMap(a -> a.getWechatuserid(), a -> a));
return userInfoMap;
} catch (Exception e) {
LOGGER.info("异常信息:{}",e.getMessage());
return null;
}
}
}
package com.yizhi.application.controller;
import com.alibaba.fastjson.JSON;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.application.domain.PublicPlatformConfig;
import com.yizhi.application.domain.TrAccountUserinfo;
import com.yizhi.application.domain.UserInfo;
import com.yizhi.application.orm.util.QueryUtil;
import com.yizhi.application.service.IAccessTokenService;
import com.yizhi.application.service.IPublicPlatformConfigService;
import com.yizhi.application.service.ITrAccountUserinfoService;
import com.yizhi.application.service.IUserInfoService;
import com.yizhi.system.application.vo.domain.Account;
import com.yizhi.system.application.system.remote.AccountClient;
import com.yizhi.system.application.system.remote.LoginLogClient;
import com.yizhi.system.application.system.remote.SiteClient;
import com.yizhi.application.task.UpdateUserInfoService;
import com.yizhi.util.application.constant.ReturnCode;
import com.yizhi.system.application.vo.AccountVO;
import com.yizhi.wechat.application.vo.wechat.Constants;
import com.yizhi.system.application.vo.LoginLogAddReqVO;
import com.yizhi.system.application.vo.WeChatUserVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 获取微信token
*
* @author lingye
* @date 2020-2-10 17:02:14
*/
@RestController
@RequestMapping(value = "/wechat")
public class WeChatUserController {
public static final Logger LOGGER = LoggerFactory.getLogger(WeChatUserController.class);
@Autowired
private SiteClient siteClient;
@Autowired
private AccountClient accountClient;
@Autowired
private ITrAccountUserinfoService iTrAccountUserinfoService;
@Autowired
private UserInfoController userInfoController;
@Autowired
private IPublicPlatformConfigService iPublicPlatformConfigService;
@Autowired
private UpdateUserInfoService updateUserInfoService;
@Autowired
private LoginLogClient loginLogClient;
@Autowired
private IAccessTokenService accessTokenService;
@Autowired
private IUserInfoService userInfoService;
@GetMapping("/appid/accesstoken/get")
public String getWechatAccessTokenByAppId(@RequestParam("appId") String appId,
@RequestParam(value = "agentId",required = false) String agentId) {
PublicPlatformConfig config =iPublicPlatformConfigService.getPubConfig(appId,agentId);
return accessTokenService.getAccessToken(config);
}
@GetMapping(value = "/token")
public Map<String, Object> getWeChatUserInfoToken(@RequestParam(name = "weChatUserId", required = true) String weChatUserId,
@RequestParam(name = "appId", required = true) String appId,
@RequestParam(name = "agentId", required = false) String agentId
) {
RequestContext context = ContextHolder.get();
LOGGER.info("请求的上下文信息:{}", JSON.toJSON(context));
Map<String, Object> retMap = new HashMap<String, Object>(16);
retMap.put("returnCode", 1);
//获取企业的信息
Long siteId = context.getSiteId();
String siteCode = context.getSiteCode();
Long companyId = context.getCompanyId();
String companyCode = context.getCompanyCode();
PublicPlatformConfig platformConfig = null;
List<PublicPlatformConfig> pubConfigs = iPublicPlatformConfigService.getPubConfigs(appId, agentId);
LOGGER.info("公众号配置所有列表:{}", JSON.toJSON(pubConfigs));
if (pubConfigs == null) {
retMap.put("returnCode", 2);
return retMap;
}
for (PublicPlatformConfig config : pubConfigs) {
if (companyCode.equals(config.getCompanyCode()) && siteCode.equals(config.getSiteCode())) {
platformConfig = config;
break;
}
}
if (platformConfig == null) {
// 公众号配置的站点和链接的站点不匹配
retMap.put("returnCode", 2);
retMap.put("msg","配置链接的公司站点编码和微信公众号配置的不一致!");
return retMap;
}
LOGGER.info("公众号配置:{}", JSON.toJSON(platformConfig));
TrAccountUserinfo trAccountUserinfo = userInfoController.queryUserInWechat(weChatUserId, companyId);
// 如果是光大证券的特殊要命需求:
// 1. 没有找到 就去system用户表里面找
// 1.1 先查询当前企业用户的信息
if (companyCode.equals("ebscn")) {
if (StringUtils.isNotEmpty(platformConfig.getAgentId())) {
String accessToken = userInfoController.getWeChatAccessToken(platformConfig);
// 查询用户的信息
com.yizhi.wechat.application.vo.wechat.WeChatUserVO weChatUserVO = userInfoController.getWechatUser(accessToken, weChatUserId);
LOGGER.info("-----------------------------------------------------");
LOGGER.info("-----------------------------------------------------");
LOGGER.info(" 测试光大用,后期删除: weChatUserVO:{}", JSON.toJSONString(weChatUserVO));
LOGGER.info("-----------------------------------------------------");
LOGGER.info("-----------------------------------------------------");
if (weChatUserVO == null) {
retMap.put("returnCode", 2);
retMap.put("msg","请求企业微信中用户信息失败");
return retMap;
}
ResponseEntity<Account> accountResponseEntity =
accountClient.searchByConditionWithPriority(companyId, weChatUserId,
weChatUserVO.getAccountVO().getMobile(), weChatUserVO.getAccountVO().getEmail());
Account account = accountResponseEntity.getBody();
// 没有找到 提示报错
if (account == null) {
retMap.put("returnCode", 10);
return retMap;
} else {
bindCompanyWeChatUser(weChatUserId, companyId, siteId, account.getId(), 1);
AccountVO accountVO = new AccountVO();
BeanUtils.copyProperties(account, accountVO);
retMap.put("userInfo", accountVO);
return retMap;
}
}
retMap.put("returnCode", 2);
retMap.put("msg","微信配置agentId为空");
return retMap;
}
if (null != trAccountUserinfo) {
// 异步更新用户信息、部门信息
updateUserInfoService.taskUpdateUserInfo(platformConfig, trAccountUserinfo);
AccountVO accountVO = accountClient.findById(trAccountUserinfo.getAccountId());
Map<String, Object> stringObjectMap = checkUser(accountVO);
if (!stringObjectMap.isEmpty()){
return stringObjectMap;
}
LOGGER.info("当前用户的信息accountVO:{}", accountVO);
if (!getSiteAuthorize(accountVO.getId(), siteId, companyId, companyCode)) {
// 没有站点访问权限
LOGGER.info("没有访问权限!");
retMap.put("returnCode", 0);
return retMap;
}
retMap.put("userInfo", accountVO);
addUserLoginLog(companyId, siteId, accountVO, Constants.THREE);
return retMap;
} else {
LOGGER.info("不存在账号");
LOGGER.info("公众号配置:{}", platformConfig);
LOGGER.info("判断:{}", platformConfig.getIsAddedUser() == 1 ? true : false);
AccountVO accountVO = null;
if (Constants.ZERO.equals(platformConfig.getType()) && platformConfig.getIsAddedUser() == 1) {
LOGGER.info("当前的结果===");
accountVO = getCompanyWeChatUser(siteId, companyId, siteCode, weChatUserId, platformConfig, context);
if (accountVO != null) {
retMap.put("userInfo", accountVO);
addUserLoginLog(companyId, siteId, accountVO, Constants.THREE);
}
}
if (Constants.TWO.equals(platformConfig.getType())) {
// 服务商接口
accountVO = getProviderUser(siteId,companyId,weChatUserId,context);
retMap.put("userInfo", accountVO);
addUserLoginLog(companyId, siteId, accountVO, Constants.FIVE);
}
return retMap;
}
}
private static Map<String, Object> checkUser(AccountVO accountVO) {
Map<String, Object> retMap = new HashMap<String, Object>(16);
if (!accountVO.getEnabled() || accountVO.getLocked()) {
retMap.put("returnCode", 2);
retMap.put("msg", ReturnCode.ACCOUNT_CLOSE.getMsg());
// 前面时间大于后面时间==1
} else if (accountVO.getExpiredType() == 2 && accountVO.getEndTime().compareTo(new Date()) <= 0) {
retMap.put("returnCode", 2);
retMap.put("msg", ReturnCode.ACCOUNT_INVALID.getMsg());
} else if (accountVO.getExpiredType() == 3 && accountVO.getExpiredTime().compareTo(new Date()) <= 0) {
retMap.put("returnCode", 2);
retMap.put("msg", ReturnCode.ACCOUNT_INVALID.getMsg());
}
return retMap;
}
/**
* 企业微信新增
*
* @param siteId
* @param companyId
* @param siteCode
* @param weChatUserId
* @param publicPlatformConfig
* @return
*/
public AccountVO getCompanyWeChatUser(
Long siteId, Long companyId, String siteCode, String weChatUserId, PublicPlatformConfig publicPlatformConfig
, RequestContext context) {
LOGGER.info("添加用户上下参数:{}", JSON.toJSON(context));
String companyCode = context.getCompanyCode();
try {
AccountVO userInfo = accountClient.findUser(weChatUserId, companyId);
// 判断用户是否存在
if (null != userInfo) {
LOGGER.info("存在同名的用户。");
bindCompanyWeChatUser(weChatUserId, companyId, siteId, userInfo.getId(),0);
return userInfo;
} else {
String accessToken = accessTokenService.getAccessToken(publicPlatformConfig);
LOGGER.info("获取微信用户信息token:{}", accessToken);
com.yizhi.wechat.application.vo.wechat.WeChatUserVO weChatUser = userInfoController.getWechatUser(accessToken, weChatUserId);
if (weChatUser == null) {
return null;
}
weChatUser.setContext(context);
WeChatUserVO weChatUserVO = new WeChatUserVO();
BeanUtils.copyProperties(weChatUser,weChatUserVO);
// 深度复制
com.yizhi.wechat.application.vo.wechat.AccountVO accountVOTemp = weChatUser.getAccountVO();
com.yizhi.system.application.vo.AccountVO accountVOTemp1 = new AccountVO();
BeanUtils.copyProperties(accountVOTemp,accountVOTemp1 );
weChatUserVO.setAccountVO(accountVOTemp1);
LOGGER.info("获取的用户微信信息{}", JSON.toJSON(weChatUser));
LOGGER.info("获取的用户微信信息,负责的信息 = {}", JSON.toJSON(weChatUserVO));
Account account = null;
try {
account = accountClient.saveUser(weChatUserVO);
LOGGER.info("添加后的用户信息:{}", JSON.toJSON(account));
} catch (Exception e) {
LOGGER.info("保存异常:{}", JSON.toJSONString(e));
}
// 绑定微信号
bindCompanyWeChatUser(weChatUserId, companyId, siteId, account.getId(),0);
AccountVO accountVO = new AccountVO();
BeanUtils.copyProperties(account, accountVO);
// 生成站点访问权限
Boolean resultFlag = siteClient.relateAccountSite(siteId, account.getId(), companyCode);
LOGGER.info("访问权限生成:" + resultFlag);
return accountVO;
}
} catch (Exception e) {
LOGGER.info("返回异常:{}", JSON.toJSONString(e));
return null;
}
}
public AccountVO getProviderUser(
Long siteId, Long companyId, String weChatUserId, RequestContext context) {
LOGGER.info("添加用户上下参数:{}", JSON.toJSON(context));
String companyCode = context.getCompanyCode();
try {
WeChatUserVO weChatUser = new WeChatUserVO();
UserInfo userInfo = new UserInfo();
userInfo.setWechatuserid(weChatUserId);
userInfo.setIsDeleted(0);
userInfo = userInfoService.selectOne(QueryUtil.condition(userInfo));
AccountVO accountVO = new AccountVO();
accountVO.setName(userInfo.getNickname());
accountVO.setHeadPortrait(userInfo.getHeadimgurl());
accountVO.setName(weChatUserId);
accountVO.setEmail(userInfo.getEmail());
accountVO.setMobile(userInfo.getMobile());
accountVO.setFullName(userInfo.getNickname());
weChatUser.setAccountVO(accountVO);
weChatUser.setContext(context);
weChatUser.setCorpId(userInfo.getCorpId());
Account account = null;
try {
account = accountClient.saveProviderUser(weChatUser);
LOGGER.info("添加后的用户信息:{}", JSON.toJSON(account));
} catch (Exception e) {
LOGGER.info("保存异常:{}", e.getMessage());
}
if (account ==null){
LOGGER.info("新增用户失败");
}
// 绑定微信号
bindCompanyWeChatUser(weChatUserId, companyId, siteId, account.getId(),5);
BeanUtils.copyProperties(account,accountVO);
// 生成站点访问权限
Boolean resultFlag = siteClient.relateAccountSite(siteId, account.getId(), companyCode);
LOGGER.info("访问权限生成:" + resultFlag);
return accountVO;
} catch (Exception e) {
LOGGER.info("返回异常:{}", e.getMessage());
return null;
}
}
/**
* 绑定用户
*
* @param weChatUserId
* @param companyId
* @param siteId
* @param accountId
*/
@Transactional(rollbackFor = Exception.class)
public void bindCompanyWeChatUser(String weChatUserId, Long companyId, Long siteId, Long accountId,Integer type) {
TrAccountUserinfo trAccountUserInfo = new TrAccountUserinfo();
trAccountUserInfo.setWechatuserid(weChatUserId);
trAccountUserInfo.setAccountId(accountId);
trAccountUserInfo.setSiteId(siteId);
trAccountUserInfo.setCompanyId(companyId);
trAccountUserInfo.setType(type);
trAccountUserInfo.setCreateTime(new Date());
LOGGER.info("企业用户绑定的参数:{}", JSON.toJSON(trAccountUserInfo));
boolean bindUser = iTrAccountUserinfoService.insert(trAccountUserInfo);
LOGGER.info("绑定企业号:{}", bindUser);
}
/**
* 判断站点是否有权
*
* @param siteId
* @return
*/
public Boolean getSiteAuthorize(Long accountId, Long siteId, Long companyId, String companyCode) {
LOGGER.info("判断权限接口:accountId:" + accountId + ",siteId:" + siteId + ",companyId:" + companyId);
try {
boolean accessToSite = siteClient.accessToSite(accountId, siteId, companyId, companyCode);
LOGGER.info("返回的站点权限1:{}", accessToSite);
if (accessToSite) {
return Boolean.TRUE;
}
accessToSite = siteClient.accessToSite(accountId, siteId, companyId, null);
LOGGER.info("返回的站点权限2:{}", accessToSite);
return accessToSite;
} catch (Exception e) {
LOGGER.info("调用system异常:{}", e.getMessage());
return false;
}
}
/**
* 用户登录统计
*
* @param companyId 公司id
* @param siteId 站点id
*/
public void addUserLoginLog(Long companyId, Long siteId, AccountVO accountVO, Integer type) {
LoginLogAddReqVO loginLogAddReqVO = new LoginLogAddReqVO();
loginLogAddReqVO.setCompanyId(companyId);
loginLogAddReqVO.setSiteId(siteId);
loginLogAddReqVO.setType(type);
loginLogAddReqVO.setAccountId(accountVO.getId());
loginLogAddReqVO.setOrgId(accountVO.getOrgId());
try {
loginLogClient.addLoginLog(loginLogAddReqVO);
} catch (Exception e) {
LOGGER.error("统计用户异常{}", e.getMessage());
}
}
}
package com.yizhi.application.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yizhi.application.aes.AesException;
import com.yizhi.application.aes.WXBizMsgCrypt;
import com.yizhi.core.application.cache.RedisCache;
import com.yizhi.application.domain.PublicPlatformConfig;
import com.yizhi.application.domain.SuiteTicket;
import com.yizhi.application.service.IPublicPlatformConfigService;
import com.yizhi.application.service.ISuiteTicketService;
import com.yizhi.wechat.application.utils.ElementUtils;
import com.yizhi.wechat.application.utils.FormatUtils;
import com.yizhi.wechat.application.utils.OkHttpUtils;
import com.yizhi.wechat.application.vo.wechat.SuiteTicketVO;
import com.yizhi.wechat.application.vo.wechat.WechatProviderVO;
import io.swagger.annotations.Api;
import lombok.extern.log4j.Log4j2;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Iterator;
/**
* 服务商接口
*
* @author lingye
*/
@Api(tags = "微信供应商接口")
@RequestMapping("/provider")
@RestController
@Log4j2
public class WechatProviderController {
// public final static String TOKEN = "a30rw9jBPYAmdjoxqqWgWfrYqdHP";
// public final static String ENCODING_AESKEY = "TOAX0ShveDLbPGl4rZRdmFxemn7GXxxe0OO950bXvqz";
// public final static String CORP_ID = "ww3cf43133c5880598";
// public final static String SUITE_ID = "ww67f499ed2d11a2dc";
// public final static String TOKEN1 = "kFziYBcchlLFknse";
// public final static String ENCODING_AESKEY1 = "3uhcLd0Pmr53ObF3dAd4Bp9xhQDsWMieTcMKxdqKor3";
@Value("${provider.corp.encoding.aeskey}")
private String encodingAesKey;
@Value("${provider.corp.token}")
private String corpToken;
@Value("${provider.corpId}")
private String corpId;
@Value("${provider.suite.id}")
private String suiteId;
@Value("${provider.suite.token}")
private String suiteToken;
@Value("${provider.suite.encoding.aseKey}")
private String suiteEncodingAesKey;
// HttpClientUtils httpClientUtils = new HttpClientUtils();
@Autowired
RedisCache redisCache;
@Value("${wechat.provider.token}")
private String providerAccessTokenUrl;
@Value("${wechat.provider.suite.token}")
private String suiteTokenUrl;
@Autowired
private IPublicPlatformConfigService publicPlatformConfigService;
@Autowired
private ISuiteTicketService suiteTicketService;
/**
* 通用开发参数 -系统事件接收URL
*
* @param signature 签名
* @param timestamp 时间戳
* @param nonce 随机数
* @param echostr
* @return
* @throws AesException
*/
@RequestMapping(value = "/get", method = RequestMethod.GET)
public String checkToken(@RequestParam(name = "msg_signature") String signature,
@RequestParam(name = "timestamp") String timestamp,
@RequestParam(name = "nonce") String nonce,
@RequestParam(name = "echostr") String echostr
) throws AesException {
//token和encoding_aeskey就是上诉随机获取的值,corp_id是企业id,在企业微信管理页面点击: 我的企业,拉到最下方可以看到
WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(corpToken, encodingAesKey, corpId);
String sEchoStr = wxcpt.VerifyURL(signature, timestamp, nonce, echostr);
System.out.println("-----签名校验通过-----");
return sEchoStr;
}
/**
* 服务商应用的
*
* @param signature
* @param timestamp
* @param nonce
* @param echostr
* @return
* @throws AesException
*/
@RequestMapping(value = "/callback", method = RequestMethod.GET)
public String callBack(@RequestParam(name = "msg_signature") String signature,
@RequestParam(name = "timestamp") String timestamp,
@RequestParam(name = "nonce") String nonce,
@RequestParam(name = "echostr") String echostr
) throws AesException {
//token和encoding_aeskey就是上诉随机获取的值,corp_id是企业id,在企业微信管理页面点击: 我的企业,拉到最下方可以看到
WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(suiteToken, suiteEncodingAesKey, corpId);
String sEchoStr = wxcpt.VerifyURL(signature, timestamp, nonce, echostr);
System.out.println("-----签名校验通过-----");
return sEchoStr;
}
/**
* 应用接受消息的接口
*
* @param wechatProviderVO
* @return
* @throws Exception
*/
@PostMapping(value = "/handle", produces = {"application/xml;charset=UTF-8"})
public Object handlerMessage(@RequestBody WechatProviderVO wechatProviderVO) throws Exception {
WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(suiteToken, suiteEncodingAesKey, corpId);
String sReqData = FormatUtils.getReqData(wechatProviderVO.getMsg());
String signature = wechatProviderVO.getSignature();
String timestamp = wechatProviderVO.getTimestamp();
String nonce = wechatProviderVO.getNonce();
String sMsg = wxcpt.DecryptMsg(signature, timestamp, nonce, sReqData);
ElementUtils element = new ElementUtils(sMsg);
String msgType = element.get("MsgType");
String content = "";
switch (msgType) {
/**
* 事件类型处理
*/
case "event":
content = "触发事件";
break;
/**
* 文字消息处理:这里是将用户发送的消息原样返回
*/
case "text":
content = element.get("Content");
break;
default:
break;
}
String sRespData = FormatUtils.getTextRespData(content);
String sEncryptMsg = wxcpt.EncryptMsg(sRespData, timestamp, nonce);
return sEncryptMsg;
}
@GetMapping("/suitetoken")
public String getSuiteToken(@RequestParam(name = "suiteId") String suiteId) {
log.info("当前suite_id:{}",suiteId);
Object hget = redisCache.hget("st_" + suiteId, "st_" + suiteId);
log.info("返回的结果:{}",JSON.toJSON(hget));
String suiteAccessToken = null;
if (hget != null) {
suiteAccessToken = hget.toString();
log.info("token:{}", JSON.toJSON(hget));
return suiteAccessToken;
}
PublicPlatformConfig pubConfig = publicPlatformConfigService.getPubConfig(suiteId, null);
log.info("suite_token:{}",JSON.toJSON(pubConfig));
SuiteTicket suiteTicket = suiteTicketService.getSuiteTicketById(suiteId);
log.info("返回suiteTicket:{}", JSON.toJSON(suiteTicket));
HashMap<String, String> map = new HashMap<>();
map.put("suite_id", suiteId);
map.put("suite_secret", pubConfig.getSecret());
map.put("suite_ticket", suiteTicket.getSuiteTicket());
log.info("参数map:{}",JSON.toJSON(map));
HashMap<String, String> head = new HashMap<>();
head.put("Content-Type", "application/json");
String result = OkHttpUtils.doRequest2("https://qyapi.weixin.qq.com/cgi-bin/service/get_suite_token", head, JSON.toJSONString(map));
log.info("请求后的token:{}",result);
JSONObject suiteJson = JSON.parseObject(result);
suiteAccessToken = suiteJson.getString("suite_access_token");
log.info("suiteAccessToken:{}",suiteAccessToken);
redisCache.hset("st_" + suiteId, "st_" + suiteId, suiteAccessToken, 7200);
return suiteAccessToken;
}
/**
* suite_ticket 的接收
*
* @param suiteTicketVO
* @return
* @throws AesException
*/
@PostMapping(value = "/suite/receive", produces = {"application/xml;charset=UTF-8"})
public String suiteReceive(@RequestBody SuiteTicketVO suiteTicketVO) throws AesException {
log.info("参数:{}", JSON.toJSON(suiteTicketVO));
WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(suiteToken, suiteEncodingAesKey, suiteId);
String sReqData = FormatUtils.getReqData(suiteTicketVO.getInMsgEntity());
String msg_signature = suiteTicketVO.getMsg_signature();
String timestamp = suiteTicketVO.getTimestamp();
String nonce = suiteTicketVO.getNonce();
String sMsg = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, sReqData);
log.info("返回的结果:{}", sMsg);
SuiteTicket suiteTicket = new SuiteTicket();
SuiteTicket s = updateSuiteTicket(sMsg, suiteTicket);
if (s == null) {
return "fail";
}
suiteTicketService.saveOrUpdateSuiteTicket(suiteTicket);
return "success";
}
/**
* @param xmlResult
* @param suiteTicket
* @return
*/
private SuiteTicket updateSuiteTicket(String xmlResult, SuiteTicket suiteTicket) {
try {
Document document = DocumentHelper.parseText(xmlResult);
Element rootElement = document.getRootElement();
// 迭代xml字段节点
Iterator iter = rootElement.elementIterator();
// 获取节点
while (iter.hasNext()) {
Element elementOption = (Element) iter.next();
// 节点属性
String name = elementOption.getName();
// 节点元素
String text = elementOption.getText();
log.info("当前" + name + "的值:{}", text);
if (name.equals("SuiteId")) {
suiteTicket.setSuiteId(text);
} else if (name.equals("SuiteTicket")) {
suiteTicket.setSuiteTicket(text);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return suiteTicket;
}
}
package com.yizhi.application.domain;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.FieldFill;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
*
* </p>
*
* @author lilingye
* @since 2018-04-29
*/
@Data
@Api(tags = "PublicPlatformConfig", description = "")
@TableName("public_platform_config")
public class PublicPlatformConfig extends Model<PublicPlatformConfig> {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "唯一标识 主键")
private Long id;
@ApiModelProperty(value = "公众号名称")
private String name;
@ApiModelProperty(value = "公众号类型")
private String type;
@ApiModelProperty(value = "秘钥")
@TableField("app_id")
private String appId;
@ApiModelProperty(value = "秘钥(公众号服务APPsecret和企业服务CorpSecret)")
private String secret;
@ApiModelProperty(value = "企业应用的id")
@TableField("agent_id")
private String agentId;
@TableField(value = "create_time", fill = FieldFill.INSERT)
private Date createTime;
@ApiModelProperty(value = "0 不增加新用户, 1 增加新用户到系统")
@TableField("is_added_user")
private Integer isAddedUser;
@ApiModelProperty(value = "是否删除 0未删除 1已删除")
@TableField("is_deleted")
private Integer isDeleted;
@ApiModelProperty(value = "站点code")
@TableField("site_code")
private String siteCode;
@ApiModelProperty(value = "企业code")
@TableField("company_code")
private String companyCode;
@ApiModelProperty(value = "企业名称")
@TableField("company_name")
private String companyName;
@ApiModelProperty(value = "站点名称")
@TableField("site_name")
private String siteName;
@ApiModelProperty(value = "url")
@TableField("url")
private String url;
@ApiModelProperty(value = "是否绑定开放平台")
@TableField("open_platform_bind")
private Integer openPlateFormBind;
@ApiModelProperty(value = "开放品台名称")
private String openPlatformName;
@ApiModelProperty(value = "开放平台id")
private String openPlatformId;
@Override
protected Serializable pkVal() {
return this.id;
}
}
package com.yizhi.application.domain;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.FieldFill;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
* 第三方应用suite_ticket 表
* </p>
*
* @author lingye
* @since 2020-08-05
*/
@Data
@Api(tags = "SuiteTicket", description = "第三方应用suite_ticket 表")
@TableName("suite_ticket")
public class SuiteTicket extends Model<SuiteTicket> {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "主键")
private Long id;
@ApiModelProperty(value = "suite_id")
@TableField("suite_id")
private String suiteId;
@ApiModelProperty(value = "suiteticket")
@TableField("suite_ticket")
private String suiteTicket;
@ApiModelProperty(value = "创建时间")
@TableField(value = "create_time", fill = FieldFill.INSERT)
private Date createTime;
@ApiModelProperty(value = "更新时间")
@TableField(value = "update_time", fill = FieldFill.INSERT)
private Date updateTime;
@ApiModelProperty(value = "删除标记 1删除 0 未删除")
private Integer deleted;
@Override
protected Serializable pkVal() {
return this.id;
}
}
package com.yizhi.application.domain;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.FieldFill;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
*
* </p>
*
* @author lilingye
* @since 2018-04-29
*/
@Data
@Api(tags = "TrAccountUserinfo", description = "")
@TableName("tr_account_userinfo")
public class TrAccountUserinfo extends Model<TrAccountUserinfo> {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "主键 唯一标识")
private Long id;
@ApiModelProperty(value = "用户id")
@TableField("account_id")
private Long accountId;
@ApiModelProperty(value = "微信公众号服务id")
private String wechatuserid;
@ApiModelProperty(value = "站点Id")
@TableField("site_id")
private Long siteId;
@ApiModelProperty(value = "企业id")
@TableField("company_id")
private Long companyId;
@ApiModelProperty(value = "用类型 0 普通微信公众号用户 1企业微信服务号用户")
private Integer type;
@TableField(value = "create_time", fill = FieldFill.INSERT)
private Date createTime;
@ApiModelProperty(value = "是否删除 0 未删除 1删除")
@TableField("is_deleted")
private Integer isDeleted;
@TableField(value = "update_time", fill = FieldFill.UPDATE)
private Date updateTime;
@ApiModelProperty(value = "更新人的id")
@TableField("update_by_id")
private Long updateById;
@ApiModelProperty(value = "创建人id")
@TableField("create_by_id")
private Long createById;
@TableField(value = "union_id")
private String unionId;
@Override
protected Serializable pkVal() {
return this.id;
}
}
package com.yizhi.application.domain;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.FieldFill;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
* 用户信息表
* </p>
*
* @author lilingye
* @since 2018-08-20
*/
@Data
@Api(tags = "UserInfo", description = "用户信息表")
@TableName("user_info")
public class UserInfo extends Model<UserInfo> {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "表唯一标识id")
private Long id;
@ApiModelProperty(value = "用户的唯一标识")
private String wechatuserid;
@ApiModelProperty(value = "用户昵称")
private String nickname;
@ApiModelProperty(value = "性别。0表示未定义,1表示男性,2表示女性")
private Integer sex;
@ApiModelProperty(value = "省份")
private String province;
@ApiModelProperty(value = "城市")
private String city;
@ApiModelProperty(value = "国家")
private String country;
@ApiModelProperty(value = "用户头像")
private String headimgurl;
@ApiModelProperty(value = "用户特权信息,json 数组,如微信沃卡用户为(chinaunicom)")
private String privilege;
@ApiModelProperty(value = "只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。")
@TableField(value = "union_id")
private String unionId;
@ApiModelProperty(value = "企业成员手机号,仅在用户同意snsapi_privateinfo授权时返回")
private String mobile;
@ApiModelProperty(value = "企业成员邮箱")
private String email;
@ApiModelProperty(value = "电话号码")
private String telephone;
@ApiModelProperty(value = "英文名称")
@TableField("english_name")
private String englishName;
@ApiModelProperty(value = "职位")
private String position;
@ApiModelProperty(value = "企业 员工个人二维码,扫描可添加为外部联系人")
@TableField(value = "qr_code")
private String qrCode;
@ApiModelProperty(value = "1 普通微信用户 0企业微信用户")
@TableField("user_type")
private Integer userType;
@ApiModelProperty(value = "创建时间")
@TableField(value = "create_time", fill = FieldFill.INSERT)
private Date createTime;
@ApiModelProperty(value = "0有效,1删除")
@TableField("is_deleted")
private Integer isDeleted;
@ApiModelProperty(value = "第三方应用id")
@TableField(value = "corp_id",exist = false)
private String corpId;
@ApiModelProperty(value = "企业 员工个人二维码,扫描可添加为外部联系人")
@TableField(value = "user_id",exist = false)
private String userId;
@ApiModelProperty(value = "安装应用的设备Id")
@TableField(value = "device_id",exist = false)
private String deviceId;
@Override
protected Serializable pkVal() {
return this.id;
}
}
package com.yizhi.application.feign;
import com.alibaba.fastjson.JSONObject;
import com.yizhi.wechat.application.vo.wechat.WechatParamVO;
import feign.Headers;
import feign.Param;
import feign.RequestLine;
import org.springframework.stereotype.Service;
/**
* 获取企业微信用户信息
*
* @author lilingye
* @since 2018-5-3 19:17:41
*/
@Headers("Content-Type: application/json")
@Service("cWeChatClient")
public interface CWeChatClient {
/**
* 通过code获取token
*
* @param secret
* @return
*/
@RequestLine("GET /cgi-bin/gettoken?corpsecret={secret}&corpid={corpid}")
JSONObject getWechatToken(@Param("secret") String secret, @Param("corpid") String corpid);
/**
* #根据code和AccessToken获取用户信息
*
* @param access_token
* @param code
* @return
*/
@RequestLine("GET /cgi-bin/user/getuserinfo?access_token={access_token}&code={code}")
JSONObject getUserInfo(@Param("access_token") String access_token, @Param("code") String code);
/**
* 获取用户的详细信息
*
* @param wechatParamVO user_ticket信息
* @return
*/
@RequestLine("POST /cgi-bin/user/getuserdetail?access_token={access_token}")
JSONObject getUserDetail(@Param("access_token") String access_token, WechatParamVO wechatParamVO);
/**
* 获取ticket
*
* @param access_token
* @return
*/
@RequestLine("GET /cgi-bin/get_jsapi_ticket?access_token={access_token}")
JSONObject getTicket(@Param("access_token") String access_token);
/**
* 获取企业用户信息包括当前部门的id
*
* @param accessToken ACCESSTOKEN
* @param userId 用户userId
* @return 用户详细信息
*/
@RequestLine("GET /cgi-bin/user/get?access_token={accessToken}&userid={userId}")
JSONObject getCWechatUserDetail(@Param("accessToken") String accessToken, @Param("userId") String userId);
/**
* 获取企业服务号部门列表
*
* @param accessToken
* @param id 部门id
* @return 列表
*/
@RequestLine("GET /cgi-bin/department/list?access_token={accessToken}&id={id}")
JSONObject getCwechatDepartmentList(@Param("accessToken") String accessToken, @Param("id") Long id);
}
package com.yizhi.application.feign;
import com.netflix.hystrix.HystrixCommandProperties;
import feign.hystrix.HystrixFeign;
import feign.hystrix.SetterFactory;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author lililingye
*/
@Slf4j
@Configuration
public class CWeChatConfig {
@Value("${cloud.company.wechat.base_url}")
private String baseUrl;
private String accessTimeOutMillis = "1000";
@Bean
CWeChatClient cWeChatClient() throws InterruptedException {
try {
Integer.parseInt(accessTimeOutMillis);
return HystrixFeign.builder()
.decoder(new JacksonDecoder())
.encoder(new JacksonEncoder())
.setterFactory((target, method) ->
new SetterFactory.Default().create(target, method).
andCommandPropertiesDefaults(HystrixCommandProperties.defaultSetter().
withExecutionTimeoutInMilliseconds(Integer.parseInt(accessTimeOutMillis))))
.target(CWeChatClient.class, this.baseUrl);
} catch (Exception e) {
return HystrixFeign.builder()
.decoder(new JacksonDecoder())
.encoder(new JacksonEncoder())
.setterFactory((target, method) ->
new SetterFactory.Default().create(target, method).
andCommandPropertiesDefaults(HystrixCommandProperties.defaultSetter().
withExecutionTimeoutInMilliseconds(10000)))
.target(CWeChatClient.class, this.baseUrl);
}
}
}
package com.yizhi.application.feign;
import com.alibaba.fastjson.JSONObject;
import feign.Headers;
import feign.Param;
import feign.RequestLine;
import org.springframework.stereotype.Service;
@Headers("Content-Type: application/json")
@Service("weChatClient")
public interface WeChatClient {
// /**
// * 获取code
// * @param appid
// * @param redirect_uri
// * @param scope
// * @return
// */
// @RequestLine("GET /get")
// String getCode(@Param("appid") String appid,@Param("redirecct_uri") String redirect_uri,
// @Param("scope") String scope);
/**
* 获取token
*
* @param appid 公众号的唯一标识
* @param secret 公众号的appsecret
* @param code
* @return
*/
@RequestLine("GET /sns/oauth2/access_token?appid={appid}&secret={secret}&code={code}&grant_type=authorization_code")
JSONObject getWechaToken(@Param("appid") String appid,
@Param("secret") String secret,
@Param("code") String code);
/**
* 刷新token
*
* @param appid 公众号的唯一标识
* @param refresh_token 填写通过access_token获取到的refresh_token参数
* @return
*/
@RequestLine("GET /sns/oauth2/refresh_token?appid={appid}&grant_type=refresh_token&refresh_token={refresh_token}")
JSONObject refreshToken(@Param("appid") String appid,
@Param("refresh_token") String refresh_token);
/**
* 获取用户详情
*
* @param accessToken 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
* @param openid 用户唯一标识
* @return
*/
@RequestLine("GET /sns/userinfo?access_token={accessToken}&openid={openid}&lang=zh_CN")
JSONObject getUserInfo(@Param("accessToken") String accessToken,
@Param("openid") String openid);
/**
* 微信公众号获取jsapi_ticket
*
* @param accessToken Token 值
* @return
*/
@RequestLine("GET /cgi-bin/ticket/getticket?access_token={accessToken}&type=jsapi")
JSONObject getTicket(@Param("accessToken") String accessToken);
/**
* 获取accessToken
*
* @param appid
* @param secret
* @return
*/
@RequestLine("GET /cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}")
JSONObject getAccessToken(@Param("appid") String appid, @Param("secret") String secret);
@RequestLine("GET /cgi-bin/get_current_selfmenu_info?access_token={accessToken}")
JSONObject getMenuInfo(@Param("accessToken") String accessToken);
}
package com.yizhi.application.feign;
import com.netflix.hystrix.HystrixCommandProperties;
import feign.hystrix.HystrixFeign;
import feign.hystrix.SetterFactory;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Slf4j
@Configuration
public class WeChatConfig {
@Value("${cloud.wechat.base_url}")
private String baseUrl;
private String accessTimeOutMillis = "1000";
@Bean
WeChatClient weChatClient() throws InterruptedException {
try {
Integer.parseInt(accessTimeOutMillis);
return HystrixFeign.builder()
.decoder(new JacksonDecoder())
.encoder(new JacksonEncoder())
.setterFactory((target, method) ->
new SetterFactory.Default().create(target, method).
andCommandPropertiesDefaults(HystrixCommandProperties.defaultSetter().
withExecutionTimeoutInMilliseconds(Integer.parseInt(accessTimeOutMillis))))
.target(WeChatClient.class, this.baseUrl);
} catch (Exception e) {
return HystrixFeign.builder()
.decoder(new JacksonDecoder())
.encoder(new JacksonEncoder())
.setterFactory((target, method) ->
new SetterFactory.Default().create(target, method).
andCommandPropertiesDefaults(HystrixCommandProperties.defaultSetter().
withExecutionTimeoutInMilliseconds(10000)))
.target(WeChatClient.class, this.baseUrl);
}
}
}
package com.yizhi.application.mapper;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.yizhi.application.domain.PublicPlatformConfig;
/**
* <p>
* Mapper 接口
* </p>
*
* @author lilingye
* @since 2018-04-29
*/
public interface PublicPlatformConfigMapper extends BaseMapper<PublicPlatformConfig> {
}
package com.yizhi.application.mapper;
import com.yizhi.application.domain.SuiteTicket;
import com.baomidou.mybatisplus.mapper.BaseMapper;
/**
* <p>
* 第三方应用suite_ticket 表 Mapper 接口
* </p>
*
* @author lingye
* @since 2020-08-05
*/
public interface SuiteTicketMapper extends BaseMapper<SuiteTicket> {
}
package com.yizhi.application.mapper;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.yizhi.application.domain.TrAccountUserinfo;
/**
* <p>
* Mapper 接口
* </p>
*
* @author lilingye
* @since 2018-04-29
*/
public interface TrAccountUserinfoMapper extends BaseMapper<TrAccountUserinfo> {
}
package com.yizhi.application.mapper;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.yizhi.application.domain.UserInfo;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
/**
* <p>
* Mapper 接口
* </p>
*
* @author lilingye
* @since 2018-04-29
*/
public interface UserInfoMapper extends BaseMapper<UserInfo> {
/**
* 修改用户头像和昵称根据wechatUserId
*
* @param nickname
* @param headImgUrl
* @param wechatUserId
* @return
*/
@Update("UPDATE user_info SET nickname =#{nickname} ,headimgurl = #{headImgUrl} WHERE wechatuserid=#{wechatUserId}")
boolean updateUserInfoByWeChatId(
@Param("nickname") String nickname,
@Param("headImgUrl") String headImgUrl,
@Param("wechatUserId") String wechatUserId
);
}
package com.yizhi.application.service;
import com.yizhi.application.domain.PublicPlatformConfig;
/**
* <p>
* 服务类
* </p>
*
* @author lilingye
* @since 2020-2-12
*/
public interface IAccessTokenService {
/**
* 获取token
* @param publicPlatformConfig
* @return
*/
String getAccessToken(PublicPlatformConfig publicPlatformConfig);
/**
* 生成accessToken 签名使用
* @param publicPlatformConfig
* @return
*/
String insetWeChatAccessToken(PublicPlatformConfig publicPlatformConfig);
/**
* 获取jsApiTicket
* @param access_token ACCESSTOKEN
* @param publicPlatformConfig 配置信息
* @return
*/
String addJsApiTicket(String access_token,PublicPlatformConfig publicPlatformConfig);
}
package com.yizhi.application.service;
import com.yizhi.wechat.application.vo.wechat.WUserInfoVO;
import java.util.List;
/**
* @author lilingye
* @date 2018-8-20 13:36:15
*/
public interface ICwechatService {
/**
* 获取企业拼接额字符串
*
* @param accessToken
* @param cOrgId
* @return
*/
List<String> getCwechatOrg(String accessToken, Long cOrgId);
/**
* 获取企业用户详情
*
* @return
*/
WUserInfoVO getCwechatUserDetail(String accessToken, String userId);
}
package com.yizhi.application.service;
import com.yizhi.wechat.application.vo.wechat.WechatUserInfoVO;
/**
* <p>
* 第三方应用suite_ticket 表 服务类
* </p>
*
* @author lingye
* @since 2020-08-05
*/
public interface IProviderUserInfoService {
/**
* 获取用户的详情
* @param suiteId
* @param code
* @return
*/
WechatUserInfoVO getProviderInfoDetail(String suiteId,String code);
}
package com.yizhi.application.service;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.IService;
import com.yizhi.application.domain.PublicPlatformConfig;
import java.util.List;
/**
* <p>
* 服务类
* </p>
*
* @author lilingye
* @since 2018-04-29
*/
public interface IPublicPlatformConfigService extends IService<PublicPlatformConfig> {
/**
* 获取公众服务号实体
*
* @param appId 公众号的APPID
* @param agentId agentId
* @return
*/
PublicPlatformConfig getPubConfig(String appId, String agentId);
/**
* 获取配置列表
* @param appId
* @param agentId
* @return
*/
List<PublicPlatformConfig> getPubConfigs(String appId, String agentId);
/**
* 获取公众号配置列表
*
* @return
*/
List<PublicPlatformConfig> getPlatformInfos();
/**
* 插入信息
*
* @param publicPlatformConfig
* @return
*/
PublicPlatformConfig insertPublicPlatformConfigInfo(PublicPlatformConfig publicPlatformConfig);
/**
* 查询列表
*
* @param pageNo
* @param pageSize
* @param name
* @return
*/
Page<PublicPlatformConfig> findPublicConfigList(Integer pageNo, Integer pageSize, String name);
/**
* 获取实体
*
* @param publicPlatformConfig
* @return
*/
PublicPlatformConfig getPublicPlatformConfig(PublicPlatformConfig publicPlatformConfig);
/**
* 更具appid查询在➕的config
* @param appId 公众号APPID
* @return config
*/
PublicPlatformConfig getConfigByAppId(String appId);
}
package com.yizhi.application.service;
import com.yizhi.application.domain.SuiteTicket;
import com.baomidou.mybatisplus.service.IService;
/**
* <p>
* 第三方应用suite_ticket 表 服务类
* </p>
*
* @author lingye
* @since 2020-08-05
*/
public interface ISuiteTicketService extends IService<SuiteTicket> {
/**
* 保存/更新 suite_ticket
* @param suiteTicket
* @return
*/
Boolean saveOrUpdateSuiteTicket(SuiteTicket suiteTicket);
/**
* 获取suiteTicket
* @param suiteId
* @return
*/
SuiteTicket getSuiteTicketById(String suiteId);
}
package com.yizhi.application.service;
import com.baomidou.mybatisplus.service.IService;
import com.yizhi.application.domain.TrAccountUserinfo;
import com.yizhi.wechat.application.vo.wechat.TrAccountUserinfoVO;
/**
* <p>
* 服务类
* </p>
* @author lilingye
* @since 2018-04-29
*/
public interface ITrAccountUserinfoService extends IService<TrAccountUserinfo> {
/**
* 绑定用户和未木云系统账号
*
* @param trAccountUserinfoVO
* @return
*/
TrAccountUserinfoVO saveAccount(TrAccountUserinfoVO trAccountUserinfoVO);
/**
* 查询用户绑定未木云系统账号的状态
*
* @param openId 用户唯一标识
* @return
*/
TrAccountUserinfo queryAccount(String openId);
/**
* 查询用户是否在站点内
*
* @param openId
* @param companyId
* @return
*/
TrAccountUserinfo findAccount(String openId, Long companyId);
/**
* 判断用户是否存在绑定关系
* @param trAccountUserInfo
* @return
*/
TrAccountUserinfo findBindWechat(TrAccountUserinfo trAccountUserInfo);
/**
* 修改关联关系
*
* @param trAccountUserinfo
* @return
*/
boolean updateTrAccountUserInfo(TrAccountUserinfo trAccountUserinfo);
/**
* 解绑用户
* @param weChatUserId
* @return
*/
boolean unbindAccountByWeChatUserId(String weChatUserId);
/**
* 解绑用户
* @param accountId
* @return
*/
boolean updateUserInfo(Long accountId,String wechatUserId);
/**
* 自动解绑用户
* @param trAccountUserInfo
* @return
*/
boolean autoUnBindWeChatAccount(TrAccountUserinfo trAccountUserInfo);
}
package com.yizhi.application.service;
import com.alibaba.fastjson.JSONObject;
import com.yizhi.application.domain.PublicPlatformConfig;
import com.yizhi.application.domain.TrAccountUserinfo;
import com.yizhi.application.domain.UserInfo;
import com.baomidou.mybatisplus.service.IService;
import com.yizhi.wechat.application.vo.wechat.SignatureVO;
import com.yizhi.wechat.application.vo.wechat.WUserInfoVO;
import com.yizhi.wechat.application.vo.wechat.WechatUserInfoVO;
/**
* <p>
* 服务类
* </p>
*
* @author lilingye
* @since 2018-04-29
*/
public interface IUserInfoService extends IService<UserInfo> {
/**
* 查看微信用户是否在系统中存在
* @param wechatUserId
* @return
*/
TrAccountUserinfo getUserInVmCloud(String wechatUserId);
/**
* 用户通过微信登录后 新建关联关系
* @param wechatUserId
* @return
*/
TrAccountUserinfo saveUser(String wechatUserId, Long accountId);
/**
* 在微信公众号获取用户信息
* @param appid
* @param secret
* @return
*/
WechatUserInfoVO getWeChatUserInfo(String appid, String secret, String code, Integer source);
/**
*获取企业服务号的用户信息
* @param publicPlatformConfig 配置实体
* @return
*/
WechatUserInfoVO getCompanyWechatUserInfo(PublicPlatformConfig publicPlatformConfig, String code , Integer source);
/**
* 获取企业的ticket
* @param type 接口类型 0 是企业;1 是非企业
* @param url 当前网页的URL,不包含#及其后面部分
* @return
*/
SignatureVO getSignature(String access_token, String url, PublicPlatformConfig publicPlatformConfig);
/**
* 获取AccessToken
* @param publicPlatformConfig APPID
*
* @return
*/
String getAccessToken(PublicPlatformConfig publicPlatformConfig);
/**
* 获取jsApiTicket
* @param access_token ACCESSTOKEN
* @param publicPlatformConfig 配置信息
* @return
*/
String getJsApiTicket(String access_token,PublicPlatformConfig publicPlatformConfig);
/**
* 获取企业的用户信息
* @param userId
* @param publicPlatformConfig
* @return
*/
JSONObject getCwechatUserInfo(String userId,PublicPlatformConfig publicPlatformConfig);
/**
* 通过用户openId获取用户信息
* @param openId
* @return
*/
WUserInfoVO getWUserInfoVO(String openId);
/**
* 小程序添加用户到表中
* @param openId
*/
void saveMiniProgramUser(String openId,String unionId);
/**
* 修改用户信息
* @param userInfo
* @return flag
*/
Boolean updateUserInfo(UserInfo userInfo);
}
package com.yizhi.application.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yizhi.core.application.cache.RedisCache;
import com.yizhi.application.domain.PublicPlatformConfig;
import com.yizhi.application.feign.CWeChatClient;
import com.yizhi.application.feign.WeChatClient;
import com.yizhi.application.service.IAccessTokenService;
import com.yizhi.wechat.application.vo.wechat.Constants;
import com.yizhi.wechat.application.vo.wechat.WTicketVO;
import com.yizhi.wechat.application.vo.wechat.WTokenVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.Date;
/**
* <p>
* 服务实现类
* </p>
*
* @author lilingye
* @since token
*/
@Service
public class AccessTokenServiceImpl implements IAccessTokenService {
private static final Logger LOGGER = LoggerFactory.getLogger(AccessTokenServiceImpl.class);
@Autowired
private RedisCache redisCache;
@Autowired
private CWeChatClient cWeChatClient;
@Autowired
private WeChatClient weChatClient;
@Override
public String getAccessToken(PublicPlatformConfig publicPlatformConfig) {
String accessTokenKey = null;
if (Constants.ZERO.equals(publicPlatformConfig.getType())) {
accessTokenKey = (publicPlatformConfig.getAppId() + publicPlatformConfig.getAgentId()).trim();
} else {
accessTokenKey = publicPlatformConfig.getAppId().trim();
}
LOGGER.info("获取当前的accessTokenKey:{}", accessTokenKey);
//从缓存中获取token
Object tokenDetail = redisCache.hget(accessTokenKey, accessTokenKey);
if (null == tokenDetail) {
// 生成新的token
return insetWeChatAccessToken(publicPlatformConfig);
}
// 判断缓存中的redis存在
LOGGER.info("当前redis中存放accessToken详细信息:{}", tokenDetail);
JSONObject accessTokenDetail = JSONObject.parseObject(tokenDetail.toString());
String accessToken = accessTokenDetail.getString("accessToken");
if (StringUtils.isEmpty(accessToken) || accessToken.equals(Constants.nullStr)) {
//生成新的token
LOGGER.info("accessToken值不在在,重新获取");
return insetWeChatAccessToken(publicPlatformConfig);
}
LOGGER.info("accessToken值存在");
// 发现从redis中获取的token有过期现象,所以需要检验先=下token的正确性
JSONObject json = weChatClient.getMenuInfo(accessToken);
// token 过期
if (json.toString().contains("40001")) {
LOGGER.warn("accessToken值存在 过期,重新获取");
return insetWeChatAccessToken(publicPlatformConfig);
}
return accessToken;
}
@Override
public String insetWeChatAccessToken(PublicPlatformConfig publicPlatformConfig) {
// 调用微信接口获取token 并存在redis中
String accessToken = null;
// 根据公众号类型获取
if ((Constants.ZERO).equals(publicPlatformConfig.getType())) {
// 获取企业token
LOGGER.info("企业微信获取token参数:{}", "secret:" + publicPlatformConfig.getSecret().trim() + "--appId:" + publicPlatformConfig.getAppId().trim());
JSONObject accessTokenJson = cWeChatClient.getWechatToken(publicPlatformConfig.getSecret().trim(), publicPlatformConfig.getAppId().trim());
LOGGER.info("企业微信accessToken:{}", accessTokenJson);
accessToken = accessTokenJson.getString(Constants.ACCESS_TOKEN);
} else {
// 获取微信号token
JSONObject accessTokenJson = weChatClient.getAccessToken(publicPlatformConfig.getAppId(), publicPlatformConfig.getSecret());
LOGGER.info("微信公众号的accessToken:{}", accessTokenJson);
accessToken = accessTokenJson.getString(Constants.ACCESS_TOKEN);
}
String tokenKey = null;
if ((Constants.ZERO).equals(publicPlatformConfig.getType())) {
tokenKey = (publicPlatformConfig.getAppId() + publicPlatformConfig.getAgentId()).trim();
} else {
tokenKey = publicPlatformConfig.getAppId();
}
if (!Constants.nullStr.equals(accessToken) && null != accessToken && !"".equals(accessToken)) {
WTokenVO wTokenVO = new WTokenVO();
wTokenVO.setAppid(publicPlatformConfig.getAppId());
wTokenVO.setCreateTime(new Date());
wTokenVO.setAccessToken(publicPlatformConfig.getAgentId());
wTokenVO.setAccessToken(accessToken);
redisCache.hset(tokenKey, tokenKey, JSON.toJSONString(wTokenVO), 3600);
return accessToken;
} else {
return accessToken;
}
}
/**
* 定时任务生成jsApiTicket
*
* @param publicPlatformConfig
* @return
*/
@Override
public String addJsApiTicket(String accessToken, PublicPlatformConfig publicPlatformConfig) {
String ticketKey = "jsapiticket_" + (publicPlatformConfig.getAppId() + publicPlatformConfig.getAgentId()).trim();
LOGGER.info("ticketKey的值是:" + ticketKey);
String ticket = null;
WTicketVO wTicketVO = new WTicketVO();
wTicketVO.setAppid(publicPlatformConfig.getAppId());
wTicketVO.setAgentId(publicPlatformConfig.getAgentId());
wTicketVO.setCreateTime(new Date());
// 企业号的类型
String type = publicPlatformConfig.getType();
// 企业服务号
if (Constants.ZERO.equals(type)) {
JSONObject jsApiTicketDetail = cWeChatClient.getTicket(accessToken);
LOGGER.info("生产的jsApiTicket的详情:{}", jsApiTicketDetail);
ticket = jsApiTicketDetail.getString("ticket");
LOGGER.info("新生成jsapticket是:" + ticket);
wTicketVO.setTicket(ticket);
redisCache.hset(ticketKey, ticketKey, JSON.toJSONString(wTicketVO), Constants.REDIS_INVALID_TIME);
} else {
// 微信公众号
JSONObject jsApiTicketDetail = weChatClient.getTicket(accessToken);
LOGGER.info("生产的jsApiTicket的详情:{}", jsApiTicketDetail);
ticket = jsApiTicketDetail.getString("ticket");
LOGGER.info("重新生成jsapTicket是:" + ticket);
wTicketVO.setTicket(ticket);
redisCache.hset(ticketKey, ticketKey, JSON.toJSONString(wTicketVO), Constants.REDIS_INVALID_TIME);
}
return ticket;
}
}
package com.yizhi.application.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yizhi.application.feign.CWeChatClient;
import com.yizhi.application.service.ICwechatService;
import com.yizhi.application.service.IUserInfoService;
import com.yizhi.wechat.application.vo.wechat.Constants;
import com.yizhi.wechat.application.vo.wechat.WUserInfoVO;
import com.yizhi.wechat.application.vo.wechat.WechatOrg;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author lilingye
* @date 2018-8-17 14:19:09
*/
@Log4j2
@Service
public class CwechatServiceImpl implements ICwechatService {
@Autowired
private IUserInfoService userInfoService;
@Autowired
private CWeChatClient cWeChatClient;
@Override
public List<String> getCwechatOrg(String accessToken, Long cOrgId) {
List<String> orgNameList = getOrgName(new ArrayList<String>(), accessToken, cOrgId);
Collections.reverse(orgNameList);
log.info("查询到当前组织:" + orgNameList);
return orgNameList;
}
@Override
public WUserInfoVO getCwechatUserDetail(String accessToken, String userId) {
JSONObject cWechatUserDetail = cWeChatClient.getCWechatUserDetail(accessToken, userId);
log.info("获取到的用户的信息:" + cWechatUserDetail.toString());
WUserInfoVO wUserInfoVO = new WUserInfoVO();
if ("0".equals(cWechatUserDetail.getString("errcode"))) {
wUserInfoVO.setWechatuserid(cWechatUserDetail.getString("userid") != null ? cWechatUserDetail.getString("userid") : "");
wUserInfoVO.setNickname(cWechatUserDetail.getString("name") != null ? cWechatUserDetail.getString("name") : "");
wUserInfoVO.setMobile(cWechatUserDetail.getString("mobile") != null ? cWechatUserDetail.getString("mobile") : "");
wUserInfoVO.setPosition(cWechatUserDetail.getString("position") != null ? cWechatUserDetail.getString("position") : "");
wUserInfoVO.setSex(Integer.parseInt(cWechatUserDetail.getString("gender") != null ? cWechatUserDetail.getString("gender") : ""));
wUserInfoVO.setHeadimgurl(cWechatUserDetail.getString("avatar") != null ? cWechatUserDetail.getString("avatar") : "");
wUserInfoVO.setEmail(cWechatUserDetail.getString("email") != null ? cWechatUserDetail.getString("email") : "");
wUserInfoVO.setEnglishName(cWechatUserDetail.getString("englishname") != null ? cWechatUserDetail.getString("englishname") : "");
wUserInfoVO.setTelephone(cWechatUserDetail.getString("telephone") != null ? cWechatUserDetail.getString("telephone") : "");
wUserInfoVO.setQrCode(cWechatUserDetail.getString("qr_code") != null ? cWechatUserDetail.getString("qr_code") : "");
wUserInfoVO.setMainDepartmentId(cWechatUserDetail.getString("main_department"));
log.info("拿到的企业主部门信息:{}", cWechatUserDetail.getString("main_department"));
JSONArray departmentList = cWechatUserDetail.getJSONArray("department");
log.info("拿到的企业部门信息:{}", JSON.toJSONString(departmentList));
// 取第一个
// String departmentId = departmentList.getString(0);
//2020-09-24改为获取主部门即可
wUserInfoVO.setDepartmentId(wUserInfoVO.getMainDepartmentId());
}
return wUserInfoVO;
}
/**
* 递归获取用户部门list
*
* @param orgNameList
* @param accessToken
* @param cOrgId
* @return
*/
public List<String> getOrgName(List<String> orgNameList, String accessToken, Long cOrgId) {
JSONObject departmentInfo = cWeChatClient.getCwechatDepartmentList(accessToken, cOrgId);
log.info("department 信息:" + departmentInfo.toString());
if ((Constants.ZERO).equals(departmentInfo.getString("errcode"))) {
JSONArray departmentList = departmentInfo.getJSONArray("department");
// JsonArray to List
List<WechatOrg> orgList = JSONObject.parseArray(departmentList.toJSONString(), WechatOrg.class);
Long id = null;
String orgName = null;
Long orgId = null;
for (WechatOrg wechatOrg : orgList) {
if (cOrgId.equals(wechatOrg.getId())) {
orgId = wechatOrg.getId();
id = wechatOrg.getParentId();
orgName = wechatOrg.getName();
orgNameList.add(orgName);
break;
}
}
//不拿根部门
if (Constants.YES_FLAG !=id ) {
getOrgName(orgNameList, accessToken, id);
log.info("组织名称:" + orgId + ";" + orgName);
}
}
return orgNameList;
}
}
package com.yizhi.application.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yizhi.application.controller.WechatProviderController;
import com.yizhi.application.domain.UserInfo;
import com.yizhi.application.orm.id.IdGenerator;
import com.yizhi.application.service.IProviderUserInfoService;
import com.yizhi.core.application.task.TaskExecutor;
import com.yizhi.application.task.UpdateUserInfoService;
import com.yizhi.wechat.application.utils.OkHttpUtils;
import com.yizhi.wechat.application.vo.wechat.Constants;
import com.yizhi.wechat.application.vo.wechat.WUserInfoVO;
import com.yizhi.wechat.application.vo.wechat.WechatUserInfoVO;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* <p>
* 第三方应用suite_ticket 表 服务实现类
* </p>
*
* @author lingye
* @since 2020-08-05
*/
@Service
@Log4j2
public class ProviderUserInfoServiceImpl implements IProviderUserInfoService {
@Autowired
IdGenerator idGenerator;
@Value("${wechat.provider.user.info}")
private String providerUserInfoUrl;
@Value("${wechat.provider.user.detail}")
private String providerUserDetailUrl;
@Autowired
private WechatProviderController providerController;
@Autowired
private UpdateUserInfoService updateUserInfoService;
@Autowired
private TaskExecutor taskExecutor;
@Override
public WechatUserInfoVO getProviderInfoDetail(String suiteId, String code) {
WechatUserInfoVO userInfoVO = new WechatUserInfoVO();
String suiteToken = providerController.getSuiteToken(suiteId);
log.info("suite_token:{}",suiteToken);
String url = providerUserInfoUrl + "code=" + code + "&access_token=" + suiteToken;
log.info("当前url:{}",url);
String result = OkHttpUtils.httpGet(url);
JSONObject userJson = JSON.parseObject(result);
log.info("返回的用户信息结果:{}",userJson);
WUserInfoVO wUserInfoVO = new WUserInfoVO();
if (!(Constants.ZERO).equals(userJson.getString("errcode"))) {
userInfoVO.setCode(Constants.DEL_FLAG);
userInfoVO.setMsg(userJson.getString("errmsg"));
return userInfoVO;
}
String userId = userJson.getString("UserId");
String openUserId = userJson.getString("open_userid");
String deviceId = userJson.getString("DeviceId");
String corpId = userJson.getString("CorpId");
if (!"null".equals(corpId)) {
HashMap<String, Object> map = new HashMap<>();
String userTicket = userJson.getString("user_ticket");
map.put("user_ticket", userTicket);
Map<String, String> head = new HashMap<String, String>();
head.put("Content-Type", "application/json");
String userDetailUrl = providerUserDetailUrl+"access_token="+suiteToken;
String userDetail = OkHttpUtils.doRequest2(userDetailUrl, head, JSON.toJSONString(map));
JSONObject userDetailJSON = JSON.parseObject(userDetail);
log.info("用户的详情:{}",userDetail);
if (Constants.ZERO.equals(userDetailJSON.getString("errcode"))) {
UserInfo userInfo = new UserInfo();
getProviderUser(userDetailJSON, userInfo);
userInfo.setDeviceId(deviceId);
userInfo.setUserId(userId);
BeanUtils.copyProperties(userInfo, wUserInfoVO);
updateUserInfoService.taskAddProviderUserInfo(userInfo);
}
log.info("返回的实体wUserInfoVO:{}", JSON.toJSON(wUserInfoVO));
wUserInfoVO.setWechatuserid(openUserId);
wUserInfoVO.setIsDeleted(Constants.NO_FLAG);
userInfoVO.setWUserInfoVO(wUserInfoVO);
userInfoVO.setCode(Constants.YES_FLAG);
}
return userInfoVO;
}
public void getProviderUser(JSONObject userDetailJSON, UserInfo userInfo) {
userInfo.setId(idGenerator.generate());
userInfo.setWechatuserid(userDetailJSON.getString("open_userid"));
userInfo.setNickname(userDetailJSON.getString("name"));
userInfo.setMobile(userDetailJSON.getString("mobile"));
userInfo.setEmail(userDetailJSON.getString("email"));
userInfo.setHeadimgurl(userDetailJSON.getString("avatar"));
userInfo.setQrCode(userDetailJSON.getString("qr_code"));
userInfo.setSex(Integer.parseInt(userDetailJSON.getString("gender")));
String corpId = userDetailJSON.getString("corpid");
userInfo.setCorpId(corpId);
userInfo.setCreateTime(new Date());
userInfo.setUserType(Constants.DEL_FLAG);
}
}
package com.yizhi.application.service.impl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.application.domain.PublicPlatformConfig;
import com.yizhi.application.mapper.PublicPlatformConfigMapper;
import com.yizhi.application.orm.id.IdGenerator;
import com.yizhi.application.orm.util.QueryUtil;
import com.yizhi.application.service.IPublicPlatformConfigService;
import com.yizhi.wechat.application.vo.wechat.Constants;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author lilingye
* @since 2018-04-29
*/
@Service
@Transactional
@Log4j2
public class PublicPlatformConfigServiceImpl extends ServiceImpl<PublicPlatformConfigMapper, PublicPlatformConfig> implements IPublicPlatformConfigService {
@Autowired
IdGenerator idGenerator;
/**
* 获取公众号配置信息
*
* @param appId 公众号的APPID
* @return
*/
@Override
public PublicPlatformConfig getPubConfig(String appId, String agentId) {
PublicPlatformConfig publicPlatformConfig = new PublicPlatformConfig();
publicPlatformConfig.setAppId(appId);
publicPlatformConfig.setAgentId(StringUtils.isNotEmpty(agentId) ? agentId.trim() : null);
publicPlatformConfig.setIsDeleted(Constants.DEL_FLAG);
return this.selectOne(QueryUtil.condition(publicPlatformConfig));
}
@Override
public PublicPlatformConfig getConfigByAppId(String appId) {
PublicPlatformConfig publicPlatformConfig = new PublicPlatformConfig();
publicPlatformConfig.setAppId(appId);
publicPlatformConfig.setIsDeleted(Constants.DEL_FLAG);
List<PublicPlatformConfig> configList = this.selectList(QueryUtil.condition(publicPlatformConfig));
if (configList == null || configList.isEmpty()) {
return null;
}
return configList.get(0);
}
@Override
public List<PublicPlatformConfig> getPubConfigs(String appId, String agentId) {
PublicPlatformConfig publicPlatformConfig = new PublicPlatformConfig();
publicPlatformConfig.setAppId(appId);
publicPlatformConfig.setAgentId(StringUtils.isNotEmpty(agentId) ? agentId.trim() : null);
publicPlatformConfig.setIsDeleted(Constants.DEL_FLAG);
List<PublicPlatformConfig> publicPlatformConfigs = this.selectList(QueryUtil.condition(publicPlatformConfig));
if (CollectionUtils.isNotEmpty(publicPlatformConfigs)) {
return publicPlatformConfigs;
}
return null;
}
@Override
public List<PublicPlatformConfig> getPlatformInfos() {
List<PublicPlatformConfig> configList = new ArrayList<>();
PublicPlatformConfig publicPlatformConfig = new PublicPlatformConfig();
publicPlatformConfig.setIsDeleted(Constants.DEL_FLAG);
publicPlatformConfig.setType(Constants.ONE);
EntityWrapper<PublicPlatformConfig> condition = QueryUtil.condition(publicPlatformConfig);
condition.groupBy("app_id");
// 微信公众号配置列表
configList = this.selectList(condition);
PublicPlatformConfig config = new PublicPlatformConfig();
config.setIsDeleted(Constants.DEL_FLAG);
config.setType(Constants.ZERO);
condition = QueryUtil.condition(publicPlatformConfig);
condition.groupBy("agent_id");
List<PublicPlatformConfig> companyConfigList = this.selectList(condition);
if (CollectionUtils.isNotEmpty(companyConfigList)) {
configList.addAll(companyConfigList);
}
return configList;
}
@Override
public PublicPlatformConfig insertPublicPlatformConfigInfo(PublicPlatformConfig publicPlatformConfig) {
publicPlatformConfig.setId(idGenerator.generate());
publicPlatformConfig.setCreateTime(new Date());
if (StringUtils.isNotBlank(publicPlatformConfig.getAgentId())) {
publicPlatformConfig.setType(Constants.ZERO);
} else {
publicPlatformConfig.setType(Constants.ONE);
}
RequestContext context = ContextHolder.get();
log.info("上下文" + context);
this.insert(publicPlatformConfig);
return publicPlatformConfig;
}
@Override
public Page<PublicPlatformConfig> findPublicConfigList(Integer pageNo, Integer pageSize, String name) {
Page<PublicPlatformConfig> page = new Page<PublicPlatformConfig>(pageNo, pageSize);
PublicPlatformConfig publicPlatformConfig = new PublicPlatformConfig();
EntityWrapper condition = QueryUtil.condition(publicPlatformConfig);
condition.orderBy("create_time", false);
if (StringUtils.isNotBlank(name)) {
condition.like("name", name.trim());
}
condition.orderBy("create_time",true);
return this.selectPage(page, condition);
}
@Override
public PublicPlatformConfig getPublicPlatformConfig(PublicPlatformConfig publicPlatformConfig) {
return this.selectOne(QueryUtil.condition(publicPlatformConfig));
}
}
package com.yizhi.application.service.impl;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yizhi.application.domain.SuiteTicket;
import com.yizhi.application.mapper.SuiteTicketMapper;
import com.yizhi.application.orm.id.IdGenerator;
import com.yizhi.application.orm.util.QueryUtil;
import com.yizhi.application.service.ISuiteTicketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
/**
* <p>
* 第三方应用suite_ticket 表 服务实现类
* </p>
*
* @author lingye
* @since 2020-08-05
*/
@Service
public class SuiteTicketServiceImpl extends ServiceImpl<SuiteTicketMapper, SuiteTicket> implements ISuiteTicketService {
@Autowired
IdGenerator idGenerator;
@Override
public Boolean saveOrUpdateSuiteTicket(SuiteTicket suiteTicket) {
SuiteTicket s = new SuiteTicket();
s.setSuiteId(suiteTicket.getSuiteId());
s.setDeleted(0);
SuiteTicket st = this.selectOne(QueryUtil.condition(s));
boolean updateRes;
if (st == null) {
suiteTicket.setId(idGenerator.generate());
suiteTicket.setDeleted(0);
Date date = new Date();
suiteTicket.setCreateTime(date);
suiteTicket.setUpdateTime(date);
updateRes = this.insert(suiteTicket);
} else {
suiteTicket.setDeleted(0);
suiteTicket.setId(st.getId());
updateRes = this.updateById(suiteTicket);
}
return updateRes;
}
@Override
public SuiteTicket getSuiteTicketById(String suiteId) {
SuiteTicket suiteTicket = new SuiteTicket();
suiteTicket.setDeleted(0);
suiteTicket.setSuiteId(suiteId);
return this.selectOne(QueryUtil.condition(suiteTicket));
}
}
package com.yizhi.application.service.impl;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yizhi.application.domain.TrAccountUserinfo;
import com.yizhi.application.domain.UserInfo;
import com.yizhi.application.mapper.TrAccountUserinfoMapper;
import com.yizhi.application.orm.id.IdGenerator;
import com.yizhi.application.orm.util.QueryUtil;
import com.yizhi.application.service.ITrAccountUserinfoService;
import com.yizhi.application.service.IUserInfoService;
import com.yizhi.util.application.constant.ReturnCode;
import com.yizhi.wechat.application.vo.wechat.Constants;
import com.yizhi.wechat.application.vo.wechat.TrAccountUserinfoVO;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
/**
* <p>
* 服务实现类
* </p>
*
* @author lilingye
* @since 2018-04-29
*/
@Log4j2
@Service
public class TrAccountUserinfoServiceImpl extends ServiceImpl<TrAccountUserinfoMapper, TrAccountUserinfo> implements ITrAccountUserinfoService {
@Autowired
IdGenerator idGenerator;
@Autowired
IUserInfoService userInfoService;
@Override
@Transactional(rollbackFor = Exception.class)
public TrAccountUserinfoVO saveAccount(TrAccountUserinfoVO trAccountUserinfoVO) {
Long companyId = trAccountUserinfoVO.getCompanyId();
log.info("公司的id为:" + companyId);
// 查询是否存在 accountId的绑定关系
TrAccountUserinfo trAccountUserinfo = new TrAccountUserinfo();
trAccountUserinfo.setAccountId(trAccountUserinfoVO.getAccountId());
if (trAccountUserinfoVO.getType() == 5) {
// 小程序
trAccountUserinfo.setUnionId(trAccountUserinfoVO.getWechatuserid());
} else {
trAccountUserinfo.setWechatuserid(trAccountUserinfoVO.getWechatuserid());
}
trAccountUserinfo.setIsDeleted(0);
TrAccountUserinfo trUserInfoWechat = this.selectOne(QueryUtil.condition(trAccountUserinfo));
// 检查用户是否已经存在
if (trUserInfoWechat != null) {
//如果存在直接返回信息
BeanUtils.copyProperties(trUserInfoWechat, trAccountUserinfo);
} else {
// 如果不存在 查看微信号是和未木云账号绑定或者 账号被其他的微信号绑定
if (trAccountUserinfoVO.getType() == 5) {
trAccountUserinfo.setUnionId(null);
} else {
trAccountUserinfo.setWechatuserid(null);
}
trAccountUserinfo.setCompanyId(companyId);
TrAccountUserinfo trUserInfo = this.selectOne(QueryUtil.condition(trAccountUserinfo));
log.info("当前的参数1:"+JSON.toJSONString(trAccountUserinfo));
if (trUserInfo != null) {
log.info("账号:" + trAccountUserinfoVO.getAccountId() + ",已经绑定过微信账号");
trAccountUserinfoVO.setCode(ReturnCode.ACCOUNT_BIND.getCode());
return trAccountUserinfoVO;
}
trAccountUserinfo.setAccountId(null);
trAccountUserinfo.setCompanyId(companyId);
if (trAccountUserinfoVO.getType() == Constants.FIVE) {
trAccountUserinfo.setUnionId(trAccountUserinfoVO.getWechatuserid());
} else {
trAccountUserinfo.setWechatuserid(trAccountUserinfoVO.getWechatuserid());
}
log.info("当前的参数2:"+JSON.toJSONString(trAccountUserinfo));
TrAccountUserinfo wechatUser = this.selectOne(QueryUtil.condition(trAccountUserinfo));
if (wechatUser != null) {
log.info("微信账号:" + trAccountUserinfoVO.getWechatuserid() + ",");
trAccountUserinfoVO.setCode(ReturnCode.OPENID_BIND.getCode());
return trAccountUserinfoVO;
}
if (null == trUserInfo && wechatUser == null) {
log.info("登录未木云账号未绑定微信账号。");
Long id = idGenerator.generate();
trAccountUserinfo.setWechatuserid(trAccountUserinfoVO.getWechatuserid());
trAccountUserinfo.setId(id);
trAccountUserinfo.setAccountId(trAccountUserinfoVO.getAccountId());
trAccountUserinfo.setCompanyId(trAccountUserinfoVO.getCompanyId());
trAccountUserinfo.setSiteId(trAccountUserinfoVO.getSiteId());
trAccountUserinfo.setCreateTime(new Date());
trAccountUserinfo.setType(trAccountUserinfoVO.getType());
// 获取用户的头像
UserInfo wechatUserInfo = new UserInfo();
wechatUserInfo.setWechatuserid(trAccountUserinfoVO.getWechatuserid());
// String avatar = null;
// try {
// avatar = userInfoService.selectOne(QueryUtil.condition(wechatUserInfo)).getHeadimgurl();
// log.info("用户头像:" + avatar);
// } catch (Exception e) {
// e.printStackTrace();
// log.info("返回错误{}", e);
// }
// 生成wechatuserid和系统用户的关联关系
Date date = new Date();
trAccountUserinfo.setCreateTime(date);
trAccountUserinfo.setUpdateTime(date);
this.insert(trAccountUserinfo);
BeanUtils.copyProperties(trAccountUserinfo, trAccountUserinfoVO);
// trAccountUserinfoVO.setHeadImgUrl(avatar);
trAccountUserinfoVO.setCode(ReturnCode.SUCCESS.getCode());
log.info("返回实体:" + trAccountUserinfoVO);
}
}
return trAccountUserinfoVO;
}
/**
* 查询用户是否在未木云用户系统中
*
* @param openId 用户唯一标识
* @return
*/
@Override
public TrAccountUserinfo queryAccount(String openId) {
TrAccountUserinfo trAccountUserinfo = new TrAccountUserinfo();
trAccountUserinfo.setIsDeleted(0);
trAccountUserinfo.setWechatuserid(openId);
return this.selectOne(QueryUtil.condition(trAccountUserinfo));
}
/**
* 查找用户是否存在绑定微信关系中
*
* @param openId
* @param companyId
* @return
*/
@Override
public TrAccountUserinfo findAccount(String openId, Long companyId) {
TrAccountUserinfo trAccountUserinfo = new TrAccountUserinfo();
trAccountUserinfo.setIsDeleted(0);
trAccountUserinfo.setWechatuserid(openId.trim());
trAccountUserinfo.setCompanyId(companyId);
List<TrAccountUserinfo> trAccountUserInfoList = this.selectList(QueryUtil.condition(trAccountUserinfo));
if (CollectionUtils.isEmpty(trAccountUserInfoList)) {
return null;
}
return trAccountUserInfoList.get(0);
}
@Override
public TrAccountUserinfo findBindWechat(TrAccountUserinfo trAccountUserinfo) {
return this.selectOne(QueryUtil.condition(trAccountUserinfo));
}
/**
* 修改关联关系
*
* @param trAccountUserinfo
* @return
*/
@Override
public boolean updateTrAccountUserInfo(TrAccountUserinfo trAccountUserinfo) {
trAccountUserinfo = this.selectOne(QueryUtil.condition(trAccountUserinfo));
trAccountUserinfo.setIsDeleted(2);
return this.updateById(trAccountUserinfo);
}
@Override
public boolean unbindAccountByWeChatUserId(String weChatUserId) {
if (null == weChatUserId) {
return false;
}
TrAccountUserinfo trAccountUserinfo = new TrAccountUserinfo();
trAccountUserinfo.setWechatuserid(weChatUserId);
trAccountUserinfo.setIsDeleted(Constants.DEL_FLAG);
List<TrAccountUserinfo> accountUserInfoList = this.selectList(QueryUtil.condition(trAccountUserinfo));
if (CollectionUtils.isNotEmpty(accountUserInfoList)) {
accountUserInfoList.parallelStream().map(accountUser -> {
accountUser.setIsDeleted(Constants.YES_FLAG);
return accountUser;
}).collect(Collectors.toList());
boolean b = this.updateBatchById(accountUserInfoList);
}
return true;
}
@Override
public boolean updateUserInfo(Long accountId, String weChatUserId) {
boolean updateResult = false ;
TrAccountUserinfo accountUserInfo = new TrAccountUserinfo();
accountUserInfo.setAccountId(accountId);
accountUserInfo.setIsDeleted(0);
EntityWrapper<TrAccountUserinfo> condition = QueryUtil.condition(accountUserInfo);
condition.ne("wechatuserid",weChatUserId);
List<TrAccountUserinfo> trAccountUserInfoLists = this.selectList(condition);
if (CollectionUtils.isNotEmpty(trAccountUserInfoLists)) {
trAccountUserInfoLists = trAccountUserInfoLists.stream().map(trAccountUserInfo -> {
trAccountUserInfo.setIsDeleted(1);
return trAccountUserInfo;
}).collect(Collectors.toList());
updateResult = this.updateBatchById(trAccountUserInfoLists);
}
return updateResult;
}
@Override
public boolean autoUnBindWeChatAccount(TrAccountUserinfo trAccountUserInfo) {
log.info("当前绑定微信的关系信息:"+JSON.toJSON(trAccountUserInfo));
// 用户accountId
Long accountId = trAccountUserInfo.getAccountId();
// 用户wechatId
String weChatUserId = trAccountUserInfo.getWechatuserid();
// id
Long id = trAccountUserInfo.getId();
TrAccountUserinfo accountUserInfo = new TrAccountUserinfo();
accountUserInfo.setAccountId(accountId);
accountUserInfo.setIsDeleted(0);
EntityWrapper<TrAccountUserinfo> ew = QueryUtil.condition(accountUserInfo);
ew.ne("type",3);
ew.ne("id",id);
List<TrAccountUserinfo> trAccountUserInfoList = this.selectList(ew);
log.info("返回重复的:{}"+JSON.toJSON(trAccountUserInfoList));
boolean flag = false;
if (CollectionUtils.isNotEmpty(trAccountUserInfoList)) {
List<TrAccountUserinfo> userInfos = trAccountUserInfoList.stream().map(tr -> {
tr.setIsDeleted(1);
tr.setUpdateById(1000L);
tr.setUpdateTime(new Date());
return tr;
}).collect(Collectors.toList());
log.info("返回结果:"+userInfos);
flag = this.updateBatchById(userInfos);
}
log.info("返回结果:"+flag);
return flag;
}
}
package com.yizhi.application.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yizhi.core.application.cache.RedisCache;
import com.yizhi.application.controller.WechatProviderController;
import com.yizhi.application.domain.PublicPlatformConfig;
import com.yizhi.application.domain.TrAccountUserinfo;
import com.yizhi.application.domain.UserInfo;
import com.yizhi.application.feign.CWeChatClient;
import com.yizhi.application.feign.WeChatClient;
import com.yizhi.application.mapper.TrAccountUserinfoMapper;
import com.yizhi.application.mapper.UserInfoMapper;
import com.yizhi.application.orm.id.IdGenerator;
import com.yizhi.application.orm.util.QueryUtil;
import com.yizhi.application.service.IUserInfoService;
import com.yizhi.application.task.UpdateUserInfoService;
import com.yizhi.wechat.application.vo.wechat.*;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
//import com.yizhi.core.application.task.InsertCompanyUserInfoService;
/**
* <p>
* 服务实现类
* </p>
*
* @author lilingye
* @since 2018-04-29
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {
private static final Logger LOGGER = LoggerFactory.getLogger(UserInfoServiceImpl.class);
@Resource
private TrAccountUserinfoMapper trAccountUserinfoMapper;
@Resource
private UserInfoMapper userInfoMapper;
@Resource
private IdGenerator idGenerator;
@Autowired
private CWeChatClient cWeChatClient;
@Autowired
private WeChatClient weChatClient;
@Autowired
private RedisCache redisCache;
@Autowired
private IUserInfoService iUserInfoService;
@Autowired
private UpdateUserInfoService updateUserInfoService;
@Autowired
private WechatProviderController wechatProviderController;
/**
* 查询用户是wmcloud 系统
*
* @param wechatUserId
* @return
*/
@Override
public TrAccountUserinfo getUserInVmCloud(String wechatUserId) {
TrAccountUserinfo trAccountUserinfo = new TrAccountUserinfo();
trAccountUserinfo.setWechatuserid(wechatUserId);
trAccountUserinfo.setIsDeleted(Constants.DEL_FLAG);
return trAccountUserinfoMapper.selectOne(trAccountUserinfo);
}
@Override
public TrAccountUserinfo saveUser(String wechatUserId, Long accountId) {
TrAccountUserinfo trAccountUserinfo = new TrAccountUserinfo();
trAccountUserinfo.setId(idGenerator.generate());
trAccountUserinfo.setAccountId(accountId);
trAccountUserinfo.setWechatuserid(wechatUserId);
trAccountUserinfoMapper.insert(trAccountUserinfo);
return trAccountUserinfoMapper.selectOne(trAccountUserinfo);
}
@Transactional(rollbackFor = Exception.class)
@Override
public WechatUserInfoVO getWeChatUserInfo(String appId, String secret, String code, Integer source) {
WechatUserInfoVO userInfoVO = new WechatUserInfoVO();
String weChatUserId = null;
String unionId = null ;
try {
JSONObject tokenJSON = weChatClient.getWechaToken(appId, secret, code);
LOGGER.info("用户信息的token:{}", tokenJSON);
if (tokenJSON.getString("errcode") != null && !(Constants.nullStr).equals(tokenJSON.getString("errcode"))) {
// 接口报错返回信息
userInfoVO.setCode(Constants.NO_FLAG);
userInfoVO.setMsg(tokenJSON.getString("errmsg"));
return userInfoVO;
}
String accessToken = tokenJSON.getString("access_token");
LOGGER.info("获取微信用户新的token:{}", accessToken);
weChatUserId = tokenJSON.getString("openid");
unionId = tokenJSON.getString("unionid");
LOGGER.info("用户的openId:{}", weChatUserId);
WUserInfoVO wUserInfoVO = new WUserInfoVO();
if (source == null) {
updateUserInfoService.taskAddUserInfo(accessToken, weChatUserId,unionId);
} else if (source == 1){
UserInfo userInfo = getWeChatUserInfo(accessToken, weChatUserId);
BeanUtils.copyProperties(userInfo,wUserInfoVO);
}
wUserInfoVO.setWechatuserid(weChatUserId);
userInfoVO.setWUserInfoVO(wUserInfoVO);
userInfoVO.setCode(Constants.YES_FLAG);
} catch (Exception e) {
LOGGER.info("用户异常信息:{}", e.getMessage());
}
return userInfoVO;
}
@Transactional(rollbackFor = Exception.class)
@Override
public WechatUserInfoVO getCompanyWechatUserInfo(PublicPlatformConfig publicPlatformConfig, String code, Integer source) {
WechatUserInfoVO userInfoVO = new WechatUserInfoVO();
publicPlatformConfig.setType("0");
String redisKey = (publicPlatformConfig.getAppId().trim() + publicPlatformConfig.getAgentId()).trim();
// 声明 access_token
String accessToken = getCwechatAccessToken(redisKey, publicPlatformConfig);
LOGGER.info("access_token is:" + accessToken);
JSONObject userInfoJSON = cWeChatClient.getUserInfo(accessToken, code);
LOGGER.info("userInfoJSON:" + userInfoJSON);
String userTicket = userInfoJSON.getString("user_ticket");
LOGGER.info("企业的user-ticket是:" + userTicket);
WechatParamVO wechatParamVO = new WechatParamVO();
wechatParamVO.setUser_ticket(userTicket);
JSONObject userDetailJSON = null;
String userId = null;
try {
userDetailJSON = cWeChatClient.getUserDetail(accessToken, wechatParamVO);
if (!(Constants.ZERO).equals(userDetailJSON.getString("errcode"))) {
userInfoVO.setCode(Constants.DEL_FLAG);
userInfoVO.setMsg(userDetailJSON.getString("errmsg"));
return userInfoVO;
}
userId = userDetailJSON.getString("userid");
} catch (Exception e) {
LOGGER.info("" + e.getLocalizedMessage());
}
WUserInfoVO wUserInfoVO = new WUserInfoVO();
if(source==null) {
updateUserInfoService.taskAddCompanyUserInfo(userDetailJSON);
} else if (source == 1){
UserInfo userInfo = getCompanyUser(userDetailJSON);
BeanUtils.copyProperties(userInfo,wUserInfoVO);
}
wUserInfoVO.setWechatuserid(userId);
wUserInfoVO.setIsDeleted(Constants.NO_FLAG);
userInfoVO.setWUserInfoVO(wUserInfoVO);
userInfoVO.setCode(Constants.YES_FLAG);
return userInfoVO;
}
@Override
public SignatureVO getSignature(String accessToken, String url, PublicPlatformConfig publicPlatformConfig) {
String ticketKey = "jsapiticket_" + (publicPlatformConfig.getAppId() + publicPlatformConfig.getAgentId()).trim();
String ticket = null;
//从缓存中获取token
Object ticketVO = redisCache.hget(ticketKey, ticketKey);
// 0 微信企业服务请求
if (ticketVO != null) {
Object ticketJSON = JSON.toJSON(ticketVO);
LOGGER.info("查看redis中ticket信息:" + ticketJSON.toString());
ticket = JSON.parseObject(ticketJSON.toString()).getString("ticket");
if (!"".equals(ticket) && !(Constants.nullStr).equals(ticket) && ticket != null) {
LOGGER.info("redis中ticket信息:" + ticket);
} else {
//生成新的jsApiTicket
ticket = getJsApiTicket(accessToken, publicPlatformConfig);
LOGGER.info("新生成的ticket:" + ticket);
}
} else {
ticket = getJsApiTicket(accessToken, publicPlatformConfig);
LOGGER.info("新生成的ticket:" + ticket);
}
return sign(ticket, url);
}
@Override
public String getAccessToken(PublicPlatformConfig publicPlatformConfig) {
LOGGER.info("获取微信token的参数: " + publicPlatformConfig);
String accessToken = null;
// 根据公众号类型获取
if ((Constants.ZERO).equals(publicPlatformConfig.getType())) {
// 获取企业token
JSONObject accessTokenJson = cWeChatClient.getWechatToken(publicPlatformConfig.getSecret().trim(), publicPlatformConfig.getAppId().trim());
LOGGER.info("调用企业微信接返回的信息:" + accessTokenJson);
accessToken = accessTokenJson.getString(Constants.ACCESS_TOKEN);
LOGGER.info("调用企业微信接口生成的AccessToken:" + accessToken);
} else if ((Constants.ONE).equals(publicPlatformConfig.getType())) {
// 获取微信号token
JSONObject accessTokenJson = weChatClient.getAccessToken(publicPlatformConfig.getAppId(), publicPlatformConfig.getSecret());
LOGGER.info("appid是" + publicPlatformConfig.getAppId());
LOGGER.info("secret是" + publicPlatformConfig.getSecret());
LOGGER.info("accessTokenJson的值" + accessTokenJson.toJSONString());
accessToken = accessTokenJson.getString(Constants.ACCESS_TOKEN);
}else if ((Constants.TWO).equals(publicPlatformConfig.getType())){
accessToken = wechatProviderController.getSuiteToken(publicPlatformConfig.getAppId().trim());
}
return accessToken;
}
@Override
public JSONObject getCwechatUserInfo(String userId, PublicPlatformConfig publicPlatformConfig) {
String redisKey = (publicPlatformConfig.getAppId() + publicPlatformConfig.getAgentId()).trim();
LOGGER.info("accessToken 的key是:" + redisKey);
String accessToken = getCwechatAccessToken(redisKey, publicPlatformConfig);
LOGGER.info("accessToken:" + accessToken);
JSONObject cuserInfo = cWeChatClient.getCWechatUserDetail(accessToken, userId);
LOGGER.info("获取到的企业用户的信息:" + cuserInfo.toJSONString());
return cuserInfo;
}
@Override
public WUserInfoVO getWUserInfoVO(String openId) {
LOGGER.info("传来的值openId:" + openId);
UserInfo wechatUserInfo = new UserInfo();
wechatUserInfo.setWechatuserid(openId);
wechatUserInfo.setIsDeleted(Constants.DEL_FLAG);
WUserInfoVO userInfoVO = new WUserInfoVO();
UserInfo userInfo = null;
List<UserInfo> userInfoList = userInfoMapper.selectList(QueryUtil.condition(wechatUserInfo));
if (CollectionUtils.isNotEmpty(userInfoList)) {
userInfo = userInfoList.get(0);
}
LOGGER.info("查询用户openId的数据{}", userInfo);
if (userInfo != null) {
BeanUtils.copyProperties(userInfo, userInfoVO);
return userInfoVO;
} else {
return null;
}
}
/**
* 获取签名
*
* @param jsApiTicket
* @param url
* @return
*/
public static SignatureVO sign(String jsApiTicket, String url) {
Map<String, String> ret = new HashMap<String, String>();
String nonceStr = createNonceStr();
String timestamp = createTimeStamp();
String signature = "";
StringBuffer stringBuffer = new StringBuffer();
//注意这里参数名必须全部小写,且必须有序
stringBuffer.append("jsapi_ticket=").
append(jsApiTicket).
append("&noncestr=").
append(nonceStr).append("&timestamp=").append(timestamp).append("&url=").append(url);
LOGGER.info("拼接字符串:" + stringBuffer.toString());
try {
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(stringBuffer.toString().getBytes("UTF-8"));
signature = byteToHex(crypt.digest());
LOGGER.info("签名后的值:" + signature);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
SignatureVO signatureVO = new SignatureVO();
signatureVO.setSignnatrue(signature);
signatureVO.setTimestamp(timestamp);
signatureVO.setNoncestr(nonceStr);
return signatureVO;
}
private static String byteToHex(final byte[] hash) {
Formatter formatter = new Formatter();
for (byte b : hash) {
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
/**
* 获取随机数
*
* @return
*/
private static String createNonceStr() {
return UUID.randomUUID().toString();
}
/**
* 获取时间戳
*
* @return
*/
private static String createTimeStamp() {
return Long.toString(System.currentTimeMillis() / 1000);
}
/**
* 获取企业服务号的accessToken
*
* @param redisKey
* @param publicPlatformConfig
* @return
*/
public String getCwechatAccessToken(String redisKey, PublicPlatformConfig publicPlatformConfig) {
//从缓存中获取token
Object tokenVO = redisCache.hget(redisKey, redisKey);
LOGGER.info("从缓存中获取的token:" + tokenVO);
// 声明 access_token
String access_token = null;
if (!org.springframework.util.StringUtils.isEmpty(tokenVO)) {
// 获取token
Object tokenJSON = JSON.toJSON(tokenVO);
LOGGER.info("查看缓存中的access_token信息:" + tokenJSON.toString());
LOGGER.info("缓存中的accessToken的值:" + JSON.parseObject(tokenJSON.toString()).getString("accessToken"));
String accessToken = JSON.parseObject(tokenJSON.toString()).getString("accessToken");
if (!"".equals(accessToken) && !(Constants.nullStr).equals(accessToken) && accessToken != null) {
LOGGER.info("accessToken值存在");
access_token = JSON.parseObject(tokenJSON.toString()).getString("accessToken");
} else {
// 生成新的token
String accToken = getAccessToken(publicPlatformConfig);
Date nowDate = new Date();
WTokenVO wTokenVO = new WTokenVO();
wTokenVO.setAppid(publicPlatformConfig.getAppId());
wTokenVO.setCreateTime(nowDate);
wTokenVO.setAccessToken(access_token);
redisCache.hset(redisKey, redisKey, accToken, Constants.REDIS_INVALID_TIME);
access_token = getAccessToken(publicPlatformConfig);
}
} else {
WTokenVO wTokenVO = new WTokenVO();
wTokenVO.setAppid(publicPlatformConfig.getAppId());
wTokenVO.setCreateTime(new Date());
// 调用微信接口获取token 并存在redis中
access_token = iUserInfoService.getAccessToken(publicPlatformConfig);
wTokenVO.setAccessToken(access_token);
redisCache.hset(redisKey, redisKey, JSON.toJSONString(wTokenVO), Constants.REDIS_INVALID_TIME);
}
LOGGER.info("accessToken的值是:" + access_token);
return access_token;
}
/**
* 生成签名
*
* @param publicPlatformConfig
* @return
*/
@Override
public String getJsApiTicket(String accessToken, PublicPlatformConfig publicPlatformConfig) {
String ticketKey = "jsapiticket_" + (publicPlatformConfig.getAppId() + publicPlatformConfig.getAgentId()).trim();
LOGGER.info("ticketKey的值是:" + ticketKey);
String ticket = null;
// 企业号的类型
String type = publicPlatformConfig.getType();
WTicketVO wTicketVO = new WTicketVO();
wTicketVO.setAppid(publicPlatformConfig.getAppId());
wTicketVO.setAgentId(publicPlatformConfig.getAgentId());
wTicketVO.setCreateTime(new Date());
// 企业服务号
if (Constants.ONE.equals(type)) {
// 微信公众号
JSONObject jsApiTicketJSON = weChatClient.getTicket(accessToken);
LOGGER.info("=====jsApiTicketJSON========" + jsApiTicketJSON.toJSONString());
ticket = jsApiTicketJSON.getString("ticket");
LOGGER.info("重新生成jsapTicket是:" + ticket);
wTicketVO.setTicket(ticket);
redisCache.hset(ticketKey, ticketKey, JSON.toJSONString(wTicketVO), Constants.REDIS_INVALID_TIME);
} else {
JSONObject jsApiTicketJSON = cWeChatClient.getTicket(accessToken);
LOGGER.info(jsApiTicketJSON.toJSONString());
ticket = jsApiTicketJSON.getString("ticket");
LOGGER.info("新生成jsapTicket是:" + ticket);
wTicketVO.setTicket(ticket);
redisCache.hset(ticketKey, ticketKey, JSON.toJSONString(wTicketVO), Constants.REDIS_INVALID_TIME);
}
return ticket;
}
@Override
@Transactional(rollbackFor = Exception.class)
public void saveMiniProgramUser(String openId,String unionId) {
UserInfo wechatUserInfo = new UserInfo();
wechatUserInfo.setWechatuserid(openId);
wechatUserInfo.setUnionId(unionId);
wechatUserInfo.setIsDeleted(Constants.DEL_FLAG);
List<UserInfo> userInfos = this.selectList(QueryUtil.condition(wechatUserInfo));
if (CollectionUtils.isEmpty(userInfos)) {
UserInfo userInfo = new UserInfo();
userInfo.setId(idGenerator.generate());
userInfo.setWechatuserid(openId);
userInfo.setUnionId(unionId);
// 小程序类型
userInfo.setUserType(4);
userInfo.setCreateTime(new Date());
userInfo.setUserType(Constants.DEL_FLAG);
this.insert(userInfo);
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean updateUserInfo(UserInfo userInfo) {
return this.baseMapper.updateUserInfoByWeChatId(userInfo.getNickname(),userInfo.getHeadimgurl(),userInfo.getWechatuserid());
}
/**
* 获取微信用户的信息
* @param accessToken
* @param weChatUserId
* @return
*/
public UserInfo getWeChatUserInfo(String accessToken,String weChatUserId){
JSONObject user = weChatClient.getUserInfo(accessToken, weChatUserId);
UserInfo userInfo = new UserInfo();
userInfo.setId(idGenerator.generate());
userInfo.setWechatuserid(user.getString("openid") != null ? user.getString("openid") : null);
userInfo.setNickname(user.getString("nickname") != null ? user.getString("nickname") : null);
userInfo.setProvince(user.getString("province") != null ? user.getString("province") : null);
userInfo.setCity(user.getString("city") != null ? user.getString("city") : null);
userInfo.setHeadimgurl(user.getString("headimgurl") != null ? user.getString("headimgurl") : null);
userInfo.setPrivilege(user.getString("privilege") != null ? user.getString("privilege") : null);
userInfo.setUnionId(user.getString("unionid") != null ? user.getString("unionid") : null);
userInfo.setCreateTime(new Date());
userInfo.setUserType(Constants.YES_FLAG);
return userInfo;
}
public UserInfo getCompanyUser(JSONObject userDetailJON) {
UserInfo userInfo = new UserInfo();
userInfo.setId(idGenerator.generate());
userInfo.setWechatuserid(userDetailJON.getString("userid"));
userInfo.setNickname(userDetailJON.getString("name"));
userInfo.setMobile(userDetailJON.getString("mobile"));
userInfo.setEmail(userDetailJON.getString("email"));
userInfo.setHeadimgurl(userDetailJON.getString("avatar"));
userInfo.setQrCode(userDetailJON.getString("qr_code"));
userInfo.setCreateTime(new Date());
userInfo.setUserType(Constants.DEL_FLAG);
return userInfo;
}
}
package com.yizhi.application.task;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yizhi.application.controller.UserInfoController;
import com.yizhi.application.domain.PublicPlatformConfig;
import com.yizhi.application.domain.TrAccountUserinfo;
import com.yizhi.application.domain.UserInfo;
import com.yizhi.application.feign.WeChatClient;
import com.yizhi.application.orm.id.IdGenerator;
import com.yizhi.application.orm.util.QueryUtil;
import com.yizhi.application.service.ITrAccountUserinfoService;
import com.yizhi.application.service.IUserInfoService;
import com.yizhi.system.application.system.remote.AccountClient;
import com.yizhi.core.application.task.AbstractTaskHandler;
import com.yizhi.core.application.task.TaskExecutor;
import com.yizhi.system.application.system.remote.OrganizationClient;
import com.yizhi.system.application.vo.AccountVO;
import com.yizhi.system.application.vo.WeChatUpdateOrganizationVo;
import com.yizhi.wechat.application.vo.wechat.Constants;
import com.yizhi.wechat.application.vo.wechat.WeChatUserVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
/**
* 更新用户信息
* 2020-2-10
*
* @author lingye
*/
@Component
public class UpdateUserInfoService {
private static final Logger LOGGER = LoggerFactory.getLogger(UpdateUserInfoService.class);
@Autowired
private AccountClient accountClient;
@Autowired
private TaskExecutor taskExecutor;
@Autowired
private UserInfoController userInfoController;
@Autowired
IdGenerator idGenerator;
@Autowired
private WeChatClient weChatClient;
@Autowired
private IUserInfoService userInfoService;
@Autowired
private ITrAccountUserinfoService trAccountUserinfoService;
@Autowired
private OrganizationClient remoteOrganizationClient;
/**
* 异步更新用户信息
*
* @param publicPlatformConfig
* @param accountUserInfo
*/
public void taskUpdateUserInfo(PublicPlatformConfig publicPlatformConfig, TrAccountUserinfo accountUserInfo) {
taskExecutor.asynExecute(new AbstractTaskHandler() {
@Override
public void handle() {
updateUserInfo(publicPlatformConfig, accountUserInfo);
}
});
}
private void updateUserInfo(PublicPlatformConfig publicPlatformConfig, TrAccountUserinfo accountUserInfo) {
LOGGER.info("异步更新用户信息===============start=============");
String accessToken = null;
try {
trAccountUserinfoService.autoUnBindWeChatAccount(accountUserInfo);
if (StringUtils.isNotEmpty(publicPlatformConfig.getAgentId())) {
LOGGER.info("异步更新用户信息公众号配置:" + publicPlatformConfig);
accessToken = userInfoController.getWeChatAccessToken(publicPlatformConfig);
LOGGER.info(" 获取企业的accessToken:" + accessToken);
// 查询用户的信息
WeChatUserVO weChatUserVO = userInfoController.getWechatUser(accessToken, accountUserInfo.getWechatuserid());
//更新用户信息
updateAccountInfo(accountUserInfo.getWechatuserid(), weChatUserVO.getAccountVO().getFullName(), weChatUserVO.getAccountVO().getHeadPortrait());
//更新部门
updateOrg(accountUserInfo, weChatUserVO);
}
} catch (Exception e) {
e.printStackTrace();
LOGGER.info("企业信息更新失败!{}", e.getMessage());
}
LOGGER.info("异步更新用户信息===============end=============");
}
/**
* //更新部门
*/
private void updateOrg(TrAccountUserinfo accountUserInfo, WeChatUserVO weChatUserVO) {
if (accountUserInfo == null || weChatUserVO == null) {
LOGGER.error("更新部门的必要vo参数为空:{}");
return;
}
Long companyId = accountUserInfo.getCompanyId();
Long accountId = accountUserInfo.getAccountId();
List<String> orgNames = weChatUserVO.getOrgNames();
if (companyId == null || accountId == null || CollectionUtils.isEmpty(orgNames)) {
LOGGER.error("更新部门的必要参数为空:{}" + companyId + "--" + accountId + "--" + orgNames);
return;
} else {
WeChatUpdateOrganizationVo vo = new WeChatUpdateOrganizationVo();
vo.setAccountId(accountId);
vo.setCompanyId(companyId);
vo.setOrgNames(orgNames);
LOGGER.info("更新部门的传参:{}" + JSON.toJSONString(vo));
String reason = remoteOrganizationClient.updateOrganization(vo).getReason();
LOGGER.info("更新部门的结果:{}" + reason);
}
}
/**
* 异步新增用户信息
*
* @param accessToken
* @param weChatUserId
*/
public void taskAddUserInfo(String accessToken, String weChatUserId, String unionId) {
taskExecutor.asynExecute(new AbstractTaskHandler() {
@Override
public void handle() {
addUserInfo(accessToken, weChatUserId, unionId);
}
});
}
private void addUserInfo(String accessToken, String weChatUserId, String unionId) {
try {
JSONObject userInfoJSON = weChatClient.getUserInfo(accessToken, weChatUserId);
LOGGER.info("用户详细信息{}", userInfoJSON);
int userCount = getUserCount(weChatUserId);
if (userCount == 0) {
addUser(userInfoJSON);
} else {
TrAccountUserinfo accountUserInfo = new TrAccountUserinfo();
accountUserInfo.setWechatuserid(weChatUserId);
accountUserInfo.setIsDeleted(Constants.DEL_FLAG);
List<TrAccountUserinfo> accountUserinfoList = trAccountUserinfoService.selectList(QueryUtil.condition(accountUserInfo));
if (CollectionUtils.isNotEmpty(accountUserinfoList)) {
TrAccountUserinfo trAccountUserinfo = accountUserinfoList.get(0);
AccountVO accountVO = new AccountVO();
accountVO.setId(trAccountUserinfo.getAccountId());
String headImage = userInfoJSON.getString("headimgurl");
String nickName = userInfoJSON.getString("nickname");
accountVO.setHeadPortrait(headImage);
Boolean updateAccountResult = accountClient.updateAccount(accountVO);
LOGGER.info("异步更新用用户头像:{}", (updateAccountResult ? "成功" : "失败"));
updateAccountInfo(weChatUserId, nickName, headImage);
}
}
} catch (Exception e) {
LOGGER.info("获取信用户的详情异常:{}", e.getLocalizedMessage());
}
}
public int getUserCount(String openId) {
UserInfo userInfo = new UserInfo();
userInfo.setWechatuserid(openId);
userInfo.setIsDeleted(Constants.DEL_FLAG);
int count = userInfoService.selectCount(QueryUtil.condition(userInfo));
return count;
}
@Transactional(rollbackFor = Exception.class)
public void addUser(JSONObject user) {
UserInfo userInfo = new UserInfo();
userInfo.setId(idGenerator.generate());
userInfo.setWechatuserid(user.getString("openid") != null ? user.getString("openid") : null);
userInfo.setNickname(user.getString("nickname") != null ? user.getString("nickname") : null);
userInfo.setProvince(user.getString("province") != null ? user.getString("province") : null);
userInfo.setCity(user.getString("city") != null ? user.getString("city") : null);
userInfo.setHeadimgurl(user.getString("headimgurl") != null ? user.getString("headimgurl") : null);
userInfo.setPrivilege(user.getString("privilege") != null ? user.getString("privilege") : null);
userInfo.setUnionId(user.getString("unionid") != null ? user.getString("unionid") : null);
userInfo.setCreateTime(new Date());
userInfo.setUserType(Constants.YES_FLAG);
boolean insertResult = userInfoService.insert(userInfo);
LOGGER.info("微信用户新增结果:{}", insertResult ? "成功" : "失败");
}
/**
* 新增企业用户
*
* @param userDetailJON
*/
public void taskAddCompanyUserInfo(JSONObject userDetailJON) {
taskExecutor.asynExecute(new AbstractTaskHandler() {
@Override
public void handle() {
saveCompanyUserInfo(userDetailJON);
}
});
}
/**
* 企业用户新增
*
* @param userDetailJON
*/
private void saveCompanyUserInfo(JSONObject userDetailJON) {
String userId = userDetailJON.getString("userid");
//异步修改用户信息
try {
int userCount = getCompanyUserCount(userId);
if (userCount == 0) {
addCompanyUser(userDetailJON);
}
} catch (Exception e) {
LOGGER.info("获取信用户的详情异常:{}", e.getLocalizedMessage());
}
}
public int getCompanyUserCount(String weChatUserId) {
UserInfo userInfo = new UserInfo();
userInfo.setWechatuserid(weChatUserId);
userInfo.setIsDeleted(Constants.DEL_FLAG);
int count = userInfoService.selectCount(QueryUtil.condition(userInfo));
return count;
}
@Transactional(rollbackFor = Exception.class)
public void addCompanyUser(JSONObject userDetailJON) {
UserInfo userInfo = new UserInfo();
userInfo.setId(idGenerator.generate());
userInfo.setWechatuserid(userDetailJON.getString("userid"));
userInfo.setNickname(userDetailJON.getString("name"));
userInfo.setMobile(userDetailJON.getString("mobile"));
userInfo.setEmail(userDetailJON.getString("email"));
userInfo.setHeadimgurl(userDetailJON.getString("avatar"));
userInfo.setQrCode(userDetailJON.getString("qr_code"));
userInfo.setCreateTime(new Date());
userInfo.setUserType(Constants.DEL_FLAG);
boolean insertResult = userInfoService.insert(userInfo);
LOGGER.info("企业微信用户新增结果:{}", insertResult);
}
/**
* 小程序 新增用户
*
* @param openId
*/
public void addMiniProgramUserInfo(String openId, String unionId) {
taskExecutor.asynExecute(new AbstractTaskHandler() {
@Override
public void handle() {
userInfoService.saveMiniProgramUser(openId, unionId);
}
});
}
public void taskUpdateMiniUserInfo(Long accountId, String headPortrait) {
taskExecutor.asynExecute(new AbstractTaskHandler() {
@Override
public void handle() {
updateMiniUserInfo(accountId, headPortrait);
}
});
}
private void updateMiniUserInfo(Long accountId, String headPortrait) {
try {
AccountVO accountVO = new AccountVO();
accountVO.setId(accountId);
accountVO.setHeadPortrait(headPortrait);
Boolean updateAccount = accountClient.updateAccount(accountVO);
LOGGER.info("异步小程序用户头像结果:{}", updateAccount ? "成功" : "失败");
} catch (Exception e) {
LOGGER.info("企业信息更新失败!{}", e.getMessage());
}
}
private void updateAccountInfo(String wechatUserId, String nickName, String headImgUrl) {
UserInfo userInfo = new UserInfo();
userInfo.setWechatuserid(wechatUserId);
userInfo.setHeadimgurl(headImgUrl);
userInfo.setNickname(nickName);
userInfoService.updateUserInfo(userInfo);
}
public void taskAddProviderUserInfo(UserInfo userInfo) {
taskExecutor.asynExecute(new AbstractTaskHandler() {
@Override
public void handle() {
try {
int userCount = getCompanyUserCount(userInfo.getWechatuserid());
userInfo.setUserType(5);
LOGGER.info("返回的结果 userCount:{}", userCount);
if (userCount == 0) {
boolean insert = userInfoService.insert(userInfo);
LOGGER.info("返回新增结果:{}", insert);
}
} catch (Exception e) {
LOGGER.info("获取信用户的详情异常:{}", e.getLocalizedMessage());
}
}
});
}
}
server.port=35045
spring.application.name=wechat
ACTIVE=${spring.profiles.active}
spring.profiles.active=sit
# nacos
spring.cloud.nacos.config.shared-dataids=common-${spring.profiles.active}.properties
spring.cloud.nacos.config.namespace=${spring.profiles.active}
spring.cloud.nacos.config.prefix=${spring.application.name}
spring.cloud.nacos.config.file-extension=properties
#spring.cloud.nacos.config.server-addr=192.168.1.22:3333
spring.cloud.nacos.config.server-addr=192.168.1.13:3333
\ No newline at end of file
import com.alibaba.fastjson.JSONObject;
import com.yizhi.application.feign.WeChatClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @Date 2021/1/8 1:55 下午
* @Author lvjianhui
**/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {WeChatClient.class})
public class TestWechat {
@Autowired
private WeChatClient weChatClient;
@Test
public void test() {
JSONObject json = weChatClient.getMenuInfo("--");
System.out.println(json);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.yizhi</groupId>
<artifactId>wmy-parent</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath/>
</parent>
<groupId>com.yizhi</groupId>
<artifactId>cloud-wechat</artifactId>
<version>1.0-SNAPSHOT</version>
<modules>
<module>cloud-wechat-api</module>
<module>cloud-wechat-service</module>
</modules>
<packaging>pom</packaging>
<dependencies>
</dependencies>
<repositories>
<repository>
<id>wmy4.0</id>
<url>http://mvn.km365.pw/nexus/content/groups/wmy4.0-group/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
</repositories>
</project>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment