Ver Fonte

[update] message:

kelei há 6 meses atrás
pai
commit
1f0ac2a6f0

+ 13 - 0
admin/pom.xml

@@ -44,6 +44,19 @@
             <artifactId>aliyun-sdk-oss</artifactId>
             <version>3.12.0</version>
         </dependency>
+
+        <dependency>
+            <groupId>com.squareup.okhttp3</groupId>
+            <artifactId>okhttp</artifactId>
+            <version>3.10.0</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.qiniu</groupId>
+            <artifactId>qiniu-java-sdk</artifactId>
+            <version>7.13.0</version>
+        </dependency>
+
     </dependencies>
 
     <build>

+ 1 - 1
admin/src/main/java/com/flyer/foster/dto/AppUserQueryDTO.java

@@ -10,7 +10,7 @@ import lombok.Data;
  */
 @Data
 public class AppUserQueryDTO {
-    private String gardenId;
+    private Integer gardenId;
 
     private String code;
 }

+ 2 - 0
admin/src/main/java/com/flyer/foster/dto/AppUserRespDTO.java

@@ -37,4 +37,6 @@ public class AppUserRespDTO {
     private String icon;
 
     private String appId;
+
+    private String token;
 }

+ 1 - 0
admin/src/main/java/com/flyer/foster/service/impl/AppUserServiceImpl.java

@@ -64,6 +64,7 @@ public class AppUserServiceImpl extends ServiceImpl<IAppUserMapper, AppUser> imp
             appUser.setCreatedTime(LocalDateTime.now());
             appUser.setUpdatedBy("kelei");
             appUser.setUpdatedTime(LocalDateTime.now());
+            appUser.setGardenId(dto.getGardenId());
             this.save(appUser);
         }
         AppUserRespDTO respDTO = new AppUserRespDTO();

+ 47 - 1
admin/src/main/java/com/flyer/foster/service/impl/GardenServiceImpl.java

@@ -6,17 +6,25 @@ import cn.hutool.core.util.StrUtil;
 import com.baomidou.mybatisplus.core.metadata.IPage;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import com.flyer.exception.BusinessException;
+import com.flyer.foster.consts.WechatConst;
 import com.flyer.foster.dto.*;
 import com.flyer.foster.entity.Area;
 import com.flyer.foster.entity.Garden;
 import com.flyer.foster.mapper.IGardenMapper;
 import com.flyer.foster.service.IAreaService;
 import com.flyer.foster.service.IGardenService;
