天天看點

微信小程式生成攜帶參數的小程式碼

具體文檔可以看這裡:擷取攜帶參數的小程式碼

第一步:擷取ACCESS_TOKEN

//擷取token的接口位址
    public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?" + "grant_type=client_credential&appid=APPID&secret=APPSECRET";

    /**
     * 擷取access_token
     * 
     * @param appid
     * @param appsecret
     * @return
     */
    public String getAccess_token(String appid, String appsecret) {
        try {
            String requestUrl = access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
            JSONObject jsonObject = httpRequst(requestUrl, "GET", null);
            return jsonObject.getString("access_token");
        } catch (Exception e) {
            return "errer";
        }
    }

/**
     * 
     * @Title: httpsRequest
     * @Description: 發送請求,傳回JSONObject對象
     * @param requestUrl
     * @param requestMethod
     * @param outputStr
     * @return
     * @throws Exception
     */
    public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) throws Exception {
        JSONObject jsonObject = null;
        try {
            // 使用自定義的信任管理器
            TrustManager[] tm = { new X509TrustManager() {
                /**
                 * 檢查用戶端證書
                 */
                @Override
                public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                }

                /**
                 * 檢查伺服器端證書
                 */
                @Override
                public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                }

                /**
                 * 傳回受信任的X509證書數組
                 */
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

            } };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            // 建立連接配接
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(ssf);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 設定請求方式
            conn.setRequestMethod(requestMethod);
            // 當outputStr不為null時,向輸出流寫資料
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 擷取輸入流
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            // 讀取響應内容
            StringBuffer buffer = new StringBuffer();
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            // 關閉資源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            conn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (Exception e) {
            throw new Exception("請求/解析失敗");
        }
        return jsonObject;
    }
           

第二步:生成小程式二維碼工具類

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;

/**
 * 
 * @ClassName: CreateImgUtil
 * @Description: 生成小程式二維碼工具類
 * @author cheng
 * @date 2017年9月13日 上午10:34:59
 */
@SuppressWarnings("deprecation")
public class CreateImgUtil {

    /**
     * 私有化構造函數,防止建立本工具類的執行個體
     */
    private CreateImgUtil() {
    }

    @SuppressWarnings({ "resource" })
    public static String httpPostWithJSON(String url, String json, String id,String dir) throws Exception {
        String result = null;
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
        StringEntity se = new StringEntity(json);
        se.setContentType("application/json");
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "UTF-8"));
        httpPost.setEntity(se);
        HttpResponse response = httpClient.execute(httpPost);
        if (response != null) {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                InputStream instreams = resEntity.getContent();
                File saveFile = new File(dir + id + ".png");
                // 判斷這個檔案(saveFile)是否存在
                if (!saveFile.getParentFile().exists()) {
                    // 如果不存在就建立這個檔案夾
                    saveFile.getParentFile().mkdirs();
                }
                saveToImgByInputStream(instreams, dir, id + ".png");
            }
        }
        httpPost.abort();
        return result;
    }

    /*
     * @param instreams 二進制流
     * 
     * @param imgPath 圖檔的儲存路徑
     * 
     * @param imgName 圖檔的名稱
     * 
     * @return 1:儲存正常 0:儲存失敗
     */
    private static int saveToImgByInputStream(InputStream instreams, String imgPath, String imgName) {

        int stateInt = ;
        if (instreams != null) {
            try {
                File file = new File(imgPath + imgName);// 可以是任何圖檔格式.jpg,.png等
                FileOutputStream fos = new FileOutputStream(file);

                byte[] b = new byte[];
                int nRead = ;
                while ((nRead = instreams.read(b)) != -) {
                    fos.write(b, , nRead);
                }
                fos.flush();
                fos.close();
            } catch (Exception e) {
                stateInt = ;
                e.printStackTrace();
            } finally {
                try {
                    instreams.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return stateInt;
    }
}
           

第三步:生成攜帶參數的小程式碼

// 依據公司資訊生成個性化小程式碼,傳回小程式碼名稱
    private String createImgByCompanyId(String companyId,String dir) {
        // 擷取token
        String appid = "wx8b3f3454sdfsdfsdgdfgdf4tr3402c2d7728";
        String appsecret = "c35b5a0b94ea1ece9c0rwerwerwer34wetwetre390468b3efed7";
        String token = getAccess_token(appid, appsecret);
        // 生成小程式碼接口url
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN".replace("ACCESS_TOKEN",
                token);
        // 二維碼中資訊
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("path", "pages/index/index");// 你二維碼中跳向的頁面
        map.put("scene", companyId);// 攜帶參數
        String json = JSONUtils.toJSONString(map);
        // 生成二維碼
        try {
            CreateImgUtil.httpPostWithJSON(url, json, companyId,dir);
            return companyId;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }