玩转QrCode

生成二维码,跳转指定 url

  • 导入模块
 npm install --save [email protected] 
  • 引入模块
import QrcodeVue from 'qrcode.vue'
  • 编写页面
    • button 触发

  • 弹窗页面
  
      
        
          
            
            
          
        
        
            
              
提示:扫码访问我的主页。
  • 编写方法
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;
    }
  }
  • 效果展示

玩转QrCode_第1张图片

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

  • 置空初始连接

玩转QrCode_第2张图片

  • 页面初始化时请求数据

玩转QrCode_第3张图片

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

生成小程序码

    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("生成项目二维码失败");
        }
    }
}

玩转QrCode_第4张图片

二维码与小程序码的下载

  • 新增 button
      
  • 下载方法
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;
    },
}
  • 效果展示

玩转QrCode_第5张图片
玩转QrCode_第6张图片
玩转QrCode_第7张图片
玩转QrCode_第8张图片

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

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("生成项目二维码失败");
        }
    }
}
  • 效果展示

玩转QrCode_第9张图片

获取小程序的二维码

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("生成项目二维码失败");
        }
    }
}
  • 效果展示

玩转QrCode_第10张图片


涉及的微信开放接口

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

玩转QrCode_第11张图片

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

玩转QrCode_第12张图片

  • 跳转至小程序体验版的指定页面
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
  • 请求参数

玩转QrCode_第13张图片


玩转QrCode_第14张图片

你可能感兴趣的:(开发小结,java,微信小程序,vue.js)