微信生成二维码(带参数scene)

参考微信文档,这是最主要的,一切以这个为主
微信生成二维码参考文档

下面是Controller层

/**
	* 接收二维码
	* @param request
	* @return
	* @throws IOException 
	*/

	@ApiResponses(value = { @ApiResponse(code = 100, message = "请求成功") })
	@ApiOperation(value = "接收二维码")
	@PostMapping(value="/twoCode")
	public Object twoCode(@RequestBody TwoCodeParameters twoCodeParameters,HttpServletRequest request) {
		// 获取accessToken
		String accessToken = TwoCode.getToken();
		// 获取图片地址
		String imageUrl = TwoCode.getminiqrQr(accessToken, twoCodeParameters,request);
		// 返回地址给前端
		JSONObject data = new JSONObject();
		data.put("imageUrl",imageUrl);
		return data;
	}

下面的是两个工具类,仅供参考

package com.bixin.user.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;

public class WXUrlUtil {

    /** 
         * 向指定 URL 发送POST方法的请求 
         * 
         * @param url 发送请求的 URL 
         * @param param 请求参数 
         * @return 所代表远程资源的响应结果 
         */

    public static String sendPost(String url, Map paramMap) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        String param = "";
        Iterator it = paramMap.keySet().iterator();
        while(it.hasNext()) {
            String key = it.next();
            param += key + "=" + paramMap.get(key) + "&";
        }
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接 
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性 
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行 
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流 
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数 
            out.print(param);
            // flush输出流的缓冲 
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应 
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        //使用finally块来关闭输出流、输入流 
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;

    }
}


package com.bixin.user.util;

import com.alibaba.fastjson.JSONObject;
import com.bixin.user.model.TwoCodeParameters;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map;

public class TwoCode {
    /*
     * 获取 token
   * 普通的 get 可获 token
     */
    public static String getToken() {
        try {
            Map map = new LinkedHashMap();
            map.put("grant_type", "client_credential");
            map.put("appid", "改成自己的appid");//
            map.put("secret", "改成自己的secret");
            String rt = WXUrlUtil.sendPost("https://api.weixin.qq.com/cgi-bin/token", map);
            System.out.println("what is:" + rt);

            JSONObject json = JSONObject.parseObject(rt);

            if (json.getString("access_token") != null || json.getString("access_token") != "") {
                return json.getString("access_token");

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


    /*
     * 获取 二维码图片
   * 
     */
    public static String getminiqrQr(String accessToken, TwoCodeParameters twoCodeParameters,HttpServletRequest request) {



        String codeUrl = "D:\\imageTest\\"+twoCodeParameters.getExtensionId()+".jpg";
        String twoCodeUrl = "http://192.168.31.213:8020/images/"+twoCodeParameters.getExtensionId()+".jpg";


        try {
            URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数

            JSONObject paramJson = new JSONObject();
            long timeMillis = System.currentTimeMillis();
//            paramJson.put("scene",  "extensionId="+twoCodeParameters.getExtensionId()+"&extensionType="+twoCodeParameters.getExtensionType());
            paramJson.put("scene",  twoCodeParameters.getExtensionId()  +"&"+ twoCodeParameters.getExtensionType());
            paramJson.put("page", "pages/views/vip-center");
            paramJson.put("width", 430);
            paramJson.put("is_hyaline", false);
            //line_color生效
            paramJson.put("auto_color", false);
            JSONObject lineColor = new JSONObject();
            lineColor.put("r", 0);
            lineColor.put("g", 0);
            lineColor.put("b", 0);
            paramJson.put("line_color", lineColor);

            printWriter.write(paramJson.toString());
            // flush输出流的缓冲
            printWriter.flush();
            //开始获取数据
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            OutputStream os = new FileOutputStream(new File(codeUrl));
            int len;
            byte[] arr = new byte[1024];
            while ((len = bis.read(arr)) != -1) {
                os.write(arr, 0, len);
                os.flush();
            }
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return twoCodeUrl;
    }


}


还有一个映射穿透配置类(当然也可以在配置文件里做配置,下面会给一张图)

package com.bixin.user.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class GHCWebMvcConfig extends WebMvcConfigurationSupport {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
// TODO Auto-generated method stub
registry.addResourceHandler("/images/**").addResourceLocations("file:D:/imageTest/");
        super.addResourceHandlers(registry);

    }


}

微信生成二维码(带参数scene)_第1张图片

微信小程序码的生成(java)

你可能感兴趣的:(微信生成二维码(带参数scene))