玩转QrCode

发布时间:2024年01月10日

生成二维码,跳转指定 url

  • 导入模块
 npm install --save qrcode.vue@1.7.0 
  • 引入模块
import QrcodeVue from 'qrcode.vue'
  • 编写页面
    • button 触发
<template>
  <el-button type="primary" @click="showQRCode">
    <svg-icon icon-class="code"/>
    二维码
  </el-button>
</template>
  • 弹窗页面
  <el-dialog :title="QRcodeTitle" :visible.sync="showPopup" width="220px">
      <el-form class="auto-size-form" justify="center" :model="qrcode" ref="qrcode" label-position="right" label-width="200px">
        <el-row justify="center">
          <el-form-item label="" class="form-item">
            <el-input style="width: 210px"
                      v-model="qrcode.QRlink"
                      :disabled="true">
            </el-input>
          </el-form-item>
        </el-row>
        <el-row justify="center">
            <el-divider></el-divider>
              <div style="text-align: center">
                <span>提示:扫码访问我的主页。</span>
              </div>
            <el-divider></el-divider>
        </el-row>
        <el-row justify="center">
          <el-form-item label="" class="form-item">
            <template>
              <QrcodeVue ref="Qrcode" :value="qrcode.QRlink" :size="qrcode.size" level="H"/>
            </template>
          </el-form-item>
        </el-row>
      </el-form>
    </el-dialog>
  • 编写方法
export default {
  name: "qrcodeDemo",
    components: {QrcodeVue},
  data() {
    return {
      showPopup: false,//触发二维码
      QRcodeTitle: '生成二维码',
      qrcode: {
        QRImgUrl: '',
        QRlink: 'https://blog.csdn.net/ljz66254',
        size: 200
      },
    }
  },
  mothod:{
    showQRCode() {
      this.QRcodeTitle = 'qrcoder of java porter';
      this.showPopup = true;
    }
  }
  • 效果展示

image.png

修改前端代码获取后端连接

  • 置空初始连接

image.png

  • 页面初始化时请求数据

image.png

  • 通过请求后端获取小程序的连接

生成小程序码

    public String getAccessToken() throws IOException {
        String accessToken ="";
        String tokenUrl ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
        String tokenJson =requestUtils.sendGet(tokenUrl);

        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode tokenJsonNode = objectMapper.readTree(tokenJson);
        accessToken = tokenJsonNode.get("access_token").asText();
        return accessToken;
    }
package top.ljzstudy.controller;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import top.ljzstudy.utils.RequestUtils;
import top.ljzstudy.utils.Result;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.attribute.UserDefinedFileAttributeView;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


/**
 * ProjectName:    mini
 * ClassName:    ScanQrCodeJumpController
 * Package:    top.ljzstudy.controller
 * Description:     生成二维码
 * Datetime:    2023/12/29   9:22
 * Author:   LJZ
 * @author LJZ
 */
@Slf4j
@RestController("qrCodeJump/ScanQrCodeJumpController")
@RequestMapping("qrCodeJump/ScanQrCodeJump")
public class ScanQrCodeJumpController {

    @Autowired
    private RequestUtils requestUtils;

    @Value("${wechatMini.appId}")
    private  String appid;

    @Value("${wechatMini.appSecret}")
    private String secret;

    @PostMapping("createQrCode")
    public Result createQrCode(@RequestParam Map<String,Object> params){

        ByteArrayOutputStream os = null;

        InputStream swapStream = null;
        try {
            //效验数据.....
            //获取页面路径
            String page = "pages/index/index";

            String access_token =getAccessToken();
            //组装参数
            Map<String, Object> paraMap = new HashMap<>();
            //二维码携带参数 不超过32位 参数类型必须是字符串
            paraMap.put("scene", "1");
            paraMap.put("page",page);
            //二维码的宽度
            paraMap.put("width", 1280);
            //自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调
            paraMap.put("auto_color", false);
            //是否需要透明底色, is_hyaline 为true时,生成透明底色的小程序码
            paraMap.put("is_hyaline", false);
            //默认是true,检查page 是否存在,为 true 时 page 必须是已经发布的
            paraMap.put("check_path", false);
            //正式版为 "release",体验版为 "trial",开发版为 "develop"
            paraMap.put("env_version", "trial");
            //发送请求
            byte[] bytes = requestUtils.doImgPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token, paraMap);

            String url = OSSFactory.build().uploadSuffix(bytes, "jpg");
            System.out.println("url = " + url);
            if(StringUtils.isNotBlank(url)){
                return Result.success(url);
            }else{
                return Result.error("生成项目二维码失败");
            }
        } catch (Exception e) {
            log.error("QrCodeApi productQR error:", e);
            return Result.error("生成项目二维码失败");
        }
    }
}

1704874423414.png

二维码与小程序码的下载

  • 新增 button
      <div slot="footer" class="dialog-footer">
          <el-button size="small" icon="el-icon-download" @click="downloadQRcode">下载二维码</el-button>
          <el-button type="info" size="small" @click="showPopup = false">取 消</el-button>
      </div>
  • 下载方法
