java applet rear generating micro-channel two-dimensional code stored locally, the picture returns to the front end of the path

Get the applet code

The official address

https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html

 

To meet the different needs and scenarios, here are just two interfaces, developers can choose their own interface.

 

 

Interface B as an example:

Request address

POST https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN
可以看到请求地址需要
access_token,所以我们需要先获取 access_token
官方地址 https://developers.weixin.qq.com/doc/offiaccount/WeChat_Invoice/Nontax_Bill/API_list.html#1.1%20%E8%8E%B7%E5%8F%96access_token

Request address

Request the URL of: https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
request method: GET
Access_token first on the acquisition of two-dimensional code and access codes:
Package Comkymiksop.apiaikutil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
@ slf4j
public class WxQrCode {

    // get the path AccessToken 
    Private  static  Final String AccessToken_URL
             = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; // applet the above mentioned id
     // obtain two-dimensional code path 
    Private  static  Final String WxCode_URL
             = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN"; // applet key 
    / **
     * Used to obtain access_token
     * @return  access_token
     * @throws Exception
     */
    public static String getAccessToken(String appid,String secret) throws Exception {
        String requestUrl = AccessToken_URL.replace("APPID",appid).replace("APPSECRET",secret);
        URL the URL = new new the URL (requestUrl);
         // open a connection and the URL 
        the HttpURLConnection Connection = (the HttpURLConnection) url.openConnection ();
        connection.setRequestMethod ( "the POST" );
         // set the common request attribute 
        connection.setRequestProperty ( "the Content-the Type", "file application / JSON" );
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // output stream object obtained requested 
        the DataOutputStream OUT = new new the DataOutputStream (connection.getOutputStream ());
        out.writeBytes("");
        out.flush();
        out.close();

        // establishing an actual connection 
        connection.connect ();
         // define BufferedReader input stream in response to read the URL 
        BufferedReader in = null ;
         IF (requestUrl.contains ( "NLP" ))
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
        else
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        String result = "";
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result += getLine;
        }
        in.close();
        JSONObject jsonObject = JSON.parseObject(result);
        String accesstoken=jsonObject.getString("access_token");
        return accesstoken;
    }


    /*
     * Get the two-dimensional code picture
     *
     */
    public static String getminiqrQr(String accessToken,String uploadPath, HttpServletRequest request) {
        String ctxPath = uploadPath;
        String fileName="twoCode.png";
        String bizPath = "files";
        String nowday = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String ppath =ctxPath + File.separator + bizPath + File.separator + nowday;
        File file = new File(ctxPath + File.separator + bizPath + File.separator + nowday);
        if (!file.exists()) {
            file.mkdirs (); // create a file in the root directory 
        }
        String savePath = file.getPath() + File.separator + fileName;
        String qrCode = bizPath + File.separator + nowday+ File.separator + fileName;
//        if (ppath.contains("\\")) {
//            ppath = ppath.replace("\\", "/");
//        }
        if (qrCode.contains("\\")) {
            qrCode = qrCode.replace("\\", "/");
        }
//        String codeUrl=ppath+"/twoCode.png";
        System.out.print(qrCode);
        System.out.print(savePath);
        try
        {
//            URL url = new URL("https://api.weixin.qq.com/wxa/getwxacode?access_token="+accessToken);
            String wxCodeURL = WxCode_URL.replace("ACCESS_TOKEN",accessToken);
            URL url = new URL(wxCodeURL);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod ( "POST"); // commit mode
             // conn.setConnectTimeout (10000); // Connection Timeout in milliseconds
             // conn.setReadTimeout (2000); // Read Timeout in milliseconds
             // send a POST request must provided the following two lines 
            httpURLConnection.setDoOutput ( to true );
            httpURLConnection.setDoInput ( to true );
             // Get URLConnection object corresponding to the output stream 
            the PrintWriter a PrintWriter = new new the PrintWriter (httpURLConnection.getOutputStream ());
             // send a request parameter 
            the JSONObject paramJson = new new the JSONObject ();
            paramJson.put ( "SCENE", "1234567890" );
 //             paramJson.put ( "page", "Pages and the / index / index"); // applet yet released I did not bring the page parameter 
            paramJson.put ( "width ", 430 );
            paramJson.put("is_hyaline", true);
            paramJson.put("auto_color", true);
            /**
             * Line_color take effect
             * paramJson.put("auto_color", false);
             * JSONObject lineColor = new JSONObject();
             * lineColor.put("r", 0);
             * lineColor.put("g", 0);
             * lineColor.put("b", 0);
             * paramJson.put("line_color", lineColor);
             * */

            printWriter.write(paramJson.toString());
            // the flush stream output buffer 
            printWriter.flush ();
             // start acquiring data 
            BIS = BufferedInputStream new new BufferedInputStream (httpURLConnection.getInputStream ());
            OutputStream os = new FileOutputStream(new File(savePath));
            int len;
            byte[] arr = new byte[1024];
            while ((len = bis.read(arr)) != -1)
            {
                os.write(arr, 0, len);
                os.flush();
            }
            os.close();
        }
        catch (Exception e)
        {
            e.printStackTrace ();
        }
        return qrCode;
    }

}
 
 

