LoginSignup
11
12

More than 5 years have passed since last update.

個人的にハッカソンとかで使う簡易WebAPIクラス

Posted at

ちょいと前に似たようなのを書いて、その二番煎じで、WebAPIを叩く最低限のスニペットを置いておきます。ハッカソンといえど認証キーを漏洩させるわけにはいかないので、

  • 作る時点で認証キーは外部ファイル化する
  • その外部ファイルが、うっかり公開されないよう最初の時点でhtaccessとgitignoreも用意する

という仕様にしています。素材はSlackです。

webapi.php
<?php

class WebAPI{

    public $ini;

    function __construct(){
        $this->ini = parse_ini_file("api.ini",true)["slack"];
    }

    function sendMessage($text){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_URL, $this->ini["hook"]);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($curl, CURLOPT_HTTPHEADER, [
            "Accept: application/json",
            "Content-type: application/json"
        ]);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode([
            'text'=>$text
        ]));
        return curl_exec($curl);
    }
}

$api = new WebAPI();
$response = $api->sendMessage("Hello");
var_dump($response);

外部ファイルは、こう書いておく。

[slack]
hook="https://hooks.slack.com/services/xxxx/xxxx"

これは、オマケ。

<Files ~ "\.(ini)$">
    deny from all
</Files>
11
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
12