Génération de liens cryptés URL Scheme et URL Link pour Mini Programmes WeChat

Pour interagir avec l'API WeChat, nous utilisons la bibliothèque Hutool qui simplifie grandement les requêtes HTTP :

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-http</artifactId>
    <version>5.7.6</version>
</dependency>

Génération d'un lien URL Scheme crypté

Cette méthode permet d'obtenir un scheme qui ouvrira directement le Mini Programme avec les paramètres fournis :

public static String generateSchemeLink(String recordId, String phoneNumber) {
    String accessToken = fetchAccessToken();
    String endpoint = WeChatApiConstants.SCHEME_ENDPOINT + accessToken;

    JSONObject pageConfig = new JSONObject();
    pageConfig.putOpt("path", null);
    pageConfig.put("query", "recordId=" + recordId + "&phone=" + phoneNumber);
    pageConfig.put("env_version", weChatProperties.getEnvironmentVersion());

    JSONObject requestBody = new JSONObject();
    requestBody.put("jump_wxa", pageConfig);

    try {
        HttpResponse response = HttpUtil.createPost(endpoint)
                .contentType("application/json")
                .body(requestBody.toString())
                .timeout(10000)
                .execute();

        String decodedResponse = URLDecoder.decode(response.body(), StandardCharsets.UTF_8.name());
        log.info("Réponse API Scheme WeChat : {}", decodedResponse);

        JSONObject parsed = JSONUtil.parseObj(decodedResponse);
        if (parsed.getInt("errcode") == 0) {
            return parsed.getStr("openlink");
        }
    } catch (Exception ex) {
        log.error("Erreur lors de la génération du scheme", ex);
    }
    return null;
}

Génération d'un lien URL Link crypté

Cette approche utilise Apache HttpClient pour produire un lien URL Link accessbile depuis un navigtaeur externe :

public static String generateUrlLink(String recordId, String phoneNumber) {
    String accessToken = fetchAccessToken();
    String endpoint = WeChatApiConstants.URL_LINK_ENDPOINT + accessToken;

    JSONObject payload = new JSONObject();
    payload.put("env_version", weChatProperties.getEnvironmentVersion());
    payload.put("query", "recordId=" + recordId + "&phone=" + phoneNumber);

    HttpPost httpPost = new HttpPost(endpoint);
    httpPost.setEntity(new StringEntity(payload.toString(), ContentType.APPLICATION_JSON));

    try (CloseableHttpClient client = HttpClients.createDefault();
         CloseableHttpResponse apiResponse = client.execute(httpPost)) {

        String rawBody = EntityUtils.toString(apiResponse.getEntity());
        JSONObject resultJson = JSONUtil.parseObj(rawBody);
        log.info("Résultat URL Link : {}", resultJson);

        if (resultJson.getInt("errcode") == 0) {
            return resultJson.getStr("url_link");
        }
    } catch (IOException ex) {
        throw new RuntimeException("Échec de la requête URL Link", ex);
    }
    return null;
}

Format de réponse attendu

{
    "message": "Opération réussie",
    "data": "https://wxaurl.cn/BxOlgzooBmk",
    "apiCode": 0,
    "faultCode": 0,
    "success": true
}

Étiquettes: WeChat Mini Program URL Scheme URL Link Hutool Apache HttpClient

Publié le 24 juillet à 06h34