LoginSignup
8
8

More than 5 years have passed since last update.

【LINEBOT】友達追加時にユーザIDをファイルに保存する【php】

Last updated at Posted at 2019-04-09

LINEBOTを作って、APIで通知を送ったりする際にユーザIDが必要になるが、こちらからチャンネルID等をキーにフォロワーのユーザIDを取得するAPIは用意してくれていないもよう…

というわけで、webhookでfollowイベント発生時にファイルにユーザIDを追加、unfollowイベント時に削除するサンプルプログラムです。サンプルなのでファイルの排他制御や保存場所のセキュリティとか適当です。

LINE Developerで登録したコールバックURLのエンドポイントがcallback.phpの場合

callback.php

// LINEからのコールバックデータ取得
$json_string = file_get_contents('php://input');
$json_obj = json_decode($json_string);

// webhookイベントタイプ
$type = $json_obj->events[0]->type;
// ユーザID
$user_id = $json_obj->events[0]->source->userId . "\n";

if ($type == 'follow') {
        // ユーザIDをuser.lstに保存
        file_put_contents("user.lst",$user_id,FILE_APPEND);
} else if ($type == 'unfollow') {
        $buf = "";
        $users = file('user.lst');

        foreach($users as $user) {
                if ($user != $user_id) {
                        $buf .= $user;
                }
        }
        // user.lst.wkに保存
        file_put_contents('user.lst.wk',$buf);
        // user.lst.wk を user.lst にリネーム
        exec('mv -f user.lst.wk user.lst');
} else {
        // noop        
}

補足
followイベント時はLINEからこんな情報がバックされます。(eventsという名前のセット)

// object->events[0]

{
      "replyToken": "ae93388a182e4f9faa28ff26377bf3f6",
      "type": "follow", 
      "timestamp": 1554793525328,
      "source": {
        "type": "user",
        "userId": "Uxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}
8
8
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
8
8