PHPからchatwork API v2を叩くサンプル


sample.php

$chatToken = '{chatwork apiのトークン}';
$chatGroupId = '{投稿したいグループのID}';
$message = "This is test.\nMy name is test.";

$headers = [
    'X-ChatWorkToken: '.$chatToken
];

$option = [
    'body' => $message
];

$ch = curl_init( 'https://api.chatwork.com/v2/rooms/'.$chatGroupId.'/messages' );
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($option));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
curl_close($ch);

投稿したいチャットグループには、そのトークンを保持しているユーザーが入っていないと投稿できませんので、注意です。

The user whose token was issued by chatwork should be included in the chatgroup of the chatGroupId.
If not, this program can't post a message to the chatgroup.