JAVA生成带参数的小程序码,根据文件路径下载文件

生成小程序码并下载:
1、获取小程序全局唯一后台接口调用凭据 access_token
2、生成小程序码并通过fastdfs-client将小程序码输出到文件服务器上
3、根据文件路径下载文件选择文件夹保存

调用凭据 access_token

/**
 * 微信工具类
 */
public class WeixinUtil {

    private static PayConfigSingleton configuration = PayConfigSingleton.getInstance();

    public static void main(String[] args) throws UnsupportedEncodingException {
    }

    /**
     * 从配置文件里面获取数据
     */
    public static String getAccessTokenFromProperites(String subsiteFlag) throws FileNotFoundException, IOException {
        String tokenAccessPath = WeixinUtil.class.getResource("/").getPath() + "tokenAccess.properties";
        Properties properties = new Properties();
        properties.load(new FileInputStream(new File(tokenAccessPath)));
        return properties.getProperty(subsiteFlag);
    }
    @SuppressWarnings("unchecked")
    public static List<Node> getNodesFromXml(String xml, String xpath) {
        try {
            Document document = DocumentHelper.parseText(xml);
            List<Node> nodeList = document.selectNodes(xpath);
            return nodeList;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 微信授权
     *
     * @param code
     * @param isSilence
     * @return { "access_token":"ACCESS_TOKEN",  "expires_in":7200, "refresh_token":"REFRESH_TOKEN",
     * "openid":"OPENID", "scope":"SCOPE"  }
     */
    public static Map<String, String> weixinOAuth(String code, boolean isSilence) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        url = url.replace("APPID", configuration.getWeixinAppId())
                .replace("SECRET", configuration.getWeixinAppSecret())
                .replace("CODE", code);
        try {
            String result = HttpUtil.get(url, "UTF-8");
            System.out.println("微信授权:" + result);
            return JSONObject.parseObject(result, Map.class);
            } catch (Exception e) {  e.printStackTrace(); }
        return null;
    }

    /**
     * 微信第三方授权
     *
     * @param code
     * @param isSilence
     * @return {  "access_token":"ACCESS_TOKEN", "expires_in":7200,  "refresh_token":"REFRESH_TOKEN",
     * "openid":"OPENID", "scope":"SCOPE" * }
     */
    public static Map<String, String> weixinLoginOAuth(String code, boolean isSilence) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=GRANTTYPE";
        url = url.replace("APPID", configuration.getWeixinLoginAppid())
                .replace("SECRET", configuration.getWeixinLoginAppSecret())
                .replace("CODE", code);
        if (isSilence) { url = url.replace("GRANTTYPE", "snsapi_base"); }
        else { url = url.replace("GRANTTYPE", "authorization_code"); }
        try {
            String result = HttpUtil.get(url, "UTF-8");
            System.out.println("微信授权:" + result);
            return JSONObject.parseObject(result, Map.class);
            } catch (Exception e) { e.printStackTrace(); }
        return null;
    }

