LoginSignup
2
0

More than 3 years have passed since last update.

Node.jsでLINE Beaconの最初の一歩のミニマムコードを書いてみる #botawards

Last updated at Posted at 2017-02-11

LINE Beaconを初めて使う時ってMassaging APIの仕様もわからずBeaconの仕様もわからず、反応してくれないけどどこに原因があるのか分かりにくいですね。

  • LINEのビジネスアカウント(BOTアカウント)を作成
  • ビジネスアカウントにBeaconを紐づける
  • 手元のLINEのアプリの設定 > プライバシー管理 > ビーコン利用をオンに
  • LINE Beaconの電源をオンに
  • ngrokなどでトンネリングする
  • トンネリングサーバーのhttpsアドレスをlinedevelopersに登録する
  • プログラムを作り起動する

など手順がありますが、最後のプログラム部分はサクッとログを出すためし方をするとハマらなくて良さそうです。

app.js
'use strict';

const http = require('http');
const PORT = process.env.PORT || 3000;

http.createServer((req, res) => {    
    if(req.url !== '/' || req.method !== 'POST'){
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('hello');
    }

    let body = '';
    req.on('data', (chunk) => {
        body += chunk;
    });        
    req.on('end', () => {
        if(body === ''){
          console.log('bodyが空です。');
          return;
        }

        let WebhookEventObject = JSON.parse(body).events[0];  
        if(WebhookEventObject.type === 'beacon'){
            console.log('beacon発見');
            console.log(WebhookEventObject);
            return;
        }  
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('success');
    });

}).listen(PORT);

console.log(`Server running at ${PORT}`);

起動させる

$ node app.js
Server running at 3000

ここで、LINEのアプリを再起動させたりすると反応があると思います。

beacon発見
{ type: 'beacon',
  replyToken: 'xxxxxxxxxxxxxxxxxxxxxxx',
  source: { userId: 'xxxxxxxxxxxxxxxxxxxxxx', type: 'user' },
  timestamp: 1486789863718,
  beacon: { hwid: 'xxxxxxxxxx', type: 'enter' } }

LINE Beaconの検知はアプリのバックグラウンドでも動作する想定っぽいのですが僕の手元だとこのやり方が一番結果が返ってきます。

本当にログを出すだけなので、ここから発言させたり他のAPIを使う時は認証情報を使いましょう。

2
0
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
2
0