LoginSignup
23
20

More than 5 years have passed since last update.

LINE MESSAGE APIを使用してユーザー情報を取得する

Last updated at Posted at 2016-10-24

このAPIについて

以前のDeveloper Trialから今回正式版としてLINE MESSAGE APIがリリースされました。
無料アカウントで使用できる範囲が比較的多いので、これから多岐に渡って活躍が期待できそうですね。
LINE BUSINESS CENTER

さらに今回複数の言語に対応したSDKも公開されました。
リファレンスも日本語に対応しているので使いやすく実装がより簡単になりました。
API Reference

今回の内容は以前投稿したDeveloper Trial用の「LINE BOTを使用してユーザー情報を取得する」と同様ユーザー情報を取得して返事をするBOTです。

事前準備

  • アカウントを登録
    Channel SecretChannel Access Tokenが必要になります。SSLの使用できるサーバーを用意してWebhook URLに設定を行います。)

  • composerを使用してSDKのインストール
    https://github.com/line/line-bot-sdk-php

require_once('./vendor/autoload.php');

new LineMessage;

class LineMessage{

  private $token = '[Channel Access Token]';
  private $secret = '[Channel Secret]';
  private $profile_array = array(); //プロフィールを格納する配列 displayName:表示名 userId:ユーザ識別子 pictureUrl:画像URL statusMessage:ステータスメッセージ

  private $replyToken;
  private $userId;
  private $httpClient;
  private $bot;

  function __construct(){

    $json_string = file_get_contents('php://input');
    $jsonObj = json_decode($json_string);
    $this->userId = $jsonObj->{"events"}[0]->{"source"}->{"userId"};
    $this->replyToken = $jsonObj->{"events"}[0]->{"replyToken"};

    $this->httpClient = new \LINE\LINEBot\HTTPClient\CurlHTTPClient($this->token);
    $this->bot = new \LINE\LINEBot($this->httpClient, ['channelSecret' => $this->secret]);

    $this->get_profile();

  }

  function get_profile(){

    $response = $this->bot->getProfile($this->userId);

    if ($response->isSucceeded()) {

      $profile = $response->getJSONDecodedBody();
      $displayName = $profile['displayName'];
      $userId = $profile['userId'];
      $pictureUrl = $profile['pictureUrl'];
      $statusMessage = $profile['statusMessage'];
      $this->profile_array = array("displayName"=>$displayName,"userId"=>$userId,"pictureUrl"=>$pictureUrl,"statusMessage"=>$statusMessage);
      $this->reply_message();
    }
  }

  function reply_message(){

    $textMessageBuilder = new \LINE\LINEBot\MessageBuilder\TextMessageBuilder($this->profile_array["displayName"]."さんこんにちは!");
    $response = $this->bot->replyMessage($this->replyToken, $textMessageBuilder);   
  }

}

注意事項(※2016/10/25時点)

現時点でAPI Referenceを参考に実装すると幾つかの不具合が生じます。
修正済 (2016/10/27)

Get Profileのレスポンス取得部分


$profile = decode_json($response->getBody);

$profile = json_decode($response->getRawBody());

関数のdecode_jsonをjson_decodeに変更します。
getBodyは使えないみたいです、GitHubを参考にするとレスポンスのボディ部分を取得する際にはどうやらgetRawBodyを使用するのが正解みたいです。

追記(※2016/10/27時点)

API Referenceに修正がありました。


$profile = decode_json($response->getBody);

$profile = $response->getJSONDecodedBody();

こちらのgetJSONDecodedBodyを使用する事によりレスポンスボディに対してJSONをデコードした配列で取得できるみたいです。

23
20
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
23
20