• 微信小程序生成带参二维码


    场景:实现微信小程序中的海报功能,海报中有一个通过扫码跳转到自己小程序的二维码,用户保存海报到本地在朋友圈分享后就可以通过扫码进入小程序。

    • 生成二维码工具类代码如下:
      1 package com.aone.foottalk.action.wx.util;
      2 
      3 import java.io.File;
      4 import java.io.FileOutputStream;
      5 //import java.io.IOException;
      6 import java.io.InputStream;
      7 import java.util.HashMap;
      8 import java.util.Map;
      9 
     10 //import org.apache.commons.io.IOUtils;
     11 import org.apache.http.HttpResponse;
     12 import org.apache.http.client.methods.HttpPost;
     13 import org.apache.http.entity.StringEntity;
     14 import org.apache.http.impl.client.CloseableHttpClient;
     15 import org.apache.http.impl.client.HttpClientBuilder;
     16 import org.apache.http.protocol.HTTP;
     17  
     18 import com.alibaba.fastjson.JSON;
     19 //import com.aone.foottalk.action.back.image.ImgTAction;
     20 //import com.aone.foottalk.common.QiniuUtil;
     21 
     22 import net.sf.json.JSONObject;
     23 /**
     24  * 二维码工具
     25  * @author 开发
     26  *
     27  */
     28 public class AUtil {
     29     
     30     public static String getminiqrQr(String neirong,String tzdz) throws Exception{
     31         String dizhi="";//返回给前端的地址
     32         /*************获取小程序token值*******************/
     33         String access_token ="";
     34         // 小程序(商城)
     35         String appId = "***************";
     36         String secret = "***************";
     37         String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret;
     38         JSONObject json = CommonUtil.httpsRequest(url, "GET", null);
     39         if (null != json) {
     40             access_token=json.getString("access_token");
     41         }
     42         System.out.println("token"+access_token);
     43         /********************************/
     44         Map<String, Object> params = new HashMap<>();
     45         params.put("scene", neirong);
     46         params.put("page", "pages"+"/"+tzdz+"/"+tzdz);
     47         params.put("width", 430);
     48         
     49         CloseableHttpClient  httpClient = HttpClientBuilder.create().build();
     50         HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token);
     51         httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
     52         String body = JSON.toJSONString(params);
     53         StringEntity entity;
     54         entity = new StringEntity(body);
     55         entity.setContentType("image/png");
     56         httpPost.setEntity(entity);
     57         
     58         HttpResponse response;
     59         response = httpClient.execute(httpPost);
     60         InputStream inputStream = response.getEntity().getContent();
     61         /**===========================上传七牛==================================**/
     62         /*try {
     63             byte[] data = IOUtils.toByteArray(inputStream);
     64             Map<String, String> map = QiniuUtil.upload(data, neirong);
     65             String code = map.get("code");
     66             if ("200".equals(code)) {
     67                 System.out.println(map.get("path"));
     68                 dizhi=map.get("path");
     69                 System.out.println("地址:"+dizhi);
     70             }
     71         } catch (IOException ex) {
     72             System.out.println(ImgTAction.class.getName() + "has thrown an exception: " + ex.getMessage());
     73         } finally {
     74             try {
     75                 inputStream.close();
     76             } catch (IOException ignored) {
     77 
     78             }
     79         }*/
     80         /**============================保存到本地=================================**/  
     81         File targetFile = new File("/photo");  
     82         if(!targetFile.exists()){    
     83             targetFile.mkdirs();    
     84         }       
     85         FileOutputStream out = new FileOutputStream("/888.png");
     86 
     87         byte[] buffer = new byte[8192];
     88         int bytesRead = 0;
     89         while((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
     90             out.write(buffer, 0, bytesRead);
     91         }
     92         out.flush();
     93         out.close();
     94         return dizhi;
     95     }
     96     
     97     public static void main(String args[]){
     98         try {
     99             getminiqrQr("333","index");
    100         } catch (Exception e) {
    101             // TODO Auto-generated catch block
    102             e.printStackTrace();
    103         }
    104     }
    105 }
    View Code
    • 通用工具类:
      1 package com.aone.foottalk.action.wx.util;
      2 
      3 import java.io.BufferedReader;
      4 import java.io.InputStream;
      5 import java.io.InputStreamReader;
      6 import java.io.OutputStream;
      7 import java.net.ConnectException;
      8 import java.net.URL;
      9 import java.util.Formatter;
     10 
     11 import javax.net.ssl.HttpsURLConnection;
     12 import javax.net.ssl.SSLContext;
     13 import javax.net.ssl.SSLSocketFactory;
     14 import javax.net.ssl.TrustManager;
     15 
     16 import net.sf.json.JSONObject;
     17 
     18 import org.slf4j.Logger;
     19 import org.slf4j.LoggerFactory;
     20 
     21 /**
     22  * 通用工具类
     23  * @author 开发
     24  *
     25  */
     26 public class CommonUtil {
     27     private static Logger log = LoggerFactory.getLogger(CommonUtil.class);
     28 
     29     // 凭证获取(GET)
     30     public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
     31 
     32     /**
     33      * 发送https请求
     34      * 
     35      * @param requestUrl 请求地址
     36      * @param requestMethod 请求方式(GET、POST)
     37      * @param outputStr 提交的数据
     38      * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     39      */
     40     public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
     41         JSONObject jsonObject = null;
     42         try {
     43             // 创建SSLContext对象,并使用我们指定的信任管理器初始化
     44             TrustManager[] tm = { new MyX509TrustManager() };
     45             SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
     46             sslContext.init(null, tm, new java.security.SecureRandom());
     47             // 从上述SSLContext对象中得到SSLSocketFactory对象
     48             SSLSocketFactory ssf = sslContext.getSocketFactory();
     49 
     50             URL url = new URL(requestUrl);
     51             HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
     52             conn.setSSLSocketFactory(ssf);
     53             
     54             conn.setDoOutput(true);
     55             conn.setDoInput(true);
     56             conn.setUseCaches(false);
     57             // 设置请求方式(GET/POST)
     58             conn.setRequestMethod(requestMethod);
     59 
     60             // 当outputStr不为null时向输出流写数据
     61             if (null != outputStr) {
     62                 OutputStream outputStream = conn.getOutputStream();
     63                 // 注意编码格式
     64                 outputStream.write(outputStr.getBytes("UTF-8"));
     65                 outputStream.close();
     66             }
     67 
     68             // 从输入流读取返回内容
     69             InputStream inputStream = conn.getInputStream();
     70             InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
     71             BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
     72             String str = null;
     73             StringBuffer buffer = new StringBuffer();
     74             while ((str = bufferedReader.readLine()) != null) {
     75                 buffer.append(str);
     76             }
     77 
     78             // 释放资源
     79             bufferedReader.close();
     80             inputStreamReader.close();
     81             inputStream.close();
     82             inputStream = null;
     83             conn.disconnect();
     84             jsonObject = JSONObject.fromObject(buffer.toString());
     85         } catch (ConnectException ce) {
     86             log.error("连接超时:{}", ce);
     87         } catch (Exception e) {
     88             log.error("https请求异常:{}", e);
     89         }
     90         return jsonObject;
     91     }
     92     
     93     /**
     94      * 方法名:byteToHex</br>
     95      * 详述:字符串加密辅助方法 </br>
     96      * 开发人员:souvc  </br>
     97      * 创建时间:2016-1-5  </br>
     98      * @param hash
     99      * @return 说明返回值含义
    100      * @throws 说明发生此异常的条件
    101      */
    102     public static String byteToHex(final byte[] hash) {
    103         Formatter formatter = new Formatter();
    104         for (byte b : hash) {
    105             formatter.format("%02x", b);
    106         }
    107         String result = formatter.toString();
    108         formatter.close();
    109         return result;
    110     }
    111 }
    View Code
    1. 目前根据已发布小程序的appId与secret所获取的token可以下载到带参的二维码图片,但是没发布的没法得到小程序二维码图片。
    2. 小程序下载二维码需要https的图片地址,但是七牛目前是http的,图片保存地址需要处理。
  • 相关阅读:
    C++Vector使用方法
    Struts2学习笔记1
    全排列算法及实现
    概率图模型(PGM)学习笔记(三)模式判断与概率图流
    SQLite的SQL语法
    马云入股恒大背后暗藏四大隐情?
    ListView的优化
    通过WriteProcessMemory改写进程的内存
    “富豪相亲大会”究竟迷失了什么?
    Java实现 蓝桥杯VIP 算法提高 密码锁
  • 原文地址:https://www.cnblogs.com/LJing21/p/10191984.html
Copyright © 2020-2023  润新知