JAVA 微信小程序 获取二维码

微信小程序获取二维码的三种方式

1.官方文档有介绍获取二维码的,这里主要介绍JAVA怎么获取。
2.微信小程序二维码 官方地址
3.小程序获取的图片样式其实是有差异的;一种是我们熟悉的二维码,一种就是小程序码了;具体可根据需求选择。

获取二维码的前提是必须获取小程序的TOKEN

获取 access_token 详见文档


/**
  * 获取token
  * @param url
  * @param grantType
  * @param appid
  * @param secret
  * @return
  */
 public static String getAccessToken(String url,String grantType,String appid,String secret){
     String access_token = "";
     String tokenUrl = url+"?grant_type="+ grantType+"&appid="+ appid + "&secret="+ secret;
     Object result = HttpUtils.doGet(tokenUrl);
     JSONObject jsons = JSONObject.parseObject(result.toString());
     String expires_in = jsons.getString("expires_in");
     if(BL3Utils.isNotEmpty(expires_in)&&Integer.parseInt(expires_in)==7200){
         //ok
         access_token = jsons.getString("access_token");
     }else{
         System.out.println("出错获取token失败!");
     }
     return access_token;
 }

参数介绍:

  1. url :https://api.weixin.qq.com/cgi-bin/token
  2. grantType: client_credential
  3. appid:小程序appid,微信公众平台注册小程序时自动生成的。
  4. secret:小程序secret,微信公众平台注册小程序时自动生成的。

url 和grantType参数官网其实有介绍的。


获取小程序二维码

  1. 适用于需要的码数量较少的业务场景
  2. 总共生成的码数量限制为100,000,请谨慎调用。

/**
 *  获取小程序二维码
 * @param url 官方获取二维码地址
 * @param width 二维码的宽度 int类型 默认 430
 * @param access_token 
 * @param path
 * @return
 */
  public static InputStream createwxaqrcode(String url,String access_token,String path,String width){
      url = url + "?access_token=" + access_token;
      JSONObject jsonParam = new JSONObject();
      jsonParam.put("path", path);
      jsonParam.put("width", width);
      InputStream instreams = doWXPost(url, jsonParam);
     if(BL3Utils.isEmpty(instreams)){
         System.out.println("出错获取二维码失败!");
     }
     return instreams;
 }
/**
 *  请求
 * @param url 
 * @param jsonParam
 * @return
 */
 public static InputStream doWXPost(String url, JSONObject jsonParam) {
        InputStream instreams = null;
        HttpPost httpRequst = new HttpPost(url);// 创建HttpPost对象
        try {
            StringEntity se = new StringEntity(jsonParam.toString(),"utf-8");
            se.setContentType("application/json");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"UTF-8"));
            httpRequst.setEntity(se);
            HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequst);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = httpResponse.getEntity();
                if (httpEntity != null) {
                    instreams = httpEntity.getContent();
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return instreams;
    }

参数介绍:
1. url : https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode
2. access_token:上面有介绍(getAccessToken这个方法)
3. path:用户扫描该码进入小程序后,将直接进入 path 对应的页面;一般是首页地址”pages/index/index” 也可以带上参数 “pages/index/index?query=1”。
4. width:二维码的宽度 int类型 默认 430。

/* @param instreams 二进制流
 * @param imgPath 图片的保存路径
 * @param fileName 图片的名称
 * @return str 图片保存地址
 */
public static String saveToImgByInputStream(InputStream instreams,String imagePath,String fileName){
    String str = "";
    String path = "QRimage" + getWFileDirName();
    String linuxPath = path.replaceAll("//",File.separator);
    if(instreams != null){
        boolean b =uploadImages(instreams,imagePath+File.separator+linuxPath, fileName);
        if(b){
            str =linuxPath+fileName;
        }
    }
    return str;
}

参数介绍

 1. instreams: 上面有介绍(createwxaqrcode这个方法)
 2. imagePath:保存图片的地址
 3. fileName:图片自定义名称(可以自定义 比如:1.jpg、1.png等)。

/**
 * IO流保存图片
 * @param instreams
 * @param imagePath
 * @param fileName
 * @return
 */
