java生成小程序二维码

上周做了java生成二维码功能之后,这周又有新的需求出现了,可谓是唯一不变的就是变化。

这周的需求是通过java接口返回小程序码,然后提供给微信扫描跳转到小程序并显示指定的数据。

这里需要用到小程序的相关apiwxacode.getUnlimited | 微信开放文档

话不多说直接上代码

controller代码

package com.wx.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.wx.common.utils.HttpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

/**
 * //TODO 添加类/接口功能描述
 *
 * @author 刘朋
 * <br/>date 2022-06-21
 */

@Slf4j
@RestController
@RequestMapping("/applet")
@Api(tags = "小程序")
public class AppletController {

    @ApiOperation(value = "test")
    @PostMapping("/test")
    public void importData(HttpServletResponse response) throws Exception {
        response.setContentType("image/gif");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        String accessToken = getAccessToken();

        //文档地址 https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html#%E8%AF%B7%E6%B1%82%E5%8F%82%E6%95%B0

        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;

        // 发送请求参数
        JSONObject paramJson = new JSONObject();
        paramJson.set("page", "pages/index/index");
        paramJson.set("check_path", false);
        paramJson.set("width", 280);
        //这里传输的数据不能中文,要改掉!!!
        paramJson.set("scene", "传输的数据");
        //设置小程序码版本
        //paramJson.set("env_version","release"); 默认正式
            paramJson.set("env_version","trial"); //体验版
//        paramJson.set("env_version","develop"); //开发版

        InputStream inputStream = HttpUtils.postInputStream(url, paramJson);
        //将流写出到response
        IoUtil.copy(inputStream, response.getOutputStream());

    }


    public String getAccessToken(){
        String appid="填自己的appid";
        String secret="填自己的密钥";
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
        String result = HttpUtil.get(url);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        return jsonObject.get("access_token").toString();
    }
}

工具类代码

package com.wx.common.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONObject;

import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * http工具类
 *
 * @author 刘朋
 * <br/>date 2022-06-21
 */
public class HttpUtils {

    public static InputStream  postInputStream(String urlStr , JSONObject paramJson ) throws Exception {
            //获取小程序码,适用于需要的码数量较少的业务场景。通过该接口生成的小程序码,永久有效,有数量限制
            URL url = new URL(urlStr);

            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());

            printWriter.write(paramJson.toString());
            // flush输出流的缓冲
            printWriter.flush();
            String contentType = httpURLConnection.getContentType();
            if (contentType.contains("json")) {
                IoUtil.copy(httpURLConnection.getInputStream(), System.out);
                throw new IllegalArgumentException("调用微信小程序生成接口出错");
            } else {
                //开始获取数据
                return  httpURLConnection.getInputStream();
            }

    }
}

小程序获取传参的代码

onLoad(query) {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
       // scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
       const scene = decodeURIComponent(query.scene)
       console.log("scene2=="+scene);
       
       this.setData({ msg: scene })
  }

实现效果

扫描微信二维码之后能够在小程序端获取到“传输的数据”

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值