I am a controller layer from the control layer parameter with the past

package com.yami.shop.api.owneruser.controller;

import com.alibaba.fastjson.JSONObject;
import com.yami.shop.api.Util.WxQrCode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@RequestMapping("/owner/code")
@RestController
public  class WxQrCodeController {

//    @Value("${ma.appid}")
    private String APIKEY="wxab03e9b278534a80";//小程序id
//    @Value("${ma.secret}")
    private String SECRETKEY="b992f830ec418093323d487ddd109e9f";//小程序密钥
    @Value("${file.path.upload}")
    private String uploadPath;

    /**
     * Receive two-dimensional code
     * @param request
     * @return
     * @throws IOException
     */
    @GetMapping(value="/code")
    public Object twoCode(HttpServletRequest request) throws IOException {
        JSONObject data=new JSONObject();
        String accessToken = null;
        try{
            accessToken = WxQrCode.getAccessToken(APIKEY,SECRETKEY);
            System.out.println("accessToken;"+accessToken);
            String twoCodeUrl = WxQrCode.getminiqrQr(accessToken,uploadPath,request);
            data.put("twoCodeUrl", twoCodeUrl);
            return data;
        }catch (Exception e){
            e.printStackTrace ();
        }
        return null;
    }


}
 

Acquiring two-dimensional code request parameters

Attributes Types of Defaults Mandatory Explanation
access_token string   Yes Interface calls credentials
scene string   Yes Up to 32 visible characters, only supports numerals, capital and some special characters: !#$&'()*+,/:;=?@-._~the other characters make themselves as a legitimate character encoding (because they do not support %, the Chinese can not use the  urlencode handle, use a different encoding)
page string Home no Must be a page has released a small program exists (or error), for example  pages/index/index, before filling the root path Do  /not carry parameters (please put scene field), if you do not fill in this field, the default home page jump
width number 430 no The width of the two-dimensional code, the unit px, 280px minimum, maximum 1280px
auto_color boolean false no Automatic configuration line color, if the color is still black, then not recommended to configure the main colors, default false
line_color Object {"r":0,"g":0,"b":0} no It is effective when false auto_color, for example, using set color rgb  {"r":"xxx","g":"xxx","b":"xxx"} decimal notation
is_hyaline boolean false no The need for transparent background, is true, the applet generation transparent background

return value

Buffer ( return pictures Buffer )

Abnormal return

Object

JSON

Attributes Types of Explanation
errcode number error code
errmsg string Error Messages

Errcode of legal values

value Explanation Minimum version
45009 Call minute frequency is limited (currently 5000 times / min, will be adjusted). For a large number of small procedural code, the recommended pre-generated.  
41030 Preaching page page does not exist, or applet is not released  

Return Value Description

If the call succeeds, it will return to direct the picture binary content, if the request fails, it returns data in JSON format.

 

 

Guess you like

Origin www.cnblogs.com/livedian/p/11804687.html