LoginSignup
19
15

More than 5 years have passed since last update.

PHPで簡単なLINE BOTを動かす

Last updated at Posted at 2016-05-15

[目的]
LINE BOT API Trial Accountを利用してLINEボットを作る。

事前準備として、LINE BOT API Trial Account からアカウントを取得する。そして、コールバック通信にはSSL通信が必須なため、Webサーバをhttps化しておく必要がある。Webサーバのhttps化は Let's EncryptでSSL通信をしてhttps化 を行っておく。

Basic Informationの設定

LINEビジネスアカウント にログインしボットのアカウントの設定をする。

Callback URLの設定

Callback URLはポート名も含め、「https://サーバー:443/ほげほげ」の形式で入力する。

Server IP Whitelistの設定

コールバック先のサーバのIPを指定する。

実装

BOT APIのドキュメント を参考に実装する。

<?php
$request = file_get_contents("php://input");
$json = json_decode($request);
$content = $json->result[0]->content;

$header = array(
    'Content-Type: application/json; charser=UTF-8',
    'X-Line-ChannelID: 【Channel IDを指定】',  // Channel ID
    'X-Line-ChannelSecret: 【ChannelID Secretを指定】',  // ChannelID Secret
    'X-Line-Trusted-User-With-ACL: 【MIDを指定】',  // MID
);
$post = array(
    'to' => array($content->from),
    'toChannel' => 1383378250,  // Fixed value.
    'eventType' => '138311608800106203',  // Fixed value.
    'content' => array(
        'contentType' => 1,
        'toType' => 1,
    ),
);

// ボットが返答する内容。ここでは送られた内容を復唱するだけ
$post['content']['text'] = $content->text.' ですね';

$post = json_encode($post);

$ch = curl_init("https://trialbot-api.line.me/v1/events");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
19
15
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
19
15