123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267 |
- package com.caimei365.user.components;
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.JSONObject;
- import com.caimei365.user.model.JsonModel;
- import com.caimei365.user.utils.RequestUtil;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.commons.codec.binary.Base64;
- import org.apache.commons.lang.StringUtils;
- import org.bouncycastle.jce.provider.BouncyCastleProvider;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.http.HttpHeaders;
- import org.springframework.http.server.reactive.ServerHttpRequest;
- import org.springframework.stereotype.Component;
- import org.springframework.web.server.ServerWebExchange;
- import javax.crypto.Cipher;
- import javax.crypto.spec.IvParameterSpec;
- import javax.crypto.spec.SecretKeySpec;
- import java.security.AlgorithmParameters;
- import java.security.Security;
- import java.util.HashMap;
- import java.util.Map;
- /**
- * 微信 服务工具类
- *
- * @author : Charles
- * @date : 2021/3/9
- */
- @Slf4j
- @Component
- public class WeChatService {
- private String redirectUri;
- private String appId;
- private String appSecret;
- private String miniAppId;
- private String miniAppSecret;
- private String crmAppId;
- private String crmAppSecret;
- @Value("${wx.redirect-uri}")
- public void setRedirectUri(String redirectUri) {
- redirectUri = redirectUri;
- }
- @Value("${wx.app-id}")
- public void setAppId(String appId) {
- appId = appId;
- }
- @Value("${wx.app-secret}")
- public void setAppSecret(String appSecret) {
- appSecret = appSecret;
- }
- @Value("${wx.mini-app-id}")
- public void setMiniAppId(String miniAppId) {
- miniAppId = miniAppId;
- }
- @Value("${wx.mini-app-secret}")
- public void setMiniAppSecret(String miniAppSecret) {
- miniAppSecret = miniAppSecret;
- }
- @Value("${wx.crm-app-id}")
- public void setCrmAppId(String crmAppId) {
- crmAppId = crmAppId;
- }
- @Value("${wx.crm-app-secret}")
- public void setCrmAppSecret(String crmAppSecret) {
- crmAppSecret = crmAppSecret;
- }
- public String getRedirectUri() {
- return redirectUri;
- }
- public String getAppId() {
- return appId;
- }
- public String getAppSecret() {
- return appSecret;
- }
- public String getMiniAppId() {
- return miniAppId;
- }
- public String getMiniAppSecret() {
- return miniAppSecret;
- }
- public String getCrmAppId() {
- return crmAppId;
- }
- public String getCrmAppSecret() {
- return crmAppSecret;
- }
- static {
- // BouncyCastle是一个开源的加解密解决方案
- Security.addProvider(new BouncyCastleProvider());
- }
- /**
- * AES解密
- *
- * @param data 密文,被加密的数据
- * @param key 秘钥
- * @param iv 偏移量
- * @param encodingFormat 解密后的结果需要进行的编码
- * @return 解密结果
- */
- public static String decrypt(String data, String key, String iv, String encodingFormat) throws Exception {
- // 被加密的数据
- byte[] dataByte = Base64.decodeBase64(data);
- // 加密秘钥
- byte[] keyByte = Base64.decodeBase64(key);
- // 偏移量
- byte[] ivByte = Base64.decodeBase64(iv);
- try {
- Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
- SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
- AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
- parameters.init(new IvParameterSpec(ivByte));
- // 初始化
- cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
- byte[] resultByte = cipher.doFinal(dataByte);
- if (null != resultByte && resultByte.length > 0) {
- return new String(resultByte, encodingFormat);
- }
- return null;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
- /**
- * 小程序微信授权登录,获取openid
- *
- * @param code 微信凭证
- * @param serverWebExchange ServerWebExchange
- * @return HashMap
- */
- public JsonModel<Map<String, Object>> getInfoMapByApplets(String code, ServerWebExchange serverWebExchange) {
- log.info("Start get SessionKey");
- Map<String, Object> returnMap = new HashMap<>(4);
- // 获取当前微信小程序的环境
- ServerHttpRequest request = serverWebExchange.getRequest();
- HttpHeaders headers = request.getHeaders();
- String referer = headers.getFirst("Referer");
- log.info("referer-is----:" + referer);
- returnMap.put("referer", referer);
- String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
- Map<String, String> requestUrlParam = new HashMap<String, String>(4);
- // 小程序appId
- requestUrlParam.put("appId", miniAppId);
- log.info("appId: ---" + miniAppId);
- // 小程序appSecret
- requestUrlParam.put("appSecret", miniAppSecret);
- // 小程序端返回的code
- requestUrlParam.put("code", code);
- // 默认参数
- requestUrlParam.put("grantType", "authorization_code");
- // 发送post请求读取调用微信接口获取openid用户唯一标识
- String infos;
- try {
- infos = RequestUtil.sendPost(requestUrl, requestUrlParam);
- } catch (Exception e) {
- return JsonModel.error("服务器内部异常", returnMap);
- }
- // 解析相应内容(转换成json对象)
- JSONObject jsonObject = JSON.parseObject(infos);
- String openId = jsonObject.getString("openid");
- String unionId = jsonObject.getString("unionid");
- String sessionKey = jsonObject.getString("session_key");
- String errCode = jsonObject.getString("errcode");
- String errMsg = jsonObject.getString("errmsg");
- log.info("openId----->" + openId +", unionId------>" + unionId);
- returnMap.put("openId", openId);
- returnMap.put("unionId", unionId);
- returnMap.put("sessionKey", sessionKey);
- boolean errFlag = StringUtils.isNotEmpty(errCode) && ("-1".equals(errCode) || "40029".equals(errCode) || "45011".equals(errCode));
- if (errFlag) {
- return JsonModel.error(-1, errMsg, returnMap);
- }
- return JsonModel.success(returnMap);
- }
- /**
- * 微信公众号授权链接(www)
- * @param redirectUri 用于微信授权的中间页面
- * @param mode 授权方式:1静默授权,其他手动同意授权
- * @return newRedirectUri
- */
- public String getAuthorizationLink(String redirectUri, Integer mode) {
- String link = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
- // 应用唯一标识
- link = link.replace("APPID", crmAppId);
- // 中间页连接
- link = link.replace("REDIRECT_URI", redirectUri);
- if (mode == 1) {
- // 静默授权
- link = link.replace("snsapi_userinfo", "snsapi_base");
- }
- return link;
- }
- /**
- * 网页授权登录,通过code获取openid
- * @param code 微信code
- * @param source 来源
- * @return
- */
- public Map<String, Object> getInfoMapByWeb(String code, String source) throws Exception {
- String link = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
- if ("pc".equals(source)) {
- // 应用唯一标识
- link = link.replace("APPID", appId);
- // 应用密钥AppSecret,在微信开放平台提交应用审核通过后获得
- link = link.replace("SECRET", appSecret);
- } else {
- //微信公众号
- link = link.replace("APPID", crmAppId);
- link = link.replace("SECRET", crmAppSecret);
- }
- // 获取的code参数
- link = link.replace("CODE", code);
- // 发送授权链接,得到微信用户信息
- String result = RequestUtil.sendGet(link);
- log.info(result);
- Map<String, Object> map = JSONObject.parseObject(result, Map.class);
- return map;
- }
- /**
- * 微信公众号获取access_token
- * @return access_token
- */
- public String getAccessToken() throws Exception {
- String link = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
- link = link.replace("APPID", crmAppId);
- link = link.replace("APPSECRET", crmAppSecret);
- String result = RequestUtil.sendGet(link);
- log.info("微信公众号获取access_token>>>" + result);
- Map<String, Object> map = JSONObject.parseObject(result, Map.class);
- return (String) map.get("access_token");
- }
- /**
- * 微信公众号获取用户信息
- * @return
- */
- public Map<String, Object> getUserInfo(String accessToken, String openid) throws Exception {
- String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openid + "&lang=zh_CN";
- String userInfo = RequestUtil.sendGet(requestUrl);
- log.info("微信公众号授权用户数据>>>>>>>>>>>" + userInfo);
- Map<String, Object> map = JSONObject.parseObject(userInfo, Map.class);
- return map;
- }
- }
|