mothod:{
    downloadQRcode() {
      const canvas = this.$refs.Qrcode
      const dataURL = canvas.$el.childNodes[0].toDataURL('image/png');
      // 创建一个链接元素
      const link = document.createElement('a');
      link.href = dataURL;
      link.download = 'javaport的二维码.png';
      // 模拟用户点击下载
      link.click();
      this.showPopup = false;
    },
}
  • 效果展示

1704771232502(1).png
1704871134248.png
1704871204694.png
1704871180177.png

生成二维码,跳转指定的小程序的页面

package top.ljzstudy.controller;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import top.ljzstudy.utils.RequestUtils;
import top.ljzstudy.utils.Result;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.attribute.UserDefinedFileAttributeView;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


/**
 * ProjectName:    mini
 * ClassName:    ScanQrCodeJumpController
 * Package:    top.ljzstudy.controller
 * Description:     扫码跳转小程序指定页面(体验版)
 * Datetime:    2023/12/29   9:22
 * Author:   LJZ
 * @author LJZ
 */
@Slf4j
@RestController("qrCodeJump/ScanQrCodeJumpController")
@RequestMapping("qrCodeJump/ScanQrCodeJump")
public class ScanQrCodeJumpController {

    @Autowired
    private RequestUtils requestUtils;

    @Value("${wechatMini.appId}")
    private  String appid;

    @Value("${wechatMini.appSecret}")
    private String secret;

    @PostMapping("createQrCode")
    public Result createQrCode(@RequestParam Map<String,Object> params){

        ByteArrayOutputStream os = null;

        InputStream swapStream = null;
        try {
            //效验数据.....
            //获取页面路径
            String page = "pages/index/index.html";

            //获取access_token
            String accessToken =getAccessToken();
            //跳转正式版
            //String targetUrl = requestUtils.sendPost("https://api.weixin.qq.com/wxa/generate_urllink?access_token=" + getAccessToken(), JSONUtil.toJsonStr(paraMap));

            //跳转体验版
            String sendUrl = "https://open.weixin.qq.com/sns/getexpappinfo?appid=" + appid + "&path=" + page;
            log.info("sendUrl = " + sendUrl);

            if(StringUtils.isNotEmpty(sendUrl)){
                return Result.success("operation successful",sendUrl);
            }else{
                new Result();
                return Result.error("operation fail");
            }
        } catch (Exception e) {
            log.error("QrCodeApi productQR error:", e);
            return Result.error("生成项目二维码失败");
        }
    }
}
  • 效果展示

1704874719017.png

获取小程序的二维码

package top.ljzstudy.controller;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import top.ljzstudy.utils.RequestUtils;
import top.ljzstudy.utils.Result;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.attribute.UserDefinedFileAttributeView;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


/**
 * ProjectName:    mini
 * ClassName:    ScanQrCodeJumpController
 * Package:    top.ljzstudy.controller
 * Description:     获取小程序二维码
 * Datetime:    2023/12/29   9:22
 * Author:   LJZ
 * @author LJZ
 */
@Slf4j
@RestController("qrCodeJump/ScanQrCodeJumpController")
@RequestMapping("qrCodeJump/ScanQrCodeJump")
public class ScanQrCodeJumpController {

    @Autowired
    private RequestUtils requestUtils;

    @Value("${wechatMini.appId}")
    private  String appid;

    @Value("${wechatMini.appSecret}")
    private String secret;

    @PostMapping("createQrCode")
    public Result createQrCode(@RequestParam Map<String,Object> params){

        ByteArrayOutputStream os = null;

        InputStream swapStream = null;
        try {
            //效验数据.....
            //获取页面路径
//            String sceneJson = "id="+dto.getId();
            String page = "pages/index/index";

            String access_token =getAccessToken();
            //组装参数
            Map<String, Object> paraMap = new HashMap<>();
            //二维码携带参数 不超过32位 参数类型必须是字符串

            paraMap.put("path",page);
            //二维码的宽度
            paraMap.put("width", 600);
            //正式版为 "release",体验版为 "trial",开发版为 "develop"
            paraMap.put("env_version", "trial");

            //二维码地址
            byte[] bytes = requestUtils.doImgPost("https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token="+access_token, paraMap);
            String qrCodeUrl = OSSFactory.build().uploadSuffix(bytes, "jpg");
            System.out.println("qrCodeUrl = " + qrCodeUrl);
            if(StringUtils.isNotEmpty(sendUrl)){

                return Result.success("operation successful",sendUrl);
            }else{
                new Result();
                return Result.error("operation fail");
            }
        } catch (Exception e) {
            log.error("QrCodeApi productQR error:", e);
            return Result.error("生成项目二维码失败");
        }
    }
}
  • 效果展示

1704879613230.png


涉及的微信开放接口

  • 获取接口调用凭据
GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

1704876071170.png

  • 获取小程序码
POST https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN

1704875800141.png

  • 跳转至小程序体验版的指定页面
GET https://open.weixin.qq.com/sns/getexpappinfo?appid=" + appid + "&path=" + path
  • 获取小程序的二维码
POST https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=ACCESS_TOKEN
  • 请求参数

1704879430507.png


在这里插入图片描述

文章来源:https://blog.csdn.net/ljz66254/article/details/135509867
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。