MiniProgramServiceImpl.java 12.9 KB
Newer Older
shenggui.li committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
package com.reyun.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.reyun.controller.manage.MngMiniProgramController;
import com.reyun.model.*;
import com.reyun.repository.AccountRepository;
import com.reyun.repository.AppRepository;
import com.reyun.repository.CampaignRepository;
import com.reyun.repository.ChannelRepository;
import com.reyun.service.CampaignService;
import com.reyun.service.MiniProgramService;
import com.reyun.util.AwsS3Util;
import com.reyun.util.Constant;
import com.reyun.util.ObjectStorageUtil;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.io.IOUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.*;

@SuppressWarnings("SpringAutowiredFieldsWarningInspection")
@Service
public class MiniProgramServiceImpl implements MiniProgramService {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(MngMiniProgramController.class);
    private static final String S3_DOWNLOAD_BUCKET = Constant.bucket;
    private static final String DOWNLOAD_PATH = "trackingio/reportdownload/";
    private static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${user_appid}&secret=${user_secret}";
    private static final String GET_MINI_CODE_URL = "https://api.weixin.qq.com/wxa/getwxacode?access_token=${access_token}";
    private static final String GET_MINI_QR_CODE_URL = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=${access_token}";

    @Autowired
    private AppRepository appRepository;

    @Autowired
    private AccountRepository accountRepository;

    @Autowired
    private CampaignRepository campaignRepository;

    @Autowired
    private CampaignService campaignService;

    @Autowired
    private ChannelRepository channelRepository;

    @Override
    public HashMap<Integer, String> generateAccessToken(App resource) {
        String url = GET_ACCESS_TOKEN_URL.replace("${user_appid}", resource.getMipAppid()).replace("${user_secret}", resource.getMipSecret());
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(url);
        HashMap<Integer, String> map = new HashMap<>();
        try {
            httpClient.executeMethod(getMethod);
            String responseBody = getMethod.getResponseBodyAsString();

            if (getMethod.getStatusCode() == HttpStatus.SC_OK && responseBody != null && !"".equals(responseBody)) {
                JSONObject jsonObject = JSONObject.parseObject(responseBody);
                Integer errcode = jsonObject.getInteger("errcode");
                String access_token = jsonObject.getString("access_token");
                if (errcode != null) {
                    map.put(errcode, jsonObject.getString("errmsg"));
                } else {
                    map.put(200, access_token);
                }
            }
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            getMethod.releaseConnection();
        }
        return map;
    }

    @Override
    public Boolean appidValid(Long loginAccount, String mipAppid) {
        Account one = accountRepository.findOne(loginAccount);
        List<App> bymipAppid = appRepository.findBymipAppid(one.getRootParent(), mipAppid);
        return bymipAppid.size() <= 0;
    }


