外部扫码跳转到微信小程序

在公司业务中,需要外部扫码后邀请好友进行注册,而正常生成的二维码无法实现(毕竟用的是微信的小程序),所以需要调用微信小程序的接口.

1.申请跳转链接

小程序管理 -> 开发设置 -> 扫普通链接二维码打开小程序

点击添加.

具体开发看微信手册

另外要说一点就是他的验证文件需要放在公网服务器上,否则微信接口访问不到则不能保存!

我是放在云服务器的nginx中,同时在html文件夹下创建一个文件夹保存,同时在nginx.conf中写入访问资源路径

	location /jckd {
	alias /usr/local/nginx/html/jckd/;
}

该路径是我的解析文件保存的路径.

同时还有一个就是需要一个测试的访问链接,用于我们开发时测试使用,如果需要带参数跳转需要写明get带参跳转的参数示例

127.0.0.1/jckd/test?id=1

127.0.0.1/jckd/test/id/1

 保存后这个链接就是我们跳转到微信小程序的链接

然后可以自己现生成一个二维码测试一下二维码生成网站

当没有问题后,Java代码进行业务写入

生成二维码使用到了Google的依赖,同时还有生成二维码使用到的工具类

   <!--工具类-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.3.2</version>
        </dependency>

        <!-- 谷歌二维码生成工具 -->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.5.1</version>
        </dependency>

        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.5.1</version>
        </dependency>

下面是微信扫码和其他外部网站扫码跳转实现代码:

/**
     * 用户邀请码生成
     *
     * @param userId 邀请用户id
     * @param qrType 二维码类型(微信/H5)
     * @return Base64图片流
     * @throws AdminServiceException
     */
    @Override
    public String getInvUserQR(Integer userId, Integer qrType) throws Exception {

        //二维码配置类
        QrConfig qrConfig = new QrConfig(400, 400);
        qrConfig.setMargin(3);

        //二维码颜色
        qrConfig.setForeColor(Color.CYAN);
        //背景颜色
        qrConfig.setBackColor(Color.GRAY);

        qrConfig.setCharset(Charset.defaultCharset());

        //生成中间log(没有图片暂时不搞)
        //QrConfig.create().setImg("");
        String url = "";
        if (qrType == 1) url = "https://127.0.0.1/jckd/test?id=" + userId;

        //小程序未上线,无法获取跳转链接
        if (qrType == 2) {
            Map<String, Object> appletUrl = getAppletUrl(userId);
            url = appletUrl.get("url").toString();
        }

        if (StringUtils.isEmpty(url)) throw new AdminServiceException(ExceptionDefinition.QRCODE_URL_ERROR);

        //生成二维码
        BufferedImage qrCode = QrCodeUtil.generate(url, qrConfig);

        //转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();

        try {
            ImageIO.write(qrCode, "jpg", os);
        } catch (IOException e) {
            throw new AdminServiceException(ExceptionDefinition.QRCODE_CONVERSION_ERROR);
        }

        //解码抬头
        String base64 = "data:image/png;base64,";
        String encode = Base64.getEncoder().encodeToString(os.toByteArray());
        return base64 + encode;
    }


    //凭证调用
    public static String getAccessToken() throws IOException {
        //小程序APPID
        String appid = "APPID";

        //小程序secret
        String secret = "secret";

        String httpUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
        httpUrl = httpUrl + "&appid=" + appid + "&secret=" + secret;


        OkHttpClient okHttpClient = new OkHttpClient();
        String accessToken = okHttpClient.newCall(new Request.Builder().url(httpUrl).get().build()).execute().body().string();

        return accessToken;
    }


    /**
     * 生成跳转链接
     * 向微信接口请求外部跳转vx小程序的链接
     * 可能会失败,失败信息也由Map返回
     *
     * @param userId 邀请人ID
     * @return Map<String, Object>
     * @throws IOException
     */
    public static Map<String, Object> getAppletUrl(Integer userId) throws IOException {
        Map<String, Object> map = new HashMap<>();

        //接口地址
        String httpUrl = "https://api.weixin.qq.com/wxa/generatescheme?access_token=";

        //需要跳转的小程序路径
        String path = "pages/public/login";

        //获取AccessToken
        String AccessTokenJson = getAccessToken();

        //格式化返回数据
        JSONObject resultObject = JSONObject.parseObject(AccessTokenJson);
        String AccessToken = resultObject.getString("access_token");


        if (AccessToken == null) {
            AccessToken = resultObject.getString("errmsg");
            map.put("code", -1);//错误码
            map.put("msg", AccessToken);//错误信息
        } else {
            map.put("code", 0);

            try {
                String content = "";

                JSONObject jsonParam = new JSONObject();
                JSONObject jump_wxa = new JSONObject();

                //请求参数装填
                jump_wxa.put("path", path);
                jump_wxa.put("query", "id=" + userId);
                jump_wxa.put("env_version", "trial");

                jsonParam.put("jump_wxa", jump_wxa);
                jsonParam.put("expire_type", 1);
                jsonParam.put("expire_interval", 2);
                String params = jsonParam.toString();

                CloseableHttpClient httpClient = HttpClients.createDefault();
                RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(300 * 1000).setConnectTimeout(300 * 1000).build();
                HttpPost post = new HttpPost(httpUrl + AccessToken);
                post.setConfig(requestConfig);
                post.setHeader("Content-Type", "application/json;charset=utf-8");

                //URLEncoder.encode(name)
                StringEntity postingString = new StringEntity(params, "utf-8");
                post.setEntity(postingString);
                CloseableHttpResponse response = httpClient.execute(post);
                content = EntityUtils.toString(response.getEntity());

                JSONObject resultUrl = JSONObject.parseObject(content);
                String newUrl = resultUrl.getString("openlink");
                map.put("url", newUrl);
                System.out.println("WeChatInterfaceUtil.getWeixinUrl--" + newUrl);
            } catch (SocketTimeoutException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return map;
    }

最后当扫码后前端从onLoad可以获取一个q的数据,然后进行解码就可以获取到里面带参跳转的数据了,通过数据可以知道邀请人ID,然后进行相应的操作.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值