微信wxacode.getUnlimited接口生成小程序码
我是基于若依框架写的,复制的这个人的代码,在他的基础上改了改https://blog.csdn.net/m0_58440053/article/details/122230926?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_title~default-1.queryctrv2&spm=1001.2101.3001.4242.2&utm_relevant_index=4
access_token缓存是按照这个人的思路写的模拟的缓存https://www.cnblogs.com/setukirin/p/5718059.html
注意:access_token是后台向下面这个地址发送get请求,返回的值,不是登陆系统后生成的token
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
这个地址里的appid和secret的获取方式在最下面,grant_type的值就写client_credential就行了
maven导包
<!--httpclient,用来发送https请求--> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency>
实体类
1 public class WeiXinAccessTokenDTO { 2 private String grant_type; 3 private String appid; 4 private String secret; 5 6 public String getGrant_type() { 7 return grant_type; 8 } 9 10 public void setGrant_type(String grant_type) { 11 this.grant_type = grant_type; 12 } 13 14 public String getAppid() { 15 return appid; 16 } 17 18 public void setAppid(String appid) { 19 this.appid = appid; 20 } 21 22 public String getSecret() { 23 return secret; 24 } 25 26 public void setSecret(String secret) { 27 this.secret = secret; 28 } 29 30 @Override 31 public String toString() { 32 return "WeiXinAccessTokenDTO{" + 33 "grant_type='" + grant_type + '\'' + 34 ", appid='" + appid + '\'' + 35 ", secret='" + secret + '\'' + 36 '}'; 37 } 38 }
import java.util.Map; public class WeiXinUnlimitedDTO { private String access_token; //访问接口需要的选填的参数,直接map键值对转换json private Map<String, Object> params; public String getAccess_token() { return access_token; } public void setAccess_token(String access_token) { this.access_token = access_token; } public Map<String, Object> getParams() { return params; } public void setParams(Map<String, Object> params) { this.params = params; } @Override public String toString() { return "WeiXinUnlimitedDTO{" + "access_token='" + access_token + '\'' + ", params=" + params + '}'; } }
getAccessToken.properties
appid = xxxxxxx//只有注册成为开发者才能得到appid,下面有获取方式 secret = xxxxxxxxxxxxxxxxx//和appid一样 grant_type = client_credential
service层
1 import com.alibaba.fastjson.JSONObject; 2 import com.ruoyi.common.core.domain.AjaxResult; 3 import com.ruoyi.common.utils.http.HttpUtils; 4 import com.ruoyi.manager.domain.dto.WeiXinAccessTokenDTO; 5 import org.apache.http.HttpEntity; 6 import org.apache.http.HttpResponse; 7 import org.apache.http.HttpStatus; 8 import org.apache.http.client.methods.HttpPost; 9 import org.apache.http.entity.StringEntity; 10 import org.apache.http.impl.client.CloseableHttpClient; 11 import org.apache.http.impl.client.HttpClients; 12 import org.springframework.stereotype.Service; 13 14 import javax.servlet.http.HttpServletResponse; 15 import java.io.*; 16 import java.nio.charset.Charset; 17 import java.util.Date; 18 import java.util.HashMap; 19 import java.util.Map; 20 import java.util.Properties; 21 22 @Service 23 public class QRCodeService { 24 //用来存放access_token 25 private Map<String,Object> token=new HashMap<>(); 26 27 /** 28 * 发送http请求访问微信小程序接口获得输入流 29 * @param URL 30 * @param json 31 * @return 32 */ 33 public static ByteArrayInputStream sendPost(String URL, String json) { 34 InputStream inputStream = null; 35 ByteArrayInputStream byteArrayInputStream = null; 36 // 创建默认的httpClient实例. 37 CloseableHttpClient httpclient = HttpClients.createDefault(); 38 // 创建httppost 39 HttpPost httppost = new HttpPost(URL); 40 httppost.addHeader("Content-type", "application/json; charset=utf-8"); 41 httppost.setHeader("Accept", "application/json"); 42 try { 43 StringEntity s = new StringEntity(json, Charset.forName("UTF-8")); 44 s.setContentEncoding("UTF-8"); 45 httppost.setEntity(s); 46 HttpResponse response = httpclient.execute(httppost); 47 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { 48 // 获取相应实体 49 HttpEntity entity = response.getEntity(); 50 inputStream = entity.getContent(); 51 ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 52 // 创建一个Buffer字符串 53 byte[] buffer = new byte[1024]; 54 // 每次读取的字符串长度,如果为-1,代表全部读取完毕 55 int len = 0; 56 // 使用一个输入流从buffer里把数据读取出来 57 while ((len = inputStream.read(buffer)) != -1) { 58 // 用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度 59 outStream.write(buffer, 0, len); 60 } 61 // 关闭输入流 62 inputStream.close(); 63 // 把outStream里的数据写入内存 64 byteArrayInputStream = new ByteArrayInputStream(outStream.toByteArray()); 65 } 66 } catch (Exception e) { 67 e.printStackTrace(); 68 } finally { 69 // 关闭连接,释放资源 70 try { 71 httpclient.close(); 72 } catch (IOException e) { 73 e.printStackTrace(); 74 } 75 } 76 return byteArrayInputStream; 77 } 78 79 /** 80 * 返回菊花二维码图片给前端 81 * @param access_token 82 * @param paramJson 83 * @param response 84 * @return 85 */ 86 public AjaxResult getWXCode(String access_token, String paramJson, HttpServletResponse response) { 87 Map<String, Object> map = new HashMap<>(); 88 AjaxResult ajaxResult=null; 89 try { 90 // log.info("access_token:[{}]", access_token); 91 String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + access_token; 92 ByteArrayInputStream inputStream = sendPost(url, paramJson); 93 //这里判断的是返回的图片还是错误信息,一般错误信息不会大于200 94 if (inputStream.available() <= 200) { 95 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 96 int i; 97 byte[] buffer = new byte[200]; 98 while ((i = inputStream.read(buffer)) != -1) { 99 byteArrayOutputStream.write(buffer, 0, i); 100 } 101 String str = new String(byteArrayOutputStream.toByteArray()); 102 //错误信息的格式在官方文档里有 103 JSONObject jsonObject = JSONObject.parseObject(str); 104 113 byteArrayOutputStream.close(); 114 return AjaxResult.error(Integer.parseInt(jsonObject.getString("errcode")),jsonObject.getString("errmsg")); 115 } 116 //返回web前端,这里返回的是base64 117 byte[] buff = new byte[inputStream.available()+1]; 118 inputStream.read(buff,0,inputStream.available()); 119 inputStream.close(); 120 //下载到本地的代码 121 // FileOutputStream fileOutputStream = new FileOutputStream("D:/123.png"); 122 // int i; 123 // byte[] buffer = new byte[200]; 124 // while ((i = inputStream.read(buffer)) != -1) { 125 // fileOutputStream.write(buffer, 0, i); 126 // } 127 // fileOutputStream.flush(); 128 // fileOutputStream.close(); 129 // inputStream.close(); 130 // map.put("true",buff); 131 ajaxResult=new AjaxResult(200,"获取小程序码成功",buff); 132 } catch (Exception e) { 133 134 ajaxResult=new AjaxResult(500,"获取小程序码失败",null); 135 } 136 return ajaxResult; 137 } 138 //获取access_token 139 public Map<String, Object> getWeiXinAccessToken() { 140 WeiXinAccessTokenDTO dto = new WeiXinAccessTokenDTO(); 141 Properties properties = new Properties(); 142 File file=new File("项目名/src/main/resources/getAccessToken.properties"); 143 FileReader reader=null; 144 try { 145 reader=new FileReader(file); 146 properties.load(reader); 147 } catch (FileNotFoundException e) { 148 e.printStackTrace(); 149 } catch (IOException e) { 150 e.printStackTrace(); 151 } 152 153 String appid=properties.getProperty("appid"); 154 String secret=properties.getProperty("secret"); 155 String grant_type=properties.getProperty("grant_type"); 159 String param = "grant_type=" + grant_type + "&appid=" + appid + "&secret=" +secret; 160 String resultStr = HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/token", param); 161 162 String[] strings = resultStr.split(","); 163 String[] access_token = strings[0].split("\""); 164 //把access_token放到模拟的缓存里 165 token.put("access_token", access_token[3]); 166 token.put("time",System.currentTimeMillis()); 167 168 return token; 169 } 170 171 //得到缓存中的access_token,如果access_token过期则重新获取 172 public String getCacheAccessToken(){ 173 Long time = (Long)token.get("time"); 174 String access_token= (String) token.get("access_token"); 175 Long nowDate = new Date().getTime(); 176 if (access_token != null && time != null && nowDate - time < 7200 * 1000){ 177 return access_token; 178 }else { 179 return (String) this.getWeiXinAccessToken().get("access_token"); 180 } 181 } 182 183 }
controller层
1 import com.alibaba.fastjson.JSON; 2 import com.ruoyi.common.core.domain.AjaxResult; 3 import com.ruoyi.common.core.redis.RedisCache; 4 import com.ruoyi.manager.service.QRCodeService; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.web.bind.annotation.PostMapping; 7 import org.springframework.web.bind.annotation.RequestBody; 8 import org.springframework.web.bind.annotation.RequestMapping; 9 import org.springframework.web.bind.annotation.RestController; 10 11 import javax.servlet.http.HttpServletResponse; 12 import java.util.Map; 13 14 @RestController 15 @RequestMapping("/manager/QRCode") 16 public class QRCodeController { 17 @Autowired 18 private QRCodeService service; 19 20 @Autowired 21 private RedisCache redisCache; 22 23 24 @PostMapping("/getUnlimited") 25 public AjaxResult getWeiXinUnlimited(@RequestBody Map<String, Object> params, HttpServletResponse response) { 26 27 28 String cacheAccessToken = service.getCacheAccessToken(); 29 System.out.println("access_token1: (" + cacheAccessToken + ")"); 30 String s = JSON.toJSONString(params); 31 AjaxResult result = service.getWXCode(cacheAccessToken, s, response); 32 return result; 33 } 34 35 }
前端vue代码
<template> <el-row> <el-col :span="24"> <el-button icon="el-icon-search" size="mini" @click="getCode">获取小程序码</el-button> <img ref="img" :src="base64"> </el-col> </el-row> </template> <script> import { getAccessToken,getCode } from '@/api/manager/QRCode' import request from '@/utils/request' export default { name: 'QRCode', data(){ return{ accessToken:'', codeData:{ access_token:'', params:{ scene:"id=3", } }, base64:'', imgUrl:'', } }, methods:{ getCode(){ getCode(this.codeData.params).then(request=>{ this.base64="data:image/jpg;base64,"+request.data; }) }, } } </script> <style scoped> </style>
QRCode.js
import request from '@/utils/request' // 获取小程序码 export function getCode(data) { return request({ url: '/manager/QRCode/getUnlimited', method: 'post', data: data }) }
获取appid和secret的步骤
微信公众平台 - 设置 - 开发设置
注册登陆 微信公众平台,进入之后点击开发管理
点击开发设置
再点击AppSecret那一行的 生成 (我记得是“生成”来着,第一次生成了之后就变成“重置”了)
然后就生成了secret,上边那个AppID就是需要的那个appid
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Blazor Hybrid适配到HarmonyOS系统
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 解决跨域问题的这6种方案,真香!
· 分享4款.NET开源、免费、实用的商城系统
· 一套基于 Material Design 规范实现的 Blazor 和 Razor 通用组件库