    @Override
    public Map<Integer, String> getQrCode(App app, Long cid, String page, String type, String surl) {

        Map<Integer, String> tokenResult = this.generateAccessToken(app);

        if (tokenResult.containsKey(200)) {
            String accesstoken = tokenResult.get(200);
            app.setAccessToken(accesstoken);
            app.setTokenValid(true);
            appRepository.save(app);

            HashMap<Integer, String> map = new HashMap<>();
            String fileName = "mini_program" + "_" + app.getAppkey() + "_" + cid + "_" + type + "_" + new Date().getTime() + ".jpeg";
            String shenmaDownloadDir = Constant.SHENMA_DOWNLOAD_DIR;
            InputStream inputStream;
            OutputStream outputStream = null;
            HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
            String postUrl = "";
            String requestBody = "";

            if ("miniCode".equals(type)) {
                postUrl = GET_MINI_CODE_URL.replace("${access_token}", accesstoken);
                if(page==null){
                    page="";
                }
                requestBody = "{" + "\"path\":\"" + page + "?" + "cid=" + cid + "&surl=" + surl + "\"" + "}";
            } else if ("miniQrCode".equals(type)) {
                postUrl = GET_MINI_QR_CODE_URL.replace("${access_token}", accesstoken);
                requestBody = "{" + "\"path\":\"" + page + "?" + "cid=" + cid + "&surl=" + surl + "\"" + "}";
            }

            try {
                PostMethod postMethod = new PostMethod(postUrl);
                StringRequestEntity requestEntity = new StringRequestEntity(requestBody, "application/json", "UTF-8");
                postMethod.setRequestEntity(requestEntity);
                try {
                    httpClient.executeMethod(postMethod);
                    if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
                        Header responseHeader = postMethod.getResponseHeader("content-type");
                        if (responseHeader != null && !responseHeader.getValue().equals("image/jpeg")) {
                            String errorMessage = postMethod.getResponseBodyAsString();
                            logger.error("请求小程序码失败:\r\n" + "appKey=" + app.getAppkey() + "  cid=" + cid + "  errorMessage=" + errorMessage);
                            map.put(201, errorMessage);
                        } else {
                            inputStream = postMethod.getResponseBodyAsStream();
                            File file = new File(shenmaDownloadDir + fileName);
                            try {
                                outputStream = new FileOutputStream(file);
                                int len;
                                byte[] buf = new byte[1024];
                                while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                                    outputStream.write(buf, 0, len);
                                    outputStream.flush();
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                                map.put(201, e.getMessage());
                                logger.error(e.getMessage());
                            } finally {
                                try {
                                    inputStream.close();
                                    if (outputStream != null) {
                                        outputStream.close();
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                    logger.error(e.getMessage());
                                    map.put(201, e.getMessage());
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    map.put(201, e.getMessage());
                    logger.error(e.getMessage());
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                logger.error(e.getMessage());
                map.put(201, e.getMessage());
            }

            String filePath = Constant.SHENMA_DOWNLOAD_DIR + fileName;
            File file = new File(filePath);
            if (file.exists()) {
                try {
                    FileInputStream in = new FileInputStream(filePath);
                    final String s3key = DOWNLOAD_PATH + fileName;
                    ObjectStorageUtil.putObjectInStream(S3_DOWNLOAD_BUCKET, s3key, in, "jpeg", file.length());
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.error(e.getMessage());
                    map.put(201, e.getMessage());
                }
            }
            map.put(200, fileName);
            return map;
        } else {
            Map<Integer, String> map = new HashMap<>();
            map.put(201, tokenResult.values().toString());
            return map;
        }
    }

    @Override
    public ResponseEntity<byte[]> downloadQrCode(Long id) {
        Campaign one = campaignRepository.findOne(id);

        final String s3key = DOWNLOAD_PATH + one.getQrCodeAddress();

        String fileName = one.getQrCodeAddress();

        InputStream in = null;
        byte[] content;
        String fileType = "image/jpeg";
        try {
            in = ObjectStorageUtil.getObjectContentStream(S3_DOWNLOAD_BUCKET, s3key);
            content = IOUtils.toByteArray(in);

            HttpHeaders headers = new HttpHeaders();
            headers.set("filename", fileName);
            headers.add("content-disposition", "attachment; filename=" + fileName);
            headers.add("Content-Type", fileType);
            return new ResponseEntity<>(content, headers, org.springframework.http.HttpStatus.CREATED);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(in);
        }
        return null;
    }

    @Override
    public List<Channel> listChannel(Account loginAccount, Long appid, String type) {

        Iterable<Campaign4Web> result = campaignService.listAuthCampaignByType(loginAccount, appid, type, false);
        List<Campaign4Web> res = campaignService.listCampaignByLink(result);

        HashSet<Long> set = new HashSet<>();
        for (Campaign4Web campaign4Web : res) {
            if (campaign4Web.getChannel() != null) {
                Channel one = channelRepository.findOne(campaign4Web.getChannel());
                set.add(one.getId());
            }
        }

        ArrayList<Long> ids = new ArrayList<>(set);

        return channelRepository.findById(ids);
    }

    @Override
    public HashMap<Integer, String> checkAppValid(Long appid, Account loginAccount) {
        HashMap<Integer, String> map = new HashMap<>();
        Integer integer = campaignRepository.findbyMipType("miniQrCode", appid);
        if (integer > 100000) {
            map.put(211, "创建的小程序二维码数量超过限制(100000条)");
        }
        App one = appRepository.findOne(appid);
        if (!(one.getTokenValid() != null && one.getTokenValid())) {
            map.put(212, one.getTokenMessage()==null?"token无效":one.getTokenMessage());
        }
        return map;
    }

    @Override
    public ResponseEntity<byte[]> impression(Long id) {
        Campaign one = campaignRepository.findOne(id);

        final String s3key = DOWNLOAD_PATH + one.getQrCodeAddress();
        String fileName = one.getQrCodeAddress();
        InputStream in = null;
        byte[] content;
        String fileType = "image/jpeg";
        try {
            in = ObjectStorageUtil.getObjectContentStream(S3_DOWNLOAD_BUCKET, s3key);
            content = IOUtils.toByteArray(in);
            HttpHeaders headers = new HttpHeaders();
            headers.set("filename", fileName);
            headers.add("Content-Type", fileType);
            return new ResponseEntity<>(content, headers, org.springframework.http.HttpStatus.CREATED);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(in);
        }
        return null;
    }

    public static void main(String[] args) {
        MiniProgramServiceImpl miniProgramService = new MiniProgramServiceImpl();
        App app = new App();
        String accessToken = "11_XUyUQgOuNS_ByVexHUmGnEbFB7liYtjTq8XA68Xx1fVSZruGGHsESOdP9C3hTI7UiJCJKhpNNHXx9hMH9FCwm6s0xZr4gOLasRS8asYIExANhxlJd3xiGST1odOToLskTiBrC3ecZJjqpsahWVZgADAGFJ";
        String appkey = "e6e155dfd3ab045322caf94439f6bd9d";
        app.setAccessToken(accessToken);
        app.setAppkey(appkey);
        Map<Integer, String> miniCode = miniProgramService.getQrCode(app, 514L, "pages/index/index", "miniCode", "fy6R3ea");
        System.out.println(miniCode);
        Map<Integer, String> miniQrCode = miniProgramService.getQrCode(app, 514L, "pages/index/index", "miniQrCode", "fy6R3ea");
        System.out.println(miniQrCode);
    }
}