    /**
     * 微信小程序授权
     *
     * @param code
     * @param isSilence
     * @return { "access_token":"ACCESS_TOKEN",  "expires_in":7200, "refresh_token":"REFRESH_TOKEN",
     * "openid":"OPENID", "scope":"SCOPE"  }
     */
    public static Map<String, String> weixinXcxOAuth(String code, boolean isSilence) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
        url = url.replace("APPID", configuration.getWeixinAppletAppId())
                .replace("SECRET", configuration.getWeixinAppletSecret())
                .replace("JSCODE", code);
        try {
            String result = HttpUtil.get(url, "UTF-8");
            System.out.println("微信授权:" + result);
            return JSONObject.parseObject(result, Map.class);
        } catch (Exception e) {  e.printStackTrace(); }
        return null;
    }


    /**
     * 获取小程序全局唯一后台接口调用凭据
     *
     * @return { "access_token":"ACCESS_TOKEN",  "expires_in":7200, "errcode":"errcode",
     * "errmsg":"errmsg" }
     */
    public static Map<String, String> weixinXcxAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
        url = url.replace("APPID", configuration.getWeixinAppletAppId())
                .replace("APPSECRET", configuration.getWeixinAppletSecret());
        try {
            String result = HttpUtil.get(url, "UTF-8");
            System.out.println("小程序全局唯一后台接口调用凭据:" + result);
            return JSONObject.parseObject(result, Map.class);
        } catch (Exception e) {  e.printStackTrace(); }
        return null;
    }

    /**
     * 获取微信授权后用户信息
     *
     * @param accessToken
     * @param openId
     * @return
     */
    public static Map<String, String> wechatUserInfo(String accessToken, String openId) {
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
        url = url.replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        try {
            String result = HttpUtil.get(url, "UTF-8");
            System.out.println("输出的jeson格式=====:"+JSONObject.parseObject(result, Map.class));
            return JSONObject.parseObject(result, Map.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

二维码生成Util

/**
 * 二维码工具类
 */
public class QrCodeUtil {
	/***
	 * @description 生成小程序码并通过fastdfs-client将小程序码输出到文件服务器上
	 * @author wyc
	 * @data 2021/1/27 9:40
	 * @param sceneStr
	 * @param page
	 * @param accessToken
	 * @return fdfsFileId:文件路径 eg:/group1/M00/01/10/dDf7E2ARGBiAHw4LAAGwxwyBAow993.jpg
	 */
	public static String getminiqrQr(String sceneStr,String page, String accessToken) {
		String fdfsFileId = null;
		RestTemplate rest = new RestTemplate();
		try {
			String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
			JSONObject json = new JSONObject();
			json.put("scene",sceneStr);
			json.put("page",page);
			json.put("width",430);
			System.out.println("调用生成微信URL接口传参:" + json);
			MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
			HttpEntity requestEntity = new HttpEntity(json, headers);
			//发送请求
			ResponseEntity<byte[]> response = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
			System.out.println(response);
			byte[] result = response.getBody();
			System.out.println(Base64.encodeBase64(result));

			//使用fastdfs-client将小程序码输出到文件服务器上
			try {
				ClientGlobal.initByProperties("fastdfs-client.properties");
			} catch (MyException e) {
				e.printStackTrace();
			}
			TrackerClient tracker = new TrackerClient();
			TrackerServer trackerServer = tracker.getConnection();
			StorageServer storageServer = tracker.getStoreStorage(trackerServer, "group1");
			StorageClient1 client = new StorageClient1(trackerServer, storageServer);
			NameValuePair[] metaList = new NameValuePair[1];
			metaList[0] = new NameValuePair("fileName", "1.jpg");
			fdfsFileId = client.upload_file1(result, "jpg", metaList);
			System.out.println(fdfsFileId);
		} catch (Exception e) {
			System.out.println("调用小程序生成微信永久小程序码URL接口异常"+e);
		}
		return fdfsFileId;
	}

	/***
	 * @description 根据文件名称和文件路径以流的形式输出,自己选择文件夹保存
	 * @author wyc
	 * @data 2021/2/1 9:47
	 * @param fileName 文件名称
	 * @param filePath 文件真实路径  eg:http:wj.100good.cn/group1/M00/01/10/dDf7E2ARGBiAHw4LAAGwxwyBAow993.jpg
	 * @return
	 */
	public static void downLoadFile(HttpServletRequest request, HttpServletResponse response, String fileName, String filePath) throws IOException{
		String showAndDownUrl= ResourceUtil.getConfigByName("showAndDownUrl");
		filePath = "http:"+showAndDownUrl+filePath;
		InputStream fis = null;
		try {
			// 构造URL
			URL url = new URL(filePath);
			// 打开连接
			URLConnection con = url.openConnection();
			// 输入流
			fis = con.getInputStream();
			request.setCharacterEncoding("UTF-8");
			String agent = request.getHeader("User-Agent").toUpperCase();
			if ((agent.indexOf("MSIE") > 0) || ((agent.indexOf("RV") != -1) && (agent.indexOf("FIREFOX") == -1)))
				fileName = URLEncoder.encodePathParam(fileName, "UTF-8");
			else {
				fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
			}
			response.reset();
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/force-download");// 设置强制下载不打开
			response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
			//response.setHeader("Content-Length", String.valueOf(file.length()));
			byte[] b = new byte[1024];
			int len;
			while ((len = fis.read(b)) != -1) {
				response.getOutputStream().write(b, 0, len);
			}
			response.flushBuffer();
			fis.close();
		}catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

}

后台调用生成小程序码Util

    /**
     * 生成小程序码
     * @auth wyc
     * @data 2021/1/27 13:45
     * @param request
     * @return
     */
    @RequestMapping(params = "createErWeima")
    @ResponseBody
    public AjaxJson createErWeima(HttpServletRequest request) {
        String message = "操作成功!";
        AjaxJson j = new AjaxJson();
        String  fdfsFileId=null;
        try {
            String objectId = request.getParameter("objectId");
            MallItemEntity mallItem = mallItemService.getMallItemById(Long.parseLong(objectId));
            String scene = "objectId="+objectId+"&cid="+mallItem.getCid()+"&typeId=1";
            Map<String, String> map = new HashMap<>();
            //获取小程序凭证accessToken
            map = WeixinUtil.weixinXcxAccessToken();
            if(map!=null){
                //生成小程序码并通过fastdfs-client将小程序码输出到文件服务器上
                fdfsFileId= QrCodeUtil.getminiqrQr(scene,"xpages/shop/shop",map.get("access_token"));
                if(StringUtil.isNotEmpty(fdfsFileId)){
                    //将小程序码文件id保存至对应产品中
                    if (StringUtil.isNotEmpty(objectId)) {
                        //封装小程序码附件信息并保存
                        TCommonFileEntity tCommonFileEntity = new TCommonFileEntity();
                        tCommonFileEntity.setFileName(mallItem.getItemName());
                        tCommonFileEntity.setPath(fdfsFileId);
                        tCommonFileEntity.setExt("jpg");
                        tCommonFileEntity.setEnable(BigDecimal.ONE);
                        final Serializable fileId;
                        try {
                            fileId= tCommonFileService.save(tCommonFileEntity);
                        } catch (Exception e) {
                            e.printStackTrace();
                            logger.error(e.getMessage());
                            j.setSuccess(false);
                            return j;
                        }

                    }
                }else{
                    j.setSuccess(false);
                    message = "生成小程序码错误,请联系开发商";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            j.setSuccess(false);
            message = "发生异常,请联系开发商!";
        }
        j.setMsg(message);
        j.setObj(fdfsFileId);
        return j;
    }
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值