java后端生成微信小程序二維碼保存本地,將圖片路徑返回給前端


獲取小程序碼

官方地址

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

 

為滿足不同需求和場景,這里提供了兩個接口,開發者可挑選適合自己的接口。

 

 

接口B為例:

請求地址

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

請求地址

請求URL:https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
請求方法:GET
先上獲取access_token 與 獲取二維碼的代碼:
package com.yami.shop.api.Util;

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 {

    //獲取AccessToken路徑
    private static final String AccessToken_URL
            = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";//小程序id
    //獲取二維碼路徑
    private static final String WxCode_URL
            = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN";//小程序密鑰
    /**
     * 用於獲取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 url = new URL(requestUrl);
        // 打開和URL之間的連接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        // 設置通用的請求屬性
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // 得到請求的輸出流對象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.writeBytes("");
        out.flush();
        out.close();

        // 建立實際的連接
        connection.connect();
        // 定義 BufferedReader輸入流來讀取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;
    }


    /*
     * 獲取 二維碼圖片
     *
     */
    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();// 創建文件根目錄
        }
        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");// 提交模式
            // conn.setConnectTimeout(10000);//連接超時 單位毫秒
            // conn.setReadTimeout(2000);//讀取超時 單位毫秒
            // 發送POST請求必須設置如下兩行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 獲取URLConnection對象對應的輸出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 發送請求參數
            JSONObject paramJson = new JSONObject();
            paramJson.put("scene", "1234567890");
//            paramJson.put("page", "pages/index/index"); //小程序暫未發布我沒有帶page參數
            paramJson.put("width", 430);
            paramJson.put("is_hyaline", true);
            paramJson.put("auto_color", true);
            /**
             * line_color生效
             * 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());
            // flush輸出流的緩沖
            printWriter.flush();
            //開始獲取數據
            BufferedInputStream bis = 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;
    }

}
 
         

controller層  我是從控制層將參數帶過去的

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;

    /**
     * 接收二維碼
     * @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;
    }


}
 

獲取二維碼請求參數

屬性 類型 默認值 必填 說明
access_token string   接口調用憑證
scene string   最大32個可見字符,只支持數字,大小寫英文以及部分特殊字符:!#$&'()*+,/:;=?@-._~,其它字符請自行編碼為合法字符(因不支持%,中文無法使用 urlencode 處理,請使用其他編碼方式)
page string 主頁 必須是已經發布的小程序存在的頁面(否則報錯),例如 pages/index/index, 根路徑前不要填加 /,不能攜帶參數(參數請放在scene字段里),如果不填寫這個字段,默認跳主頁面
width number 430 二維碼的寬度,單位 px,最小 280px,最大 1280px
auto_color boolean false 自動配置線條顏色,如果顏色依然是黑色,則說明不建議配置主色調,默認 false
line_color Object {"r":0,"g":0,"b":0} auto_color 為 false 時生效,使用 rgb 設置顏色 例如 {"r":"xxx","g":"xxx","b":"xxx"} 十進制表示
is_hyaline boolean false 是否需要透明底色,為 true 時,生成透明底色的小程序

返回值

Buffer (返回的圖片 Buffer

異常返回

Object

JSON

屬性 類型 說明
errcode number 錯誤碼
errmsg string 錯誤信息

errcode 的合法值

說明 最低版本
45009 調用分鍾頻率受限(目前5000次/分鍾,會調整),如需大量小程序碼,建議預生成。  
41030 所傳page頁面不存在,或者小程序沒有發布  

返回值說明

如果調用成功,會直接返回圖片二進制內容,如果請求失敗,會返回 JSON 格式的數據。

 

 --------------------------------請多多指教


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM