java调用小程序接口生成二维码以流的形式返回给前端

因为我也是小程序的初学者,看官网的API看了好久都没看懂,所以把我理解的记下来了,希望这篇对大家有帮助
微信官网小程序二维码API:https://developers.weixin.qq.com/miniprogram/dev/api/qrcode.html

一、获取access_token

package com.smart.visitor.web.api;


import com.smart.visitor.model.entity.Enterprise;
import com.smart.visitor.model.service.EnterpriseService;
import com.smart.visitor.util.GetScene;
import com.smart.visitor.util.GetWebAccessToken;
import org.apache.commons.lang.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;


import java.util.List;
import java.util.Map;

import static com.sun.xml.internal.ws.api.message.Packet.State.ServerResponse;

/**
 * 企业的Controller
 */

@RequestMapping("/enterprise")
@RestController
public class EnterpriseController extends BaseController {
    /**
     * 根据企业id生成二维码
     *
     * @param id
     * @param
     * @throws IOException
     */
    @GetMapping(value = "/download-qrCode")
    public void downloadQrCode(@RequestParam(value = "id") String id,
                               HttpServletResponse response) throws Exception {
        //获取AccessToken
        String accessToken = GetWebAccessToken.postToken();
        byte[] qrCodeBytes = null;
        Map paraMap = new HashMap();
        String url="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=";
        url+=accessToken;
        //二维码携带参数 不超过32位 参数类型必须是字符串
        paraMap.put("scene", id);  //存入的参数
        qrCodeBytes=GetScene.getminiqrQr(url,paraMap);
        response.setContentType("image/jpg");
        // 写入response的输出流中
        OutputStream stream = response.getOutputStream();
        stream.write(qrCodeBytes);
        stream.flush();
        stream.close();


    }
}

package com.smart.visitor.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Description: 用于获取access_token
 * @Author: 张楚涵
 * @Date: 2019/10/15 0015 8:41
 * @version:1.0.0
 */
public class GetWebAccessToken {
    /**
     * 用于获取access_token
     * @return
     * @throws Exception
     */
  //  @Scheduled(cron = "0 0 0/1 * * ? *")
    public static String postToken() throws Exception {
        String APIKEY = "wxa5fda3a16dabd4a5";//小程序id
        String SECRETKEY = "9f1dda45d93d30b204264c1a1f2b178c";//小程序密钥
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+APIKEY+"&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");
        System.out.println("********************************"+accesstoken);
        return accesstoken;
    }

}

二、生成小程序码

package com.smart.visitor.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

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

/**
 * @Description: 生成带参小程序二维码 (注意导包)
 * @Author: 张楚涵
 * @Date: 2019/10/15 0015 8:42
 * @version:1.0.0
 */
public class GetScene {
    /**
     * 生成带参小程序二维码
     *
     * @param
     * @param url
     * @return
     */
    public static byte[] getminiqrQr(String url, Map paraMap) throws Exception {
        byte[] result = null;
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json");

        // 设置请求的参数
        JSONObject postData = new JSONObject();
        for (Map.Entry entry : paraMap.entrySet()) {
            postData.put(entry.getKey(), entry.getValue());
        }
        httpPost.setEntity(new StringEntity(postData.toString(), "UTF-8"));
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toByteArray(entity);
        return result;


    }

}

代码亲测可用,有不完善的地方请留言。
url访问地址: localhost:8080/enterprise//download-qrCode

你可能感兴趣的:(程序)