+import com.flyer.foster.util.HttpUtils;
+import com.flyer.foster.util.WeChatApiUtil;
+import com.flyer.foster.util.WxAccessToken;
+import okhttp3.Response;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 
+import java.io.IOException;
+import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 import java.util.stream.Collectors;
 
 /**
@@ -32,6 +40,12 @@ public class GardenServiceImpl extends ServiceImpl<IGardenMapper, Garden> implem
     @Autowired
     private IAreaService iAreaService;
 
+    @Autowired
+    private WeChatApiUtil weChatApiUtil;
+
+    @Autowired
+    private QiniuUploadService qiniuUploadService;
+
     @Override
     public IPage<GardenRespDTO> getPageList(IPage<GardenRespDTO> page, GardenQueryDTO queryDTO) {
         IPage<GardenRespDTO> pageList = baseMapper.getPageList(page, queryDTO);
@@ -53,7 +67,39 @@ public class GardenServiceImpl extends ServiceImpl<IGardenMapper, Garden> implem
         Garden garden = new Garden();
         garden.setTenantId(tenantId);
         BeanUtil.copyProperties(addDTO, garden);
-        return this.save(garden);
+        this.save(garden);
+        // 生成二维码
+        String qrCode = this.generateQRCode(garden.getId());
+
+        return this.lambdaUpdate()
+                .set(Garden::getQrCode, qrCode)
+                .eq(Garden::getId, garden.getId()).update();
+    }
+
+    /**
+     * 生成小程序二维码
+     *
+     * @param gardenId 果园id
+     */
+    private String generateQRCode(Integer gardenId) {
+        WxAccessToken wxAccessToken = WxAccessToken.getInstance(weChatApiUtil, WechatConst.APP_ID, WechatConst.APP_SECRET);
+        StringBuilder sb2 = new StringBuilder(200);
+        sb2.append("https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=");
+        sb2.append(wxAccessToken.getAccess_token());
+        Map<String, String> params = new HashMap<>();
+        params.put("path", "/pages/subPages/task_executor/index?recordAllotId=" + gardenId);
+        params.put("width", "180");
+        Response response = HttpUtils.getResponse(sb2.toString(), params);
+        if (response.isSuccessful()) {
+            String key = "birdseye-look-mini/temp/" + System.currentTimeMillis() + "_" + gardenId + ".jpg";
+            try {
+                qiniuUploadService.upload(qiniuUploadService.uploadToken(), key, response.body().bytes());
+                return key;
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+        return "";
     }
 
     @Transactional

+ 42 - 0
admin/src/main/java/com/flyer/foster/service/impl/QiniuUploadService.java

@@ -0,0 +1,42 @@
+package com.flyer.foster.service.impl;
+
+import com.google.gson.Gson;
+import com.qiniu.common.QiniuException;
+import com.qiniu.http.Response;
+import com.qiniu.storage.Configuration;
+import com.qiniu.storage.Region;
+import com.qiniu.storage.UploadManager;
+import com.qiniu.storage.model.DefaultPutRet;
+import com.qiniu.util.Auth;
+import org.springframework.stereotype.Service;
+
+@Service
+public class QiniuUploadService {
+    static String accessKey = "mIKp5GQq1-DF_ORXexDpok4pSa6Xn6LM_OlcH50Y";
+    static String secretKey = "9ubgRioyPaLh9Jnec9y1jN4qysRZVvX8TzLiYlHb";
+    static String bucket = "birdseye";
+
+    //构造一个带指定 Region 对象的配置类
+    Configuration cfg = new Configuration(Region.huanan());
+    //...其他参数参考类注释
+    UploadManager uploadManager = new UploadManager(cfg);
+
+    public String uploadToken(){
+        //默认不指定key的情况下,以文件内容的hash值作为文件名
+        Auth auth = Auth.create(accessKey, secretKey);
+        //...生成上传凭证,然后准备上传
+        String upToken = auth.uploadToken(bucket);
+        return upToken;
+    }
+
+    public void upload(String upToken,String key, byte[] file){
+        try {
+            Response response = uploadManager.put(file, key, upToken);
+            //解析上传成功的结果
+            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
+            System.out.println(Thread.currentThread().getName() + " : " + putRet.key);
+        } catch (QiniuException ex) {
+            ex.printStackTrace();
+        }
+    }
+}

+ 168 - 0
admin/src/main/java/com/flyer/foster/util/HttpUtils.java

@@ -0,0 +1,168 @@
+package com.flyer.foster.util;
+
+import com.alibaba.fastjson.JSON;
+import okhttp3.*;
+
+import javax.servlet.http.HttpServletRequest;
+import java.io.IOException;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+public class HttpUtils {
+    public static String getHeader(HttpServletRequest request, String key){
+        return request.getHeader(key);
+    }
+
+    /**
+     * 同步访问
+     * @param address
+     * @param paramsMap
+     * @return
+     */
+    public  static String httpPost(String address, Map<String,String> paramsMap) {
+        OkHttpClient client = new OkHttpClient().newBuilder()
+                .connectTimeout(15, TimeUnit.SECONDS)
+                .readTimeout(15, TimeUnit.SECONDS)
+                .writeTimeout(15, TimeUnit.SECONDS)
+//                .sslSocketFactory(new SSLSocketClient().getSSLSocketFactory())//配置
+//                .hostnameVerifier(new SSLSocketClient().getHostnameVerifier())//配置    //忽略验证证书
+                .build();
+        MediaType type = MediaType.parse("application/json;charset=utf-8");
+        RequestBody requestBody=RequestBody.create(type, JSON.toJSONString(paramsMap));
+        Request request = new Request.Builder()
+                .url(address).post(requestBody)
+                .build();
+        try {
+            Response response = client.newCall(request).execute();
+            if(response.isSuccessful()){
+                return response.body().string();
+            }else{
+                System.out.println(address + "错误码:"+response.code());
+            }
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+    /**
+     * 同步访问
+     * @param address
+     * @param paramsMap
+     * @return
+     */
+    public  static Response  getResponse(String address, Map<String,String> paramsMap) {
+        OkHttpClient client = new OkHttpClient().newBuilder()
+                .connectTimeout(15, TimeUnit.SECONDS)
+                .readTimeout(15, TimeUnit.SECONDS)
+                .writeTimeout(15, TimeUnit.SECONDS)
+//                .sslSocketFactory(new SSLSocketClient().getSSLSocketFactory())//配置
+//                .hostnameVerifier(new SSLSocketClient().getHostnameVerifier())//配置    //忽略验证证书
+                .build();
+        MediaType type = MediaType.parse("application/json;charset=utf-8");
+        RequestBody requestBody=RequestBody.create(type, JSON.toJSONString(paramsMap));
+        Request request = new Request.Builder()
+                .url(address).post(requestBody)
+                .build();
+        try {
+            return client.newCall(request).execute();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+    /**
+     * 同步访问
+     * @param address
+     * @param json
+     * @return
+     */
+    public  static String httpJsonPost(String address, String json) {
+        OkHttpClient client = new OkHttpClient().newBuilder()
+                .connectTimeout(15, TimeUnit.SECONDS)
+                .readTimeout(15, TimeUnit.SECONDS)
+                .writeTimeout(15, TimeUnit.SECONDS)
+//                .sslSocketFactory(new SSLSocketClient().getSSLSocketFactory())//配置
+//                .hostnameVerifier(new SSLSocketClient().getHostnameVerifier())//配置    //忽略验证证书
+                .build();
+
+        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
+        Request request = new Request.Builder()
+                .url(address).post(body)
+                .build();
+        try {
+            Response response = client.newCall(request).execute();
+            if(response.isSuccessful()){
+                return response.body().string();
+            }else{
+                System.out.println(address + "错误码:"+response.code());
+            }
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+    /**
+     * 同步访问
+     * @param address
+     * @param json
+     * @return
+     */
+    public  static String httpJsonPost(String address, String json, Headers headers) {
+        OkHttpClient client = new OkHttpClient().newBuilder()
+                .connectTimeout(15, TimeUnit.SECONDS)
+                .readTimeout(15, TimeUnit.SECONDS)
+                .writeTimeout(15, TimeUnit.SECONDS)
+//                .sslSocketFactory(new SSLSocketClient().getSSLSocketFactory())//配置
+//                .hostnameVerifier(new SSLSocketClient().getHostnameVerifier())//配置    //忽略验证证书
+                .build();
+
+        RequestBody body = RequestBody.create(MediaType.parse("application/json;"), json);
+        Request request = new Request.Builder()
+                .url(address).post(body).headers(headers)
+                .build();
+
+        try {
+            Response response = client.newCall(request).execute();
+            if(response.isSuccessful()){
+                return response.body().string();
+            }else{
+                System.out.println(address + "错误码:"+response.code());
+            }
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+    /**
+     * 同步访问
+     * @param address
+     * @return
+     */
+    public  static String httpGet(String address) {
+        OkHttpClient client = new OkHttpClient().newBuilder()
+                .connectTimeout(15, TimeUnit.SECONDS)
+                .readTimeout(15, TimeUnit.SECONDS)
+                .writeTimeout(15, TimeUnit.SECONDS)
+                .build();
+
+        Request request = new Request.Builder()
+                .url(address).get()
+                .build();
+        try {
+            Response response=  client.newCall(request).execute();
+            if(response.isSuccessful()){
+                return response.body().string();
+            }else{
+                return null;
+            }
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+}

+ 22 - 26
admin/src/main/java/com/flyer/foster/util/WeChatApiUtil.java

@@ -61,7 +61,7 @@ public class WeChatApiUtil {
      *
      * @return
      */
-    public String getAccessToken(String appId, String secret) {
+    public JSONObject getAccessToken(String appId, String secret) {
         String accessToken = null;
         String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type={grantType}&appid={appId}&secret={secret}";
         HashMap<String, String> map = new HashMap<>();
@@ -72,34 +72,30 @@ public class WeChatApiUtil {
         JSONObject res;
         try {
             res = restTemplate.getForObject(url, JSONObject.class, map);
-            if (res != null) {
-                accessToken = String.valueOf(res.get("access_token"));
-            }
         } catch (RestClientException e) {
             throw new BusinessException("调用微信服务错误");
         }
-
-        return accessToken;
+        return res;
     }
 
-    public String getPhoneNumber(String appId, String appSecret, String code) {
-        String accessToken = this.getAccessToken(appId, appSecret);
-        String tel = "";
-        String url = StrUtil.format("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={}", accessToken);
-        try {
-            HttpHeaders headers = new HttpHeaders();
-            headers.setContentType(MediaType.APPLICATION_JSON);
-            HashMap<String, String> bodyParams = new HashMap<>();
-            bodyParams.put("code", code);
-            // 用HttpEntity封装整个请求报文
-            HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(bodyParams, headers);
-            JSONObject res = restTemplate.postForObject(url, httpEntity, JSONObject.class);
-            if (res != null) {
-                tel = res.getJSONObject("phone_info").getString("phoneNumber");
-            }
-        } catch (RestClientException e) {
-            throw new BusinessException("调用微信服务错误");
-        }
-        return tel;
-    }
+//    public String getPhoneNumber(String appId, String appSecret, String code) {
+//        String accessToken = this.getAccessToken(appId, appSecret);
+//        String tel = "";
+//        String url = StrUtil.format("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={}", accessToken);
+//        try {
+//            HttpHeaders headers = new HttpHeaders();
+//            headers.setContentType(MediaType.APPLICATION_JSON);
+//            HashMap<String, String> bodyParams = new HashMap<>();
+//            bodyParams.put("code", code);
+//            // 用HttpEntity封装整个请求报文
+//            HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(bodyParams, headers);
+//            JSONObject res = restTemplate.postForObject(url, httpEntity, JSONObject.class);
+//            if (res != null) {
+//                tel = res.getJSONObject("phone_info").getString("phoneNumber");
+//            }
+//        } catch (RestClientException e) {
+//            throw new BusinessException("调用微信服务错误");
+//        }
+//        return tel;
+//    }
 }

+ 46 - 0
admin/src/main/java/com/flyer/foster/util/WxAccessToken.java

@@ -0,0 +1,46 @@
+package com.flyer.foster.util;
+
+import com.alibaba.fastjson.JSONObject;
+import lombok.Data;
+
+import java.time.LocalDateTime;
+
+/**
+ * 获取 WX 单例 AccessToken
+ */
+@Data
+public class WxAccessToken {
+
+    private static WxAccessToken instance;
+
+
+    public static WxAccessToken getInstance(WeChatApiUtil weChatApiUtil, String appId, String secret){
+        if(instance != null && !instance.isExpires()){
+            return instance;
+        }
+        JSONObject obj= weChatApiUtil.getAccessToken(appId, secret);
+        instance = new WxAccessToken();
+        instance.expires_in = obj.getInteger("expires_in");
+        instance.expires = LocalDateTime.now().plusSeconds(instance.expires_in - 100);
+        instance.access_token = obj.getString("access_token");
+        return instance;
+    }
+
+    /**
+     * 判断当期token是否过期
+     * @return
+     */
+    private boolean isExpires(){
+        return LocalDateTime.now().isAfter(instance.expires);
+    }
+
+
+    private WxAccessToken(){}
+
+    private LocalDateTime expires;
+    private String access_token;
+    private Integer expires_in;
+
+
+
+}

+ 1 - 1
admin/src/main/resources/application-dev.yml

@@ -40,7 +40,7 @@ sa-token:
   # token 名称(同时也是 cookie 名称)
   token-name: token
   # token 有效期(单位:秒) 默认30天,-1 代表永久有效
-  timeout: 86400
+  timeout: 2592000
   # token 最低活跃频率(单位:秒),如果 token 超过此时间没有访问系统就会被冻结,默认-1 代表不限制,永不冻结
   active-timeout: -1
   # 是否允许同一账号多地同时登录 (为 true 时允许一起登录, 为 false 时新登录挤掉旧登录)