精华内容
下载资源
问答
  • Java生成小程序二维码

    2019-11-05 11:22:42
    直接切入主题Java部分代码 public Map<String,Object> doQrCode(String accessToken, ServletOutputStream out){ String guidStr = UUIDUtil.generateGUID().replace(... //微信小程序二维码生成 RestT...

    直接切入主题Java部分代码

    public Map<String,Object> doQrCode(String accessToken,  ServletOutputStream out){
       
    			String guidStr = UUIDUtil.generateGUID().replace("-",""
    展开全文
  • java生成小程序二维码

    千次阅读 2018-07-24 14:08:16
    2019-12-10更新 直接上代码 import com.alibaba.fastjson.JSONObject; import ... import java.io.*;...import java.net.HttpURLConnection; import java.net.URL; import ja...

    2019-12-10更新

    直接上代码

    import com.alibaba.fastjson.JSONObject;
    import com.yuboinfo.commom.utils.https.HttpXmlClient;
    
    import java.io.*;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLDecoder;
    import java.nio.charset.StandardCharsets;
    
    /**
     * @author admin
     */
    public class XcxQrCode {
        /**
         * 生成二维码
         * Folder:文件夹路径
         * xcxUrl:小程序地址 必须已发布的小程序
         *
         * @param folder 文件夹名称
         * @param xcxUrl 小程序地址
         * @return 地址
         */
        public static String qrCode(String folder,String fileName, String xcxUrl,String appid,String secret) {
    
            //获取ACCESS_TOKEN
            String accessToken = getAccessToken( appid, secret);
            String name = getQrCode(accessToken, folder, fileName, xcxUrl, 300);
            System.out.println(name);
            return name;
        }
    
        public static String getAccessToken(String appid,String secret) {
            String requestStr = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET";
            requestStr = requestStr.replace("APPID", appid);
            requestStr = requestStr.replace("SECRET", secret);
            String oauth2Token = HttpXmlClient.get(requestStr);
            JSONObject jsonObject = JSONObject.parseObject(oauth2Token);
            return jsonObject.getString("access_token");
        }
    
        public static String getQrCode(String accessToken, String folder,String fileName, String xcxPath, int width) {
            String createwxaqrcodeStr = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" + accessToken;
    
            InputStream is = null;
            try {
                JSONObject json = new JSONObject();
                json.put("path",xcxPath);
                json.put("width",width);
                String params = json.toString();
                is = postInputStream(createwxaqrcodeStr, params);
                boolean flag = saveToImgByInputStream(is, folder, fileName);
                if (flag) {
                    return folder + "/" + fileName;
                }
    
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if(is != null){
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return "";
        }
    
        /**
         * 发送HttpPost请求 返回流
         *
         * @param strUrl 服务地址
         * @param params json字符串,例如: "{ \"id\":\"12345\" }" ;其中属性名必须带双引号<br/>
         * @return 成功:返回json字符串<br/>
         */
        public static InputStream postInputStream(String strUrl, String params) {
            try {
                // 创建连接
                URL url = new URL(strUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setUseCaches(false);
                connection.setInstanceFollowRedirects(true);
                // 设置请求方式
                connection.setRequestMethod("POST");
                // 设置接收数据的格式
                connection.setRequestProperty("Accept", "application/json");
                // 设置发送数据的格式
                connection.setRequestProperty("Content-Type", "application/json");
                //创建链接
                connection.connect();
                // utf-8编码
                OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
                out.append(params);
                out.flush();
                out.close();
                return connection.getInputStream();
    
            } catch (IOException e) {
    
                e.printStackTrace();
            }
            return null;
        }
    
        /**
         * 将二进制转换成文件保存
         *
         * @param instreams 二进制流
         * @param imgPath   图片的保存路径
         * @param imgName   图片的名称
         * @return 1:保存正常
         * 0:保存失败
         */
        public static boolean saveToImgByInputStream(InputStream instreams, String imgPath, String imgName) {
            if (instreams != null) {
                FileOutputStream fos = null;
                try {
                    createDir(imgPath);
    
                    //可以是任何图片格式.jpg,.png等
                    File file = new File(imgPath, imgName);
                    fos = new FileOutputStream(file);
                    byte[] b = new byte[1024];
                    int nRead;
                    while ((nRead = instreams.read(b)) != -1) {
                        fos.write(b, 0, nRead);
                    }
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (fos != null) {
                            fos.flush();
                            fos.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
    
                }
            }
            return false;
        }
    
        /**
         * 创建文件夹
         *
         * @param destDirName 文件夹名称
         */
        public static void createDir(String destDirName) {
            try {
                destDirName = URLDecoder.decode(destDirName, "GB2312");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            File dir = new File(destDirName);
            if (dir.exists()) {
                System.out.println("创建目录" + destDirName + "失败,目标目录已经存在");
                return;
            }
            if (!destDirName.endsWith(File.separator)) {
                destDirName = destDirName + File.separator;
            }
            // 创建目录
            if (dir.mkdirs()) {
                System.out.println("创建目录:" + destDirName + "成功!");
            } else {
                System.out.println("创建目录:" + destDirName + "失败!");
            }
        }
    
        public static void main(String[] args) {
            String appid = "";
            String secret = "";
            qrCode("d:/","adf.png", "pages/index/index",appid,secret);
        }
    }
    

    HttpXmlClient.util

    
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.ParseException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.methods.HttpUriRequest;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    import org.jboss.logging.Logger;
    
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    
    /**
     * @author admin
     */
    public class HttpXmlClient {
        private static Logger log = Logger.getLogger(HttpXmlClient.class);
    
        /**
         * 返回请求接口回复的json数据
         *
         * @param url    链接
         * @param params 参数
         * @return String
         */
        public static String post(String url, Map<String, String> params) {
    
            //获取DefaultHttpClient请求
            HttpClient httpclient = HttpClientBuilder.create().build();
            log.info("create httppost:" + url);
            HttpPost post = postForm(url, params);
            return invoke(httpclient, post);
        }
    
        public static String get(String url) {
            HttpClient httpclient = HttpClientBuilder.create().build();
            log.info("create httpget:" + url);
            HttpGet get = new HttpGet(url);
            return invoke(httpclient, get);
        }
    
    
        private static String invoke(HttpClient httpclient,
                                     HttpUriRequest httpost) {
            HttpResponse response = sendRequest(httpclient, httpost);
            return paseResponse(response);
        }
    
        private static String paseResponse(HttpResponse response) {
            log.info("get response from http server..");
            HttpEntity entity = response.getEntity();
            log.info("response status: " + response.getStatusLine());
            String body = null;
            try {
                body = EntityUtils.toString(entity);
                log.info(body);
            } catch (ParseException | IOException e) {
                e.printStackTrace();
            }
    
            return body;
        }
    
        private static HttpResponse sendRequest(HttpClient httpclient,
                                                HttpUriRequest httpost) {
            log.info("execute post...");
            HttpResponse response = null;
            try {
                response = httpclient.execute(httpost);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return response;
        }
    
        private static HttpPost postForm(String url, Map<String, String> params) {
    
            HttpPost httpost = new HttpPost(url);
            List<NameValuePair> nvps = new ArrayList<>();
    
            if (params != null) {
                Set<String> keySet = params.keySet();
    
                for (String key : keySet) {
                    nvps.add(new BasicNameValuePair(key, params.get(key)));
                }
                try {
                    log.info("set utf-8 form entity to httppost");
                    httpost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
    
            }
            return httpost;
        }
    }

     

    展开全文
  • java 生成小程序二维码

    千次阅读 2019-03-15 14:15:45
    根据小程序的appId和秘钥换取授权accessToken 信息: String codeUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="//生成二维码url String url = "...+appId+"...
    根据小程序的appId和秘钥换取授权accessToken 信息:
    
    String codeUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="//生成二维码url
    String url = "https://api.weixin.qq.com/cgi-bin/token?appid="+appId+"&secret="+appSecret+"&grant_type=client_credential"
    RestTemplate restTemplate = new RestTemplate()
    ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class)
    logger.info("responseEntity授权获取accessToken:"+responseEntity)
     if(responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
    
            String sessionData = responseEntity.getBody()
            logger.info("sessionData = " + sessionData)
            JSONObject jsonObj = JSON.parseObject(sessionData)
            String accessToken = jsonObj.getString("access_token")
    
            URL url_Code= new URL(codeUrl+accessToken)
            HttpURLConnection httpURLConnection = (HttpURLConnection) url_Code.openConnection()
            httpURLConnection.setRequestMethod("POST")//提交模式
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true)
            httpURLConnection.setDoInput(true)
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream())
            // 发送请求参数
            JSONObject paramJson = new JSONObject()
            paramJson.put("scene",orderCodeReq.scene)
            paramJson.put("page", orderCodeReq.page)
            paramJson.put("width", orderCodeReq.width)//二维码的宽度,默认为 430px,最小 280px,最大 1280px
            paramJson.put("auto_color", orderCodeReq.autoColor)
            Map<String,Object> line_color = new HashMap<>()
            line_color.put("r", 0)
            line_color.put("g", 0)
            line_color.put("b", 0)
            paramJson.put("line_color", line_color)
            printWriter.write(paramJson.toString())
            // flush输出流的缓冲
            printWriter.flush()
            //开始获取数据
            String uploadBasePath = 上传文件的路径//
            String accessPath= 访问路径//
            String imei = RandomUtil.getCharAndNum(10) //随机生成文件的名称
            String name = imei+".png"
            String towPath=  上传文件的路径     
    
            if(uploadBasePath.charAt(uploadBasePath.length()-1) != '/') uploadBasePath=uploadBasePath+"/"
              String basePath=uploadBasePath+towPath
              File fileDir=new File(basePath)
              if(!fileDir.isDirectory()) fileDir.mkdirs()
              fileName = accessPath+"/"+towPath+"/"+name
    
              BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream())
              OutputStream os = new FileOutputStream(new File(basePath+"/"+name))
              int len
              byte[] arr = new byte[1024]
              while ((len = bis.read(arr)) != -1)
               {
                   os.write(arr, 0, len)
                   os.flush()
               }
              os.close()
            
      }
    返回前端的是一个可以在浏览器上面访问的地址
    展开全文
  • 通过微信小程序接口,生成带参数的二维码,并下载之本地返回二维码图片地址
  • 工具类MpQrUtils.java,获取accessToken与二维码的输入流: import javax.servlet.http.HttpServletRequest; import com.alibaba.fastjson.JSONObject; import java.io.*; import java.net.HttpURLConnection;...

    直接上代码:

    工具类MpQrUtils.java,获取accessToken与二维码的输入流:

    
    
    import javax.servlet.http.HttpServletRequest;
    
    import com.alibaba.fastjson.JSONObject;
    
    import java.io.*;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.LinkedHashMap;
    import java.util.Map;
    
    public class MpQrUtils{
    
    
    	/**
    	 * 
    	 * @方法名称 getToken
    	 * @功能描述 <pre>获得accessToken,获取二维码需要</pre>
    	 * @作者    yw
    	 * @创建时间 2020年9月17日 上午11:06:42
    	 * @param appid
    	 * @param secret
    	 * @return
    	 */
        public  static String getToken(String appid, String secret) {
            try {
                Map<String, String> map = new LinkedHashMap<>();
                map.put("grant_type", "client_credential");
                map.put("appid", appid);//appid 小程序后台获取
                map.put("secret", secret);//app秘钥 小程序后台获取
                String rt = UrlUtil.sendPost("https://api.weixin.qq.com/cgi-bin/token", map);
                JSONObject json = JSONObject.parseObject(rt);
                if (json.getString("access_token") != null || json.getString("access_token") != "") {
                    return json.getString("access_token");
                } else {
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        
        /**
         * 
         * @方法名称 getminiqrQr
         * @功能描述 <pre>返回流 以便上传</pre>
         * @作者    yw
         * @创建时间 2020年9月17日 上午10:53:30
         * @param accessToken
         * @param userId
         * @return
         */
        public static InputStream getminiqrQr(String accessToken, Long userId) {
        	try
        	{
        		URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken);
        		HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        		httpURLConnection.setRequestMethod("POST");//post 必须 post
        		// 发送POST请求必须设置如下两行
        		httpURLConnection.setDoOutput(true);
        		httpURLConnection.setDoInput(true);
        		// 获取URLConnection对象对应的输出流
        		PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
        		// 发送请求参数
        		JSONObject paramJson = new JSONObject();
        		paramJson.put("scene","userId=" + userId);//这就是你二维码里携带的参数 String
        		paramJson.put("path", "pages/index/index"); //这是设置扫描二维码后跳转的页面
        		printWriter.write(paramJson.toString());
        		// flush输出流的缓冲
        		printWriter.flush();
        		return httpURLConnection.getInputStream();
        	}
        	catch (Exception e)
        	{
        		e.printStackTrace();
        	}
        	return null;
        }
    }
    
    

    控制层(为了简洁,直接在这个地方做了上传到oss):请求获取二维码链接

        /**
         * 
         * @方法名称 getShareQr
         * @功能描述 <pre>获取分享二维码</pre>
         * @作者    yw
         * @创建时间 2020年9月17日 上午10:32:19
         * @param request
         * @return
         * @throws IOException
         */
        @RequestMapping(value="getShareQr",method= RequestMethod.GET)
        public ResponseMsg getShareQr( HttpServletRequest request) throws IOException{
        	AdminUser user = TokenUtils.getCurUser(request);//通过token获得用户
        	AppUser appuser = appUserService.getUserByAppId(request.getHeader("appid"));//我这里是多个小程序,根据不同的小程序,获取不同的用户密码
            String accessToken = CreateQrcore.getToken(appuser.getAppId(), appuser.getAppSecret());
            InputStream ips = CreateQrcore.getminiqrQr(accessToken, user.getId());//获取的二维码流数据
            String newFileName = "xxxxx".png";//名称自定义
            uploadFilePathConfig.ossClient().putObject(uploadFilePathConfig.getBucketName(), newFileName, ips);//上传到oss
    		String returnUrl = uploadFilePathConfig.getAliyunImgDomain() + newFileName;
    		return new ResponseMsg(returnUrl);
        }

     

    展开全文
  • java生成小程序二维码-自定义参数

    千次阅读 2019-10-28 13:33:49
    第一次写博客,有点紧张,不足之处,请大佬们轻喷,代码也不是我自己写的,我也是这里copy一点那里copy一点,然后总结出来...微信官网小程序二维码API:https://developers.weixin.qq.com/miniprogram/dev/api/qrco...
  • Java后台生成小程序二维码

    千次阅读 2019-12-03 20:27:55
    微信小程序官方文档...在此使用接口B获取大量小程序码 接口B POST https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN ...
  • Java生成微信小程序二维码

    千次阅读 2019-05-20 15:01:29
    Java生成微信小程序二维码 import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io....
  • java调用微信小程序官方api生成二维码 提示:以下是本篇文章正文内容,下面案例可供参考 1.微信小程序官方文档 官方文档 代码如下(示例): String page="小程序路径(必须)"; //获取AccessToken String ...
  • 一、准备工作 微信公众平台接口调试工具 小程序的唯一标识(appid) 小程序的密钥(secret) 二、获取access_token 打开微信公众平台接口调试工具,在参数列表中输入小程序的appid和...生成小程序二维码官方文档 ht...
  • 简单粗暴,直接开干,获取 access_token public String getAccessToken() { try { StringBuilder url = new ... //固定参数 url.append("grant_type=").append("client_credential"); //微信小程序
  • Django后端实现生成小程序二维码 准备 1.在开发中心—小程序应用—选择小程序—开发管理–功能列表中添加‘小程序二维码’的功能。 支付宝小程序端 这部分看个人,可以自行传参到后端,用于扫描小程序的启动参数,...
  • java生成微信小程序二维码

    千次阅读 2019-06-11 09:12:40
    java中先编写url请求的工具类:UrlUtil,代码如下: package com.sinotrans.agent.basic.service.impl; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import ...
  • java生成带Logo二维码

    2013-03-08 15:42:29
    java可以生成二维码、解密二维码生成带logo二维码
  • java生成微信小程序二维码并保存/返回给前端 /** * @param 用于获取access_token * @param apiKey 小程序id * @param secretKey 小程序密钥 * @return access_token * @throws Exception */ @RequestMapping...
  • 生成小程序二维码传参scene的问题

    千次阅读 2020-05-11 13:37:59
    生成小程序二维码传参scene的问题 一、报错提示 '{"errcode":40169,"errmsg":"invalid length for scene, or the data is not json string hint: [MHecNHnre-dcD9Wa]"}' 原因:参数 scene 超过了32位 二、官方...
  • Java生成微信小程序二维码上传阿里云返回路径 1.先在yml配置微信参数 wx: appid: XXXXX appsecret: XXXXX 2.WXcode配置类 package com.yl.base.util; import com.alibaba.fastjson.JSON; import ...
  • java小程序生成二维码

    千次阅读 2019-05-08 13:20:00
    通过appId和secret获取小程序

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 11,866
精华内容 4,746
关键字:

java生成小程序二维码

java 订阅