public static boolean uploadImages( InputStream instreams,String imagePath,String fileName) {
    File f = new File(imagePath);
    f.setWritable(true, false);
    boolean flag = false;
    try {
        // 1K的数据缓冲
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流
        File file = new File(imagePath,fileName);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
            try {
                // 创建新文件
                file.createNewFile();
            } catch (IOException e) {
                System.out.println("创建新文件时出现了错误。。。");
                e.printStackTrace();
            }
        }
        OutputStream os = new FileOutputStream(imagePath+File.separator+fileName);
        // 开始读取
        while ((len = instreams.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        // 完毕,关闭所有链接
        os.close();
        instreams.close();
        flag = true;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return flag;
}

直接使用下面的代码就可以获取到二维码地址了

String qrcodeUrl = saveToImgByInputStream(instreams,imagePath,fileName);

获取小程序码

目前有两个接口可以生成小程序码,开发者可以根据自己的需要选择合适的接口

第一种

  1. 适用于需要的码数量较少的业务场景
  2. 总共生成的码数量限制为100,000,请谨慎调用。

/**
 1. 带参数有限个数小程序码接口
 2. @param url
 3. @param access_token
 4. @param path
 5. @param width
 6. @return
 */
 public static InputStream getwxacode(String url,String access_token,String path,String width){
     url = url + "?access_token=" + access_token;
     JSONObject jsonParam = new JSONObject();
     jsonParam.put("path", path);
     jsonParam.put("width", Integer.parseInt(width));
     jsonParam.put("auto_color", false);
     Map<String,Object> line_color = new HashMap<>();
     line_color.put("r", 0);
     line_color.put("g", 0);
     line_color.put("b", 0);
     jsonParam.put("line_color", line_color);
     InputStream instreams = HttpUtils.doWXPost(url, jsonParam);
     if(BL3Utils.isEmpty(instreams)){
         System.out.println("出错获取二维码失败!");
     }
     return instreams;
 }

参数说明

  1. url : https://api.weixin.qq.com/wxa/getwxacode
  2. access_token:上面有介绍(getAccessToken这个方法)
  3. path:用户扫描该码进入小程序后,将直接进入 path 对应的页面;一般是首页地址:”pages/index/index” 也可以带上参数:”pages/index/index?query=1”。
  4. width:二维码的宽度 int类型 默认 430

第二种

  1. 适用于需要的码数量极多的业务场景
  2. 没有数量限制

/**
  * 带参数无限个数小程序码接口
  * @param url
  * @param access_token
  * @param path
  * @param width
  * @return
  */
  public static InputStream getwxacodeunlimit(String url,String access_token,String path,String width){
      String[] str = path.split("[?]");
      path = str[0];
      String scene = str[1];
      url = url + "?access_token=" + access_token;
      // 接收参数json列表
      JSONObject jsonParam = new JSONObject();
      jsonParam.put("scene", scene);
      jsonParam.put("page", path);
      jsonParam.put("width", Integer.parseInt(width));
      jsonParam.put("auto_color", false);
      Map<String,Object> line_color = new HashMap<>();
      line_color.put("r", 0);
      line_color.put("g", 0);
      line_color.put("b", 0);
      jsonParam.put("line_color", line_color);
      InputStream instreams = HttpUtils.doWXPost(url, jsonParam);
      if(BL3Utils.isEmpty(instreams)){
          System.out.println("出错获取二维码失败!");
      }
      return instreams;
  }

参数说明

  1. url : https://api.weixin.qq.com/wxa/getwxacodeunlimit
  2. access_token:上面有介绍(getAccessToken这个方法)
  3. path:用户扫描该码进入小程序后,将直接进入 path 对应的页面;一般是首页地址”pages/index/index” 也可以带上参数:”pages/index/index?query=1”。
  4. width:二维码的宽度 int类型 默认 430

注意:

  1. 第二种生成小程序码的情况 只有小程序上线后才能生成二维码。
  2. 其他方法生成的码只有小程序上线后才会有权限访问 否则会提示小程序尚未发布
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值