🐴

Apex:SlackAPIをApexから実行するための基本的なやつ

2021/03/17に公開

汎用的なApexコードです。

ソースコード

public class RequestSender {
    private final String token;
    private final String baseUrl;
    private Http http = new Http();

    public RequestSender(String token) {
        this(token, 'https://www.slack.com/api/');
    }

    public RequestSender(String token, String baseUrl) {
        this.token = token;
        this.baseUrl = baseUrl;
    }

    public class Response {
        public HttpResponse httpResponse;
        public Map<String, Object> body;
        public String rawBody;
        public Response(HttpResponse httpResponse) {
            this.httpResponse = httpResponse;
            this.rawBody = httpResponse.getBody();
            this.body = (Map<String, Object>) JSON.deserializeUntyped(this.rawBody);
        }
    }

    public Response callApi(
        String apiMethodName,
        Map<String, Object> params
    ) {
        HttpRequest request = new HttpRequest();
        request.setMethod('POST');
        request.setEndpoint(this.baseUrl + apiMethodName);
        request.setHeader('Content-Type', 'application/x-www-form-urlencoded');
        request.setHeader('Authorization', 'Bearer ' + this.token);
        Map<String, String> encodedParams = new Map<String, String>();
        String body = '';
        for (String name : params.keySet()) {
            if (params.get(name) != null) {
                String value = params.get(name).toString();
                body += '&' + name + '=' + EncodingUtil.urlDecode(value, 'utf-8');
            }
        }
        request.setBody(body.substring(1));
        return new Response(this.http.send(request));
    }
}

Discussion