美文网首页小程序
java生成带参数的小程序二维码 扫描后在小程序端获取参数

java生成带参数的小程序二维码 扫描后在小程序端获取参数

作者: 闲置的Programmer | 来源:发表于2019-06-19 16:05 被阅读0次

    一、Java端

    1、搭建一个springboot项目,引入以下pom依赖

    <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/top.jfunc.common/converter -->
            <dependency>
                <groupId>top.jfunc.common</groupId>
                <artifactId>converter</artifactId>
                <version>1.8.0</version>
            </dependency>
    
            <dependency>
                <groupId>net.sf.json-lib</groupId>
                <artifactId>json-lib</artifactId>
                <version>2.4</version>
                <classifier>jdk15</classifier>
            </dependency>
    
    
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.7.4</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
                <version>2.7.4</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
                <version>2.7.4</version>
            </dependency>
        </dependencies>
    
    

    2、新建2个工具类 UrlUtil、CreateQrcore

    1、UrlUtil //向指定 URL 发送POST方法的请求

    package com.example.utils;
    
    import java.io.BufferedReader;
    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 UrlUtil {
        /**
         * 向指定 URL 发送POST方法的请求
         *
         * @param url 发送请求的 URL
         * @return 所代表远程资源的响应结果
         */
        public static String sendPost(String url, Map<String, ?> paramMap) {
            PrintWriter out = null;
            BufferedReader in = null;
            String result = "";
    
            String param = "";
            Iterator<String> 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(Exception ex){
                    ex.printStackTrace();
                }
            }
            return result;
        }
    }
    
    

    2、CreateQrcore 创建二维码 设定二维码的参数、生成后保存的地址等等

    paramJson.put("scene","2");//这一句就是你二维码里携带的参数 String型 名称不可变

    package com.example.utils;
    
    
    import net.sf.json.JSONObject;
    
    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 CreateQrcore {
    
        /*
         * 获取 token
       * 普通的 get 可获 token
         */
        public  static String getToken() {
            try {
                Map<String, String> map = new LinkedHashMap<>();
                map.put("grant_type", "client_credential");
                map.put("appid","xxxxxxxxxxxxxx");
                map.put("secret", "xxxxxxxxxxxxxxxxxxxxx");
    
                String rt = UrlUtil.sendPost("https://api.weixin.qq.com/cgi-bin/token", map);
                System.out.println("what is:"+rt);
                JSONObject json = JSONObject.fromObject(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,HttpServletRequest request) {
            String p="F://code"; //二维码生产的地址  本地F盘code文件夹
            System.out.println(p);
            String codeUrl=p+"/twoCode.png";
            String twoCodeUrl="twoCode.png";
            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();
                paramJson.put("scene","2");//这就是你二维码里携带的参数 String型  名称不可变
                paramJson.put("path", "pages/index/index"); //这是设置扫描二维码后跳转的页面
                paramJson.put("width", 430);
                paramJson.put("is_hyaline", true);
                paramJson.put("auto_color", true);
    
                System.out.println("httpURLConnection"+httpURLConnection);
                System.out.println("paramJson.toString()"+paramJson.toString());
                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;
        }
    }
    
    
    

    3、创建一个Controller作接口调用

    package com.example.controller;
    
    import com.example.utils.CreateQrcore;
    import net.sf.json.JSONObject;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.servlet.http.HttpServletRequest;
    import java.io.IOException;
    
    @RestController
    public class CoreController {
    
    
        /**
         * 接收二维码
         * @param request
         * @return
         * @throws IOException
         */
        @RequestMapping(value="/twoCode",method= RequestMethod.POST,produces="text/html;charset=utf-8")
        @ResponseBody
        public Object twoCode( HttpServletRequest request) throws IOException{
    
            JSONObject data=new JSONObject();
            String accessToken = CreateQrcore.getToken();
            System.out.println("accessToken;"+accessToken);
            String twoCodeUrl = CreateQrcore.getminiqrQr(accessToken,request);
            data.put("twoCodeUrl", twoCodeUrl);
            return data;
        }
    }
    
    

    二、小程序端

    1、在二维码设置的跳转页面里的JS中写入以下代码进行获取二维码的参数

    在onLoad()方法中加上options参数,然后用decodeURIComponent转一次码后进行或许,这些操作都是必须的,而且scene这个变量名是不可变的

    onLoad(options) {
                var scene_id = decodeURIComponent(options.scene); //获取二维码的参数
                console.info('scene_id : ' +scene_id)
                
                if(scene_id == 'undefined' || !scene_id || scene_id == null ){
                    wx.reLaunch({
                        url: '/pages/index/share',
                    })
                    return false;
                }
                
                this.scene = scene_id;   //获取的机器码编号
                console.info(this.scene)
                //检查登录是否过期
                wx.checkSession({
                    success: function(e) { //登录态未过期
                        console.log(new Date() + "未过期");
                    },
                    fail: function() { //登录态过期了
                        console.log(new Date() + "已过期");
                    }
                });
            },
    
    

    2、拿刚刚生成的二维码在小程序端进行测试,在微信开发者工具里有个通过二维码编译,点击后选择刚刚生成的二维码


    image.png

    3、获取参数成功~~


    image.png

    相关文章

      网友评论

        本文标题:java生成带参数的小程序二维码 扫描后在小程序端获取参数

        本文链接:https://www.haomeiwen.com/subject/pcykqctx.html