LoginSignup
28

More than 5 years have passed since last update.

SSL証明書にお金をかけず、VPSでLINE BOTを作ってみた

Posted at

自分の好きな環境・サーバー・VPS等でLINE BOTを作りたいけど、SSL証明書にお金をかけるほどのモチベがない。

そこで、LINEが無料のSSL証明書を受け付けるまでとりあえず、Herokuを経由することで対処してみました。

Herokuを経由するので、ドメインやSSL証明書(https)は不要です。

Fixieは500回/月のリクエスト制限があるので使いたくない。。。

どうやってやるの?

流れ: LINE -> Heroku -> VPS -> LINE

  • LINEからの通知をHerokuで受け取る
  • HerokuからVPS等にPOSTで情報を転送
  • VPSからLINEに結果をPOST

作り方

LINEやHerokuのアカウント作成などは省略します。

Callback URLの設定

LINEのビジネスアカウントの「Basic Information」にある「Callback URL」にHerokuのアプリURLを指定します。

例: 「https://アプリ名.herokuapp.com:443」

Server IP Whitelistの設定

「Server IP Whitelist」にVPS等のIPアドレスを設定します。

LINE->Heroku->VPS用のスクリプト

下のスクリプトをHerokuにアップロードします。
このスクリプトはデータを転送しているだけです。

index.php
<?php
$json_string = file_get_contents('php://input');

$curl = curl_init("http://VPSへのURL");
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_POSTFIELDS, $json_string);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charser=UTF-8'));
curl_exec($curl);
curl_close($curl);
?>

VPS->LINE用のスクリプト

下のようなスクリプトをVPS側に配置します。
ここに返答のメインルーチンを記述します。

callback.php
<?php
$json_string = file_get_contents('php://input');
$json_obj = json_decode($json_string);
$to = $json_obj->result{0}->content->from;

$channel_id = "[チャンネルID]";
$channel_secret = "[チャンネルシークレット]";
$mid = "[MID]";

// 任意の処理で返答を作成する
$msg = "こんにちは( ´ ▽ ` )ノ";
$response_format_text = ['contentType'=>1, "toType"=>1, "text"=>"$msg"];

$post_data = ["to"=>[$to],"toChannel"=>"1383378250","eventType"=>"138311608800106203","content"=>$response_format_text];

// LINEに送信
$ch = curl_init("https://trialbot-api.line.me/v1/events");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json; charser=UTF-8',
    "X-Line-ChannelID: $channel_id",
    "X-Line-ChannelSecret: $channel_secret",
    "X-Line-Trusted-User-With-ACL: $mid"
));
curl_exec($ch);
curl_close($ch);
?>

最後に

あまりよろしい方法ではないかもしれませんが、とりあえずはこのような方法で自分の好きな環境・サーバーでLINE BOTが作れます。

LINEがLet's encryptなどの無料証明書を許可した際にはHerokuの経由をやめましょう。
スクリプトの変更は不必要なので修正は簡単だと思います。

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
28