Java生成微信小程序二维码上传阿里云返回路径

Java生成微信小程序二维码上传阿里云返回路径

1.先在yml配置微信参数

wx:
  appid: XXXXX
  appsecret: XXXXX

2.WXcode配置类

package com.yl.base.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.yl.util.config.OSSConfig;
import lombok.extern.log4j.Log4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * author: tianyuqing
 * Date: 2020/11/1016:29
 **/
@Log4j
public class WXCode {

    private static final String OSS_PATH = "http://zhenlian-web.oss-cn-beijing.aliyuncs.com/";
    private static final String FILE_PATH = "xcxCode";
    private static final String WX_CODE_URL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=";//小程序生成二维码接口路径

    /**
     * 用于获取access_token
     * @return  access_token
     * @throws Exception
     */
    public static String postToken(String apiId,String secretKey) throws Exception {
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+apiId+"&secret="+secretKey;
        URL url = new URL(requestUrl);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.writeBytes("");
        out.flush();
        out.close();

        // 建立实际的连接
        connection.connect();
        // 定义 BufferedReader输入流来读取URL的响应
        BufferedReader in = null;
        if (requestUrl.contains("nlp"))
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
        else
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        String result = "";
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result += getLine;
        }
        in.close();
        JSONObject jsonObject = JSON.parseObject(result);
        String accesstoken=jsonObject.getString("access_token");
        return accesstoken;
    }

    /**
     * 上传微信小程序二维码返回路径
     * @param map 二维码生成格式
     * @param fileName 图片id
     * @return
     */
    public static String getWxCodeUrl(Map<String,Object> map,String fileName,String apiId,String secretKey) {
        RestTemplate rest = new RestTemplate();
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            //获取accessToken
            String accessToken = postToken(apiId, secretKey);
            String url = WX_CODE_URL+accessToken;
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            //设置格式
            HttpEntity requestEntity = new HttpEntity(map, headers);
            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
            //返回图片
            byte[] result = entity.getBody();
            inputStream = new ByteArrayInputStream(result);

            //上传阿里云
            OSSClient ossClient = new OSSClient(OSSConfig.endpoint, OSSConfig.accessKeyId, OSSConfig.accessKeySecret);
            ossClient.putObject(OSSConfig.bucketName, FILE_PATH + "/" +fileName+".png",inputStream);
            ossClient.shutdown();
            log.info("生成微信二维码成功");
            return OSS_PATH + FILE_PATH + "/" + fileName+".png";

 			/**
 			//保存本地
 			File file = new File("C:/Users/Administrator/Desktop/1.png");
            if (!file.exists()){
                file.createNewFile();
            }
            outputStream = new FileOutputStream(file);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();**/
        } catch (Exception e) {
            e.printStackTrace();
            log.info("生成微信二维码失败"+e);
        } finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值