SpringBoot 生成微信二维码 B方案

SpringBoot 生成微信二维码 B方案

今天主要分享一下 如何使用 springBoot 来生成 微信B方案的二维码。微信官方地址 (微信官方文档) 有其他方案需求的小伙伴 可以进官方了解一下哈。
首先我们来看一下 他的注意事项
首先我们来看一下 他的注意事项
然后 再来研究一下 微信提供的请求地址 和 参数在这里插入图片描述
了解之后呢 我们就来看一下第一个参数 调用凭证 这个参数也是需要 调取微信提供的 Api 来获得。 它主要用到 小程序的 AppID 和 秘钥 另外一个 我们就不用管了 给默认值带上就可以了。在这里插入图片描述
因为他的 有效时间是 7200 秒,所以我这里就采用了 redis 把它储存了起来,并设置了 这个key 的失效时间 来方便我们 获取到最新的 access_token。 废话不多说 上代码

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;
@Service
public class GetWxAccessCodeTask {
    @Autowired
    private RedisTemplate redisTemplate;

    // 小程序 AppID
    private static final String APPID = "3xxx";
    // 小程序 秘钥
    private static final String APPSECRET = "cxxxx";

    public String accessCode() throws Exception{
        ValueOperations<String,String> operations = redisTemplate.opsForValue();
        // 判断 redis 里有没有这个 key
        boolean hasKey = redisTemplate.hasKey("accessToken");
        if (hasKey){
            //  有 就直接返回这个key
            return operations.get("accessToken");
        }else {
            //  没有 就重新 调用微信Api 拿
            String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                    +APPID+ "&secret="+APPSECRET;
            URL url = new URL(accessTokenUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.connect();
            //获取返回的字符
            InputStream inputStream = connection.getInputStream();
            int size =inputStream.available();
            byte[] bs =new byte[size];
            inputStream.read(bs);
            String message=new String(bs,"UTF-8");
            //获取access_token
            JSONObject jsonObject = JSONObject.parseObject(message);
            String accessToken = jsonObject.getString("access_token");
            String expires_in = jsonObject.getString("expires_in");
            // 写入缓存 我这里设定的 时间是 7180 秒 access_token 失效时间相差了一点
            operations.set("accessToken", accessToken, 7180, TimeUnit.SECONDS);
            return operations.get("accessToken");
        }

    }

获取到微信的 调用凭证 access_token 以后 第一个参数就解决了 接下来就可以 调用微信生成二维码的Api了
这里 我们再来看一下 微信的第二个参数 有了这个 scene 参数以后呢 我们就可以带我们想带的参数啦在这里插入图片描述
调用生成二维码 Api 我这里生成以后是 保存在本地的 而且只带了 scene 这一个参数 其他的 啥都没带 使用默认

package com.jt.dot.admin.web;

import com.alibaba.fastjson.JSONObject;
import com.jt.dot.admin.storage.StorageService;
import com.jt.dot.db.domain.UmsUser;
import com.jt.dot.db.service.GetWxAccessCodeTask;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

@RequestMapping("/getAccess")
@RestController
public class WxacodeController {
    @Autowired
    private GetWxAccessCodeTask wxAccessCodeTask;
    @Autowired
    private StorageService storageService;


    @RequestMapping("/AccessToken")
    public String getAccessToken() throws Exception {
        UmsUser user = (UmsUser) SecurityUtils.getSubject().getPrincipal();
        String fileName = UUID.randomUUID().toString() + System.currentTimeMillis()+ (".jpg");
        StringBuffer backUrl = new StringBuffer(); // 回调url
        StringBuffer info = new StringBuffer("https://api.weixin.qq.com/wxa/getwxacodeunlimit?");
        String scene = "userId:"+1;
        String accessToken = wxAccessCodeTask.accessCode();
        URL url = null;
        url = new URL(info.append("access_token=").append(accessToken).toString());
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-type", "application/json");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        // 获取URLConnection对象对应的输出流
        PrintWriter printWriter = new PrintWriter(connection.getOutputStream());
        JSONObject paramJson = new JSONObject();
        paramJson.put("scene", scene);

        printWriter.write(paramJson.toString());
        // flush输出流的缓冲
        printWriter.flush();
        //开始获取数据
        BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
        File file = new File("C:/Users/Administrator/Pictures/Screenshots/abc.png");
        OutputStream os = new FileOutputStream(file);
        int len;
        byte[] arr = new byte[1024];
        while ((len = bis.read(arr)) != -1) {
            os.write(arr, 0, len);
            os.flush();
        }
        os.close();
        // 上传到线上服务
//        String url1 = storageService.store(connection.getInputStream(), file.getName(), 0, "image/png");
        return "ok";
    }


}


测试如下在这里插入图片描述
二维码 看看 效果就可以啦
在这里插入图片描述
本文到处结束啦 有时间再总结一下 上传图片到OSS服务器
如需转载 请备注本文出处

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值