小程序调用微信接口生成小程序码(Java后台)

前几天要求生成小程序二维码,网上找了很多资料,官方的文档,使用之后一直报错,感觉真的很坑,下面我把自己亲测可用的方法粘出来,方便大家使用

他这个微信接口返回的是一个流,这个咱们要自己处理一下,将他放到输入流里面,然后要用输出流处理一下,代码很完整,就是有点乱,见谅。

 

@RequestMapping(value="/getQRcode",method=RequestMethod.POST)
    @ResponseBody
    public Object getQRcode(HttpServletRequest request, HttpServletResponse response,String openid) throws WriterException, IOException{
        Map<String,Object> data = new HashMap<String,Object>();
        String APPID = appid;
        String SECRET = secret;
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ APPID +"&secret=" + SECRET;
        String json = HttpUtil.getInvoke(url);
        data.put("access_token",JSONObject.fromObject(json).get("access_token"));
        String scene = openid;//携带的参数
//        String page = "pages/invition/invition";
        String page = "pages/index/start";//要跳转的小程序页,小程序必须已经发布,如果没有发布,生成的小程序码错误,打不开,直接用txt打开,看一下错误码
        data = RQcodeUtil.getminiqrQr(scene, data.get("access_token").toString(),page,request,baseSavePath);
        return data;
    }

 

//我直接写到工具类里面了,代码有点多

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;

import com.alibaba.fastjson.JSON;

public class RQcodeUtil {

    public static Map<String,Object> getminiqrQr(String sceneStr, String accessToken,String page,HttpServletRequest request,String baseSavePath) {//保存路径
        Map<String, Object> data = new HashMap<>();
        String fileName = sceneStr +".jpg";  
        String returnUrl = request.getScheme() + "://"
                + request.getServerName() + request.getContextPath();
      //图片的存入路径
        String filePath=baseSavePath + "/images/qrcode/";
        //先判断文件是否存在
        File addNew =new File(filePath);
        //如果文件夹不存在则创建
        if(!addNew .exists()){
            addNew .mkdirs();
        }
        System.out.println("token为");
        System.out.println(accessToken);
        Map<String, Object> params = new HashMap<>();
        params.put("scene", sceneStr);//参数
        params.put("page", page);//要跳转的页面
        params.put("width", 430);//二维码宽度

        CloseableHttpClient  httpClient = HttpClientBuilder.create().build();

        HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
        String body = JSON.toJSONString(params);
        StringEntity entity;
        try {
            entity = new StringEntity(body);
            entity.setContentType("image/png");
            httpPost.setEntity(entity);
            HttpResponse response1;
            
            response1 = httpClient.execute(httpPost);
            InputStream inputStream = response1.getEntity().getContent();
            
            File targetFile = new File(filePath);  
            if(!targetFile.exists()){    
                targetFile.mkdirs();    
            }       
            FileOutputStream out = new FileOutputStream(filePath + fileName);
            
            byte[] buffer = new byte[8192];
            int bytesRead = 0;
            while((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            
            out.flush();
            out.close();
            data.put("img", "https://dzs.magorobot.com" + "/images/qrcode/" + fileName);
//            data.put("img", returnUrl + "/images/qrcode/" + fileName);
//            data.put("img", "http://wxs.tunnel.qydev.com/admin/img/test.png");
            return data;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return data;
    }
}


 

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值