如下是Java後臺生成一個小程序的完整代碼。java
import com.alibaba.fastjson.JSONObject; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.Base64; import java.util.HashMap; import java.util.Map; public class WxQrCode { private static final String GETWXACODEUNLIMIT_URL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s";// 生成小程序碼地址 private static final String URL_GET_TOKEN = "https://api.weixin.qq.com/cgi-bin/token";//獲取access_token地址 private static final String APP_ID = "";// 小程序appid private static final String APP_SECRET = ""; // 小程序祕鑰 public static final String PATH_HOME = ""; /** * 獲取微信Access_Token * @param appid * @param secret * @return */ public static String getWeixinAccessToken(String appid, String secret){ String url = URL_GET_TOKEN; Map<String, String> paramMap = new HashMap<String, String>(); paramMap.put("grant_type", "client_credential"); paramMap.put("appid", appid); paramMap.put("secret", secret); String content = HttpClientUtils.executeHttpGet(url, paramMap); Map map = (Map) JsonMapper.fromJsonString(content, HashMap.class); return (String)map.get("access_token"); } /** * 生成小程序碼返回base64字符串 * @param sceneStr 要攜帶的參數 * @param accessToken * @param page 要跳轉的小程序頁面(必須是已發佈的) * @return */ public static String getminiqrQr(String sceneStr, String accessToken,String page) { HttpURLConnection httpURLConnection = null; try { URL url = new URL(String.format(GETWXACODEUNLIMIT_URL,accessToken)); httpURLConnection = (HttpURLConnection) url.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", sceneStr); paramJson.put("page", page); printWriter.write(paramJson.toString()); // flush輸出流的緩衝 printWriter.flush(); //開始獲取數據 BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream()); try (InputStream is = httpURLConnection.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();){ byte[] buffer = new byte[1024]; int len = -1; while ((len = is.read(buffer)) != -1) { baos.write(buffer, 0, len); } return Base64.getEncoder().encodeToString(baos.toByteArray()); } } catch (Exception e) { e.printStackTrace(); }finally { if (httpURLConnection != null){ httpURLConnection.disconnect(); } } return null; } /** * 模擬調用 * @param args */ public static void main(String[] args) { String accessToken = getWeixinAccessToken(APP_ID,APP_SECRET); String qrBase64 = getminiqrQr("1024",accessToken,PATH_HOME); System.out.println(qrBase64); }
寫在後面:
1.以上代碼中HttpClientUtils用你本身項目中的請求工具類就好,無特殊要求;
2.以上生成代碼均模擬正常狀況下請求,未對一些異常進行處理,該部分自行處理;
3.正常業務中不會每次都調用微信接口獲取accessToken,通常是會放進緩存,定時更新,具體根據各自業務進行修改。json