shell java ruby go

Messaging API

LINE Platformが提供する Messaging API により、LINEのトーク画面を使った対話型Botアプリケーションの開発が可能になります。

Messaging APIを構成するコンポーネントは以下です。

Webhook

友だち追加情報やユーザから送信されたメッセージをリアルタイムに受信する仕組みです。

Reply Message API

ユーザから受信したメッセージやイベントに対して返信するAPIです。

Push Message API

任意のタイミングでユーザにメッセージを送信するAPIです。

Get Content API

ユーザから受信した画像や動画、音声をダウンロードするAPIです。

Get Profile API

ユーザのプロフィール情報を取得するAPIです。

Leave API

参加したグループやトークルームから退出するAPIです。

Common Spec

Messaging APIの各APIに共通の仕様を記載します。

Rate limits

APIごとに呼び出し回数の制限があります。
制限はプランによって異なります。

Plan Limit
Developer Trial 1,000/分
その他 10,000/分

Status codes

Messaging APIが返す主要なStatus Codeは以下です。

Error Code Description
200 OK リクエスト成功
400 Bad Request リクエストに問題があります。リクエストパラメータやJSONのフォーマットを確認してください。
401 Unauthorized Authorizationヘッダを正しく送信していることを確認してください。
403 Forbidden APIの利用権限がありません。ご契約中のプランを確認してください。
429 Too Many Requests アクセス頻度を制限内に抑えてください。
500 Internal Server Error APIサーバ側の一時的なエラーです。

Error Response

Error Response JSONの例

{
  "message": "Invalid parameter(s).",
  "details": [
      { "message": "'messages[0].text' is required." },
      { "message": "'messages[1].type' is invalid." }
  ]
}

エラー時のResponse Bodyは、以下のフィールドを持つJSONデータです。

Field Type Content
message String エラーの概要
details[].message String 詳細なエラー内容

Webhook

Webhook Request Bodyの例

{
  "events": [
      {
        "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA",
        "type": "message",
        "timestamp": 1462629479859,
        "source": {
             "type": "user",
             "userId": "u206d25c2ea6bd87c17655609a1c37cb8"
         },
         "message": {
             "id": "325708",
             "type": "text",
             "text": "Hello, world"
          }
      }
  ]
}

友だち追加やメッセージ送信などの イベント は、
Developer Center の Channel Consoleで設定されたWebhook URLに HTTPS POSTリクエスト で通知されます。

Botのサーバはこのリクエストを受信し、イベントに応じた処理を行ってください。

Request Headers

Request Header Content
X-Line-Signature 署名検証に使用するSignature

Request Body

Request Bodyは、Webhook Event Objectの配列を含むJSONオブジェクトです。

Field Type Content
events Array of Webhook Event Object 受信したイベント情報

Response

WebhookのHTTPS POSTリクエストに対しては、常にStatus Code 200を返してください。

Webhook Authentication

署名検証の例

String channelSecret = ...; // Channel secret string
String httpRequestBody = ...; // Request body string
SecretKeySpec key = new SecretKeySpec(channelSecret.getBytes(), "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(key);
byte[] source = httpRequestBody.getBytes("UTF-8");
String signature = Base64.encodeBase64String(mac.doFinal(source));
// Compare X-Line-Signature request header string and the signature

署名検証の例

CHANNEL_SECRET = ... # Channel Secret string
http_request_body = request.raw_post # Request body string
hash = OpenSSL::HMAC::digest(OpenSSL::Digest::SHA256.new, CHANNEL_SECRET, http_request_body)
signature = Base64.strict_encode64(hash)
# Compare X-Line-Signature request header string and the signature

署名検証の例

defer req.Body.Close()
body, err := ioutil.ReadAll(req.Body)
if err != nil {
    // ...
}
decoded, err := base64.StdEncoding.DecodeString(req.Header.Get("X-LINE-Signature"))
if err != nil {
    // ...
}
hash := hmac.New(sha256.New, []byte("<channel secret>"))
hash.Write(body)
// Compare decoded signature and `hash.Sum(nil)` by using `hmac.Equal`

X-Line-Signature Request Headerに入っているSignatureを検証することによって、
リクエストがLINE Platformから送信されたものであることを確認する必要があります。

検証は以下の手順で行います。

  1. Channel Secretを秘密鍵として、HMAC-SHA256アルゴリズムによりRequest Bodyのダイジェスト値を得る。
  2. ダイジェスト値をBASE64エンコードした文字列が、Request Headerに付与されたSignatureと一致することを確認する。

Webhook Event Object

{
  "events": [
    {
      "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA",
      "type": "message",
      "timestamp": 1462629479859,
      "source": {
        "type": "user",
        "userId": "u206d25c2ea6bd87c17655609a1c37cb8"
      },
      "message": {
        "id": "325708",
        "type": "text",
        "text": "Hello, world"
      }
    },
    {
      "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA",
      "type": "follow",
      "timestamp": 1462629479859,
      "source": {
        "type": "user",
        "userId": "u206d25c2ea6bd87c17655609a1c37cb8"
      }
    }
  ]
}

LINE Platformで発生したイベントを表すJSONオブジェクトです。

Common Fields

全てのWebhook Event Objectには以下のフィールドが含まれます。

Field Type Content
type String イベントの種類を表す識別子
timestamp Number イベントの時刻を表すミリ秒
source User
Group
Room
イベントの送信元を表すJSONオブジェクト

Source User

イベント送信元ユーザを表すオブジェクトです。

Field Type Content
type String user
userId String 送信元ユーザを表す識別子

Source Group

イベント送信元グループを表すオブジェクトです。

Field Type Content
type String group
groupId String 送信元グループを表す識別子

Source Room

イベント送信元トークルームを表すオブジェクトです。

Field Type Content
type String room
roomId String 送信元トークルームを表す識別子

Message Event

メッセージが送信されたことを示すEvent Objectです。
messageフィールドには、メッセージの種別ごとに異なるMessage Objectが含まれます。
このイベントは返信可能です。

Field Type Content
type String message
replyToken String このイベントへの返信に使用するトークン
message Text
Image
Video
Audio
Location
Sticker
メッセージ内容

Text Message

Text Messageの例

{
  "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA",
  "type": "message",
  "timestamp": 1462629479859,
  "source": {
    "type": "user",
    "userId": "u206d25c2ea6bd87c17655609a1c37cb8"
  },
  "message": {
    "id": "325708",
    "type": "text",
    "text": "Hello, world"
  }
}

イベント送信元から送信されたテキストを表すMessage Objectです。

Field Type Content
id String メッセージ識別子
type String text
text String メッセージのテキスト

Image Message

Image Messageの例

{
  "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA",
  "type": "message",
  "timestamp": 1462629479859,
  "source": {
    "type": "user",
    "userId": "u206d25c2ea6bd87c17655609a1c37cb8"
  },
  "message": {
    "id": "325708",
    "type": "image"
  }
}

イベント送信元から送信された画像を表すMessage Objectです。
Get Content APIにより画像バイナリデータを取得できます。

Field Type Content
id String メッセージ識別子
type String image

Video Message

Video Messageの例

{
  "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA",
  "type": "message",
  "timestamp": 1462629479859,
  "source": {
    "type": "user",
    "userId": "u206d25c2ea6bd87c17655609a1c37cb8"
  },
  "message": {
    "id": "325708",
    "type": "video"
  }
}

イベント送信元から送信された動画を表すMessage Objectです。
Get Content APIにより動画バイナリデータを取得できます。

Field Type Content
id String メッセージ識別子
type String video

Audio Message

Audio Messageの例

{
  "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA",
  "type": "message",
  "timestamp": 1462629479859,
  "source": {
    "type": "user",
    "userId": "u206d25c2ea6bd87c17655609a1c37cb8"
  },
  "message": {
    "id": "325708",
    "type": "audio"
  }
}

イベント送信元から送信された音声を表すMessage Objectです。
Get Content APIにより音声バイナリデータを取得できます。

Field Type Content
id String メッセージ識別子
type String audio

Location Message

Location Messageの例

{
  "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA",
  "type": "message",
  "timestamp": 1462629479859,
  "source": {
    "type": "user",
    "userId": "u206d25c2ea6bd87c17655609a1c37cb8"
  },
  "message": {
    "id": "325708",
    "type": "location",
    "title": "my location",
    "address": "〒150-0002 東京都渋谷区渋谷2丁目21−1",
    "latitude": 35.65910807942215,
    "longitude": 139.70372892916203
  }
}

イベント送信元から送信された位置情報を表すMessage Objectです。

Field Type Content
id String メッセージ識別子
type String location
title String タイトル
address String 住所
latitude Decimal 緯度
longitude Decimal 経度

Sticker Message

Sticker Messageの例

{
  "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA",
  "type": "message",
  "timestamp": 1462629479859,
  "source": {
    "type": "user",
    "userId": "u206d25c2ea6bd87c17655609a1c37cb8"
  },
  "message": {
    "id": "325708",
    "type": "sticker",
    "packageId": "1",
    "stickerId": "1"
  }
}

イベント送信元から送信されたStickerを表すMessage Objectです。
LINEの基本なStickerとその識別子の一覧は以下を参照ください。
Sticker一覧

Field Type Content
id String メッセージ識別子
type String sticker
packageId String パッケージ識別子
stickerId String Sticker識別子

Follow Event

Follow Eventの例

{
  "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA",
  "type": "follow",
  "timestamp": 1462629479859,
  "source": {
    "type": "user",
    "userId": "u206d25c2ea6bd87c17655609a1c37cb8"
  }
}

イベント送信元に友だち追加(またはブロック解除)されたことを示すEvent Objectです。
このイベントは返信可能です。

Field Type Content
type String follow
replyToken String このイベントへの返信に使用するトークン

Unfollow Event

Unfollow Eventの例

{
  "type": "unfollow",
  "timestamp": 1462629479859,
  "source": {
    "type": "user",
    "userId": "u206d25c2ea6bd87c17655609a1c37cb8"
  }
}

イベント送信元にブロックされたことを示すEvent Objectです。

Field Type Content
type String unfollow

Join Event

Join Eventの例

{
  "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA",
  "type": "join",
  "timestamp": 1462629479859,
  "source": {
    "type": "group",
    "groupId": "cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
  }
}

イベントの送信元グループまたはトークルームに参加したことを示すEvent Objectです。
このイベントは返信可能です。

Field Type Content
type String join
replyToken String このイベントへの返信に使用するトークン

Leave Event

Leave Eventの例

{
  "type": "leave",
  "timestamp": 1462629479859,
  "source": {
    "type": "group",
    "groupId": "cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
  }
}

イベントの送信元グループから退出させられたことを示すEvent Objectです。

Field Type Content
type String leave

Postback Event

Postback Eventの例

{
  "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA",
  "type": "postback",
  "timestamp": 1462629479859,
  "source": {
    "type": "user",
    "userId": "u206d25c2ea6bd87c17655609a1c37cb8"
  },
  "postback": {
    "data": "action=buyItem&itemId=123123&color=red"
  }
}

イベントの送信元が、Template Messageに付加されたポストバックアクションを実行したことを示すEvent Objectです。
このイベントは返信可能です。

Field Type Content
type String postback
replyToken String このイベントへの返信に使用するトークン
postback.data String ポストバックデータ

Beacon Event

Beacon Eventの例

{
  "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA",
  "type": "beacon",
  "timestamp": 1462629479859,
  "source": {
    "type": "user",
    "userId": "u206d25c2ea6bd87c17655609a1c37cb8"
  },
  "beacon": {
    "hwid": "d41d8cd98f",
    "type": "enter"
  }
}

イベント送信元のユーザがLINE Beaconデバイスに近づいたことを表すイベントです。
このイベントは返信可能です。

フィールド タイプ 内容
type String beacon
replyToken String このイベントへの返信に使用するトークン
beacon.hwid String 発見したビーコンデバイスのハードウェアID
beacon.type String ビーコンイベントの種別

Reply Message

Reply Message APIの例

curl -X POST \
-H 'Content-Type:application/json' \
-H 'Authorization: Bearer {ENTER_ACCESS_TOKEN}' \
-d '{
    "replyToken":"nHuyWiB7yP5Zw52FIkcQobQuGDXCTA",
    "messages":[
        {
            "type":"text",
            "text":"Hello, user"
        },
        {
            "type":"text",
            "text":"May I help you?"
        }
    ]
}' https://api.line.me/v2/bot/message/reply
TextMessage textMessage = new TextMessage("hello");
ReplyMessage replyMessage = new ReplyMessage(
        "<replyToken>",
        textMessage
);
Response<BotApiResponse> response =
        LineMessagingServiceBuilder
                .create("<channel access token>")
                .build()
                .replyMessage(replyMessage)
                .execute();
System.out.println(response.code() + " " + response.message());
bot, err := linebot.New(<channel secret>, <channel token>)
if err != nil {
    ...
}
if _, err := bot.ReplyMessage(<replyToken>, linebot.NewTextMessage("hello")).Do(); err != nil {
    ...
}
message = {
  type: 'text',
  text: 'hello'
}
client = Line::Bot::Client.new { |config|
    config.channel_secret = "<channel secret>"
    config.channel_token = "<channel access token>"
}
response = client.reply_message("<replyToken>", message)
p response

ユーザ、グループ、トークルームからのイベントに返信するAPIです。
Webhookで通知されたイベントの中で、返信可能なイベントにはreplyTokenが付与されています。
このトークンを指定することで、イベントの送信元にメッセージを返信することができます。

replyTokenは一定秒間以内に使用しないと無効になりますので、受信してから可能な限り速く返信してください。
使用回数の上限は1トークンにつき1回までです。

HTTP Request

POST https://api.line.me/v2/bot/message/reply

Request Headers

Request Header Content
Content-Type application/json
Authorization Bearer {Channel Access Token}

Request Body

送信するメッセージを表すSend Message Objectの配列を含めてください。

Field Type Content
replyToken String Webhookで受信したreplyToken
messages Array of Send Message Object 送信するメッセージ
最大5件

Response

Response JSONの例

{}

成功時はStatus Code 200 OKと共に空のJSONオブジェクトを返します。

Push Message

Push Message APIの例

curl -X POST \
-H 'Content-Type:application/json' \
-H 'Authorization: Bearer {ENTER_ACCESS_TOKEN}' \
-d '{
    "to": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "messages":[
        {
            "type":"text",
            "text":"Hello, world1"
        },
        {
            "type":"text",
            "text":"Hello, world2"
        }
    ]
}' https://api.line.me/v2/bot/message/push
TextMessage textMessage = new TextMessage("hello");
PushMessage pushMessage = new PushMessage(
        "<to>",
        textMessage
);

Response<BotApiResponse> response =
        LineMessagingServiceBuilder
                .create("<channel access token>")
                .build()
                .pushMessage(pushMessage)
                .execute();
System.out.println(response.code() + " " + response.message());
bot, err := linebot.New(<channel secret>, <channel token>)
if err != nil {
    ...
}
if _, err := bot.PushMessage(<to>, linebot.NewTextMessage("hello")).Do(); err != nil {
    ...
}
message = {
  type: 'text',
  text: 'hello'
}
client = Line::Bot::Client.new { |config|
    config.channel_secret = "<channel secret>"
    config.channel_token = "<channel access token>"
}
response = client.push_message("<to>", message)
p response

ユーザ、グループ、トークルームに任意のタイミングでメッセージを送信するAPIです。

HTTP Request

POST https://api.line.me/v2/bot/message/push

Request Headers

Request Header Content
Content-Type application/json
Authorization Bearer {Channel Access Token}

Request Body

送信するメッセージを表すSend Message Objectの配列を含めてください。

Field Type Content
to String 送信先識別子
messages Array of Send Message Object 送信するメッセージ
最大5件

Response

Response JSONの例

{}

成功時はStatus Code 200 OKと共に空のJSONオブジェクトを返します。

Send Message Object

送信するメッセージの内容を表すJSONオブジェクトです。

Text

Textの例

{
    "type": "text",
    "text": "Hello, world"
}
Field Type Content
type String text
text String メッセージのテキスト

Image

Imageの例

{
    "type": "image",
    "originalContentUrl": "https://example.com/original.jpg",
    "previewImageUrl": "https://example.com/preview.jpg"
}
Field Type Content
type String image
originalContentUrl String 画像のURL
HTTPS
JPEG
縦横最大1024px
最大1MB
previewImageUrl String プレビュー画像のURL
HTTPS
JPEG
縦横最大240px
最大1MB

Video

Videoの例

{
    "type": "video",
    "originalContentUrl": "https://example.com/original.mp4",
    "previewImageUrl": "https://example.com/preview.jpg"
}
Field Type Content
type String video
originalContentUrl String 動画ファイルのURL
HTTPS
mp4
長さ1分以下
最大10MB
previewImageUrl String プレビュー画像のURL
HTTPS
JPEG
縦横最大240px
最大1MB

Audio

Audioの例

{
    "type": "audio",
    "originalContentUrl": "https://example.com/original.m4a",
    "duration": 240000
}
Field Type Content
type String audio
originalContentUrl String 音声ファイルのURL
HTTPS
m4a
長さ1分以下
最大10MB
duration Number 音声ファイルの時間長さ(ミリ秒)

Location

Locationの例

{
    "type": "location",
    "title": "my location",
    "address": "〒150-0002 東京都渋谷区渋谷2丁目21−1",
    "latitude": 35.65910807942215,
    "longitude": 139.70372892916203
}
Field Type Content
type String location
title String タイトル
address String 住所
latitude Decimal 緯度
longitude Decimal 経度

Sticker

Stickerの例

{
  "type": "sticker",
  "packageId": "1",
  "stickerId": "1"
}

Messaging APIから送信できるStickerの識別子は以下を参照ください。
Sticker一覧

Field Type Content
type String sticker
packageId String パッケージ識別子
stickerId String Sticker識別子

Imagemap Message

Imagemapはリンク付きの画像コンテンツです。画像全体を1つのリンクとしたり、画像の複数の領域に異なるリンクURLを指定することもできます。

左右2つのタップ領域を持つImagemap

{
  "type": "imagemap",
  "baseUrl": "https://example.com/bot/images/rm001",
  "altText": "this is an imagemap",
  "baseSize": {
      "height": 1040,
      "width": 1040
  },
  "actions": [
      {
          "type": "uri",
          "linkUri": "https://example.com/",
          "area": {
              "x": 0,
              "y": 0,
              "width": 520,
              "height": 1040
          }
      },
      {
          "type": "message",
          "text": "hello",
          "area": {
              "x": 520,
              "y": 0,
              "width": 520,
              "height": 1040
          }
      }
  ]
}
Field Type Content
type String imagemap
baseUrl String Imagemapに使用する画像のBase URL
HTTPS
altText String 代替テキスト
baseSize.width Number 基本比率サイズの幅(1040を指定してください)
baseSize.height Number 基本比率サイズの高さ(幅を1040としたときの高さを指定してください)
actions Array of Imagemap Action Object タップ時のアクション

Base URL

Imagemapに使用する画像は、Base URLの末尾に、クライアントが要求する解像度を横幅サイズ(px)で付与したURLでダウンロードできるようにしておく必要があります。

例として、Base URLに以下を指定した場合、

https://example.com/images/cats

クライアント端末が幅700pxの解像度をダウンロードするURLは以下になります。

https://example.com/images/cats/700

クライアント端末から要求される横幅サイズは以下のいずれかになります。

横幅サイズ(px)
1040, 700, 460, 300, 240

Imagemapに使用できる画像の仕様は以下です。

フォーマット
JPEG または PNG
ファイルサイズ
最大1MB

Imagemap Action Object

Imagemapに配置するアクションの内容とタップ領域の位置を指定するオブジェクトです。

タップされたときに指定のURIを開くuriと、特定のメッセージ送信をおこなうmessageの2種類があります。

URI Action

Field Type Content
type String uri
linkUri String WebページのURL
area Imagemap Area Object タップ領域の定義

Message Action

Field Type Content
type String message
text String 送信するメッセージ
area Imagemap Area Object タップ領域の定義

Imagemap Area Object

Imagemap全体の幅を1040pxとしたときのサイズを指定します。各座標は左上を原点とします。

Field Type Content
x Number タップ領域の横方向の位置
y Number タップ領域の縦方向の位置
width Number タップ領域の幅
height Number タップ領域の高さ

Template Message

Template Messageは、あらかじめ定義されたレイアウトのテンプレートにカスタムデータを挿入することによって構築するメッセージです。

Bot API v2では、Botとユーザのインタラクティブなコミュニケーションに役立つ3種類のテンプレートを用意しています。

Field Type Content
type String template
altText String 代替テキスト
template Buttons
Confirm
Carousel
テンプレートの内容を表すオブジェクト

Buttons

Buttonsの例

{
  "type": "template",
  "altText": "this is a buttons template",
  "template": {
      "type": "buttons",
      "thumbnailImageUrl": "https://example.com/bot/images/image.jpg",
      "title": "Menu",
      "text": "Please select",
      "actions": [
          {
            "type": "postback",
            "label": "Buy",
            "data": "action=buy&itemid=123"
          },
          {
            "type": "postback",
            "label": "Add to cart",
            "data": "action=add&itemid=123"
          },
          {
            "type": "uri",
            "label": "View detail",
            "uri": "http://example.com/page/123"
          }
      ]
  }
}

画像、タイトル、テキストと、複数のアクションボタンを組み合わせたテンプレートメッセージです。

Field Type Content
type String buttons
thumbnailImageUrl String 画像のURL
HTTPS
JPEGまたはPNG
縦横比 1:1.51
縦横最大1024px
最大1MB
title String タイトル
40文字以内
text String 説明文
画像もタイトルも指定しない場合:160文字以内
画像またはタイトルを指定する場合:60文字以内
actions Array of Template Action ボタン押下時のアクション
最大4個

thumbnailImageUrltitleは省略可能です。

Confirm

Confirmの例

{
  "type": "template",
  "altText": "this is a confirm template",
  "template": {
      "type": "confirm",
      "text": "Are you sure?",
      "actions": [
          {
            "type": "message",
            "label": "Yes",
            "text": "yes"
          },
          {
            "type": "message",
            "label": "No",
            "text": "no"
          }
      ]
  }
}

2つのアクションボタンを提示するテンプレートメッセージです。

Field Type Content
type String confirm
text String 説明文
240文字以内
actions Array of Template Action ボタン押下時のアクション
最大2個

Carouselの例

{
  "type": "template",
  "altText": "this is a carousel template",
  "template": {
      "type": "carousel",
      "columns": [
          {
            "thumbnailImageUrl": "https://example.com/bot/images/item1.jpg",
            "title": "this is menu",
            "text": "description",
            "actions": [
                {
                    "type": "postback",
                    "label": "Buy",
                    "data": "action=buy&itemid=111"
                },
                {
                    "type": "postback",
                    "label": "Add to cart",
                    "data": "action=add&itemid=111"
                },
                {
                    "type": "uri",
                    "label": "View detail",
                    "uri": "http://example.com/page/111"
                }
            ]
          },
          {
            "thumbnailImageUrl": "https://example.com/bot/images/item2.jpg",
            "title": "this is menu",
            "text": "description",
            "actions": [
                {
                    "type": "postback",
                    "label": "Buy",
                    "data": "action=buy&itemid=222"
                },
                {
                    "type": "postback",
                    "label": "Add to cart",
                    "data": "action=add&itemid=222"
                },
                {
                    "type": "uri",
                    "label": "View detail",
                    "uri": "http://example.com/page/222"
                }
            ]
          }
      ]
  }
}

複数の情報を並べて提示できるカルーセル型のテンプレートメッセージです。

Field Type Content
type String carousel
columns Array of Column Object カラムの配列
最大5個

Column Object

Field Type Content
thumbnailImageUrl String 画像のURL
HTTPS
JPEGまたはPNG
縦横比 1:1.51
縦横最大1024px
最大1MB
title String タイトル
40文字以内
text String 説明文
画像もタイトルも指定しない場合:120文字以内
画像またはタイトルを指定する場合:60文字以内
actions Array of Template Action ボタン押下時のアクション
最大3個

各カラムのthumbnailImageUrltitleは省略可能です。

Template Action

テンプレートメッセージに付加するアクションです。

Postback Action

このアクションをタップすると、dataで指定された文字列がPostback EventとしてWebhookで通知されます。

textを指定した場合、その内容がユーザの発言として同時に送信されます。

Field Type Content
type String postback
label String アクションの表示名
20文字以内
data String WebhookにPostback Eventpostback.dataプロパティとして送信される文字列データ
300文字以内
text String アクション実行時に送信されるテキスト
300文字以内

textは省略可能です。

Message Action

このアクションをタップすると、textで指定された文字列がユーザの発言として送信されます。

Field Type Content
type String message
label String アクションの表示名
20文字以内
text String アクション実行時に送信されるテキスト
300文字以内

URI Action

このアクションをタップすると、uriで指定されたURIを開きます。

Field Type Content
type String uri
label String アクションの表示名
20文字以内
uri String アクション実行時に開くURI
http, https, tel

Get Content

curl -X GET \
-H 'Authorization: Bearer {ENTER_ACCESS_TOKEN}' \
https://api.line.me/v2/bot/message/{messageId}/content
Response<ResponseBody> response =
        LineMessagingServiceBuilder
                .create("<channel access token>")
                .build()
                .getMessageContent("<messageId>")
                .execute();
if (response.isSuccessful()) {
    ResponseBody content = response.body();
    Files.copy(content.byteStream(),
               Files.createTempFile("foo", "bar"));
} else {
    System.out.println(response.code() + " " + response.message());
}
bot, err := linebot.New(<channel secret>, <channel token>)
if err != nil {
    ...
}
content, err := bot.GetMessageContent(<messageID>).Do()
if err != nil {
    ...
}
defer content.Content.Close()

...
client = Line::Bot::Client.new { |config|
    config.channel_secret = "<channel secret>"
    config.channel_token = "<channel access token>"
}
response = client.get_message_content("<messageId>")
if response.code == 200 {
  tf = Tempfile.open("content")
  tf.write(response.body)
} else {
  p "#{response.code} #{response.body}"
}

ユーザから送信された画像、動画、音声にアクセスするAPIです。

HTTP Request

GET https://api.line.me/v2/bot/message/{messageId}/content

Request Headers

Request Header Content
Authorization Bearer {Channel Access Token}

URL Parameters

Parameter Content
messageId メッセージの識別子

Response

成功時はStatus Code 200 OKと共にコンテンツのバイナリデータを返します。

Get Profile

curl -X GET \
-H 'Authorization: Bearer {ENTER_ACCESS_TOKEN}' \
https://api.line.me/v2/bot/profile/{userId}
Response<UserProfileResponse> response =
        LineMessagingServiceBuilder
                .create("<channel access token>")
                .build()
                .getProfile("<userId>")
                .execute();
if (response.isSuccessful()) {
    UserProfileResponse profile = response.body();
    System.out.println(profile.getDisplayName());
    System.out.println(profile.getPictureUrl());
    System.out.println(profile.getStatusMessage());
} else {
    System.out.println(response.code() + " " + response.message());
}
bot, err := linebot.New(<channel secret>, <channel token>)
if err != nil {
    ...
}
res, err := bot.GetUserProfile(<userId>).Do();
if err != nil {
    ...
}
println(res.Displayname)
println(res.PicutureURL)
println(res.StatusMessage)
client = Line::Bot::Client.new { |config|
    config.channel_secret = "<channel secret>"
    config.channel_token = "<channel access token>"
}
response = client.get_profile("<userId>")
if response.code == 200 {
  contact = JSON.parse(response.body)
  p contact['displayName']
  p contact['pictureUrl']
  p contact['statusMessage']
}

ユーザのプロフィール情報を取得するAPIです。

HTTP Request

GET https://api.line.me/v2/bot/profile/{userId}

Request Headers

Request Header Content
Authorization Bearer {Channel Access Token}

URL Parameters

Parameter Content
userId ユーザ識別子

Response

Response Bodyの例

{
    "displayName":"LINE taro",
    "userId":"Uxxxxxxxxxxxxxx...",
    "pictureUrl":"http://dl.profile.line.naver.jp/...",
    "statusMessage":"Hello, LINE!"
}

成功時はStatus Code 200 OKと共に以下のパラメータを持つJSONオブジェクトを返します。

Field Type Content
displayName String 表示名
userId String ユーザ識別子
pictureUrl String 画像URL
statusMessage String ステータスメッセージ

Leave

curl -X POST \
-H 'Authorization: Bearer {ENTER_ACCESS_TOKEN}' \
https://api.line.me/v2/bot/room/{roomId}/leave
Response<BotApiResponse> response =
        LineMessagingServiceBuilder
                .create("<channel access token>")
                .build()
                .leaveRoom("<roomId>")
                .execute();
System.out.println(response.code() + " " + response.message());
bot, err := linebot.New(<channel secret>, <channel token>)
if err != nil {
    ...
}
if _, err := bot.LeaveRoom(<roomId>).Do(); err != nil {
    ...
}
client = Line::Bot::Client.new { |config|
    config.channel_secret = "<channel secret>"
    config.channel_token = "<channel access token>"
}
response = client.leave_room("<roomId>")
p response.body

グループまたはトークルームから退出するAPIです。

HTTP Request

POST https://api.line.me/v2/bot/group/{groupId}/leave

POST https://api.line.me/v2/bot/room/{roomId}/leave

Request Headers

Request Header Content
Authorization Bearer {Channel Access Token}

URL Parameters

Parameter Content
groupId グループの識別子
roomId トークルームの識別子

Response

Response JSONの例

{}

成功時はStatus Code 200 OKと共に空のJSONオブジェクトを返します。

LINE Beacon

LINE Beacon は、「連携しているLINEユーザがビーコンに近づいたことをWebhookで即座にBotが知ることができる」サービスです。

特別なビーコンデバイスとLINEユーザの相対的な位置関係を使い、特定のLINEユーザに対して特別なサービスを提供することがより簡単に実現できるようになります。

How to Connect Bot-Beacon

LINE Official Account ManagerでビーコンとBotアカウントを結びつけてください。

How to receive Webhooks from the LINE User.

  1. LINEがインストールされているスマートフォンの bluetoothをonにしてください
  2. 「LINE Beaconを利用」にチェックを入れてください
    • LINE -> 設定 -> プライバシー管理 -> 「LINE Beaconを利用」
  3. Botアカウントを友達に追加してください
    • Botアカウントと連携していないLINEユーザの情報は送られません。
  4. ビーコンデバイスの電源が入っていることを確認し、スマートフォンを近づけて下さい。
    • LINEアプリがビーコンを検知し、その情報をLINEプラットフォームに送信します。

Info. One-Stop-Receiving with Beacon Layer

ビーコンデバイス付近のユーザのfriend listとtalk list 上に専用のバナー(Beacon Layer)を表示させる施策を、一部の店舗/建物で実施しています。

Beacon Layer をタップすると、「2. LINE Beacon を利用」と「3. 友だち追加」を同時に行うことができ、ビーコンによる友だち追加とメッセージ配信をワンストップで行うことが可能となります。

こちらの機能の利用をご希望の際は、LINE Partner よりお問い合わせ下さい。

Social REST API

How to use

RESTFul API を利用するにはまず Access Token の発行が必要になります。
下記の RESTFul API はデフォルトの権限で利用できるものになります。

Validate Access Token

Validate Access Token の例

curl -X GET \
-H 'Authorization: Bearer {ENTER_ACCESS_TOKEN}' \
https://api.line.me/v1/oauth/verify

{
  "channelId":1350031035,
  "mid":"ub00b9ac609e51f4707cd86d8e797491b"
}

取得した Acces Token を Validation するために利用します。

Request Header

Item Description
HTTP Method GET
Endpoint URL https://api.line.me/v1/oauth/verify
Required request header Authorization: Bearer {ACCESS_TOKEN}

Query Parameter

Name Type Default value Description
extend String false Optional になります。'true’ に設定することで Access Token の有効期限を取得することが可能になります。

Response

レスポンスはJSON フォーマットで返却されます。

Property Type Description
mid String Access Token を認可したユーザーの識別ID。
channelId String Access Token 発行元の Channel ID です。 
expire Integer Access Token の有効期限です。エポック秒 January 1 1970 00:00:00 GMTからの経過時間をミリ秒単位で表記したものになります。

Error Response

エラー発生時には以下のエラーが返却されます。

HTTP status Response body & Reason
401 {“statusCode”:“401”,“statusMessage”:“authentication scheme not found.”}
Request に Authorization ヘッダが設定されていません。
Authorization: Bearer {ACCESS_TOKEN} を HTTP Header に指定してください。
401 {“statusCode”:“401”,“statusMessage”:“invalid token”}
指定した Access Token が無効です。
401 {“statusCode”:“412”,“statusMessage”:“accessToken expired(1)”}
Access Token がプラットフォーム側により無効とされました。
401 {“statusCode”:“412”,“statusMessage”:“accessToken expired”}
Access Token が有効期限切れとなりました。

Reissue Access Token

Reissue Access Token の例

curl -X POST \
-H 'Authorization: Bearer {ENTER_ACCESS_TOKEN}' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'refreshToken=123ab456cdef8910ghu' \
https://api.line.me/v1/oauth/accessToken

{
  "mid":"u0047556f2e40dba2456887320ba7c76d",
  "accessToken":"ud81c65b01f5a59d39f8163815b34dad7aXNzdWVkV",
  "expire":1371721724089,
  "refreshToken":"ZkcqmSWsKnMSXq5hPpWd"
}

Refresh Token から Access Token の再発行を行います。
Refresh Token は Access Token 取得時のレスポンス json (refresh_token) に含まれます。
Refresh Token は Access Token の有効期限を過ぎてから10日間は有効です。Refresh Token の期限が切れた場合はユーザに再認可を行っていただく必要があります。

Request Header

Item Description
HTTP Method POST
Endpoint URL https://api.line.me/v1/oauth/accessToken
Required request header Content-Type: application/x-www-form-urlencoded
Authorization: Bearer {ACCESS_TOKEN}

Request Body

Request body は form-encoded フォーマットになります。

Name Type Description
refreshToken String 再発行する Access Token の Refresh Token を入力します。

Response

レスポンスはJSON フォーマットで返却されます。

Property Type Description
mid String ユーザーの識別ID
accessToken String Access Token
expire Integer Access Token の有効期限です。エポック秒 January 1 1970 00:00:00 GMTからの経過時間をミリ秒単位で表記したものになります。
refreshToken String Access Token の再発行に利用します。Access Token の有効期限から10日間は有効です。

Error Response

エラー発生時には以下のエラーが返却されます。

HTTP status Response body & Reason
401 {“statusCode”:“412”,“statusMessage”:“accessToken expired(1)”}
Access Token がプラットフォーム側により無効とされました。
401 {“statusCode”:“412”,“statusMessage”:“accessToken expired(2)”}
ユーザーがLINE から退会しました。
401 {“statusCode”:“412”,“statusMessage”:“accessToken expired”}
Access Token が有効期限切れとなりました。
401 {“statusCode”:“401”,“statusMessage”:“invalid token”}
指定した Access Token が無効です。
401 {“statusCode”:“401”,“statusMessage”:“invalid refreshToken”}
指定した Refresh Token が無効です。
403 {“statusCode”:“414”,“statusMessage”:“TOKEN_NOT_REFRESHABLE”}
Access Token の再発行は現在できません。
401 {“statusCode”:“411”,“statusMessage”:“TOKEN_INVALID_TOKEN”}
Access Token と Refresh Token の組み合わせが無効です。
401 {“statusCode”:“401”,“statusMessage”:“channel secret is not matched. maybe abusing?”}
指定した Channel の Secret が一致しません。
403 {“statusCode”:“418”,“statusMessage”:“CHANNEL_INACTIVE”}
Channel が無効です。

Logout

Logout の例

curl -X DELETE \
-H 'Authorization: Bearer {ENTER_ACCESS_TOKEN}' \
https://api.line.me/v1/oauth/logout

{"result":"OK"}

ユーザーを連携中のアプリから Logout (連携解除)させます。連携解除になるため、発行された Access Token は無効となります。

Request Header

Item Description
HTTP Method DELETE
Endpoint URL https://api.line.me/v1/oauth/logout
Required request header Authorization: Bearer {ACCESS_TOKEN}

Response

レスポンスはJSON フォーマットで返却されます。エラーレスポンスはありません。

Property Type Description
result String “OK"固定になります。

Get Profile

Get Profile の例

curl -X GET \
-H 'Authorization: Bearer {ENTER_ACCESS_TOKEN}' \
https://api.line.me/v1/profile

{
  "displayName":"Brown",
  "mid":"u0047556f2e40dba2456887320ba7c76d",
  "pictureUrl":"http://example.com/abcdefghijklmn",
  "statusMessage":"Hello, LINE!"
}

ユーザーの表示名、プロフィール画像とステータスメッセージを取得することができます。

Request Header

Item Description
HTTP Method GET
Endpoint URL https://api.line.me/v1/profile
Required request header Authorization: Bearer {ACCESS_TOKEN}

Response

レスポンスはJSON フォーマットで返却されます。

Property Type Description
displayName String ユーザーの表示名
mid String ユーザー識別ID
pictureUrl String プロフィール画像 URL。 "http” の画像 URL になります。
statusMessage String ユーザーのステータスメッセージ。 ユーザーが指定していないとレスポンス JSON に含まれません。

プロフィール画像のサムネイル

large の 画像を取得するためにアクセスするURLの例

http://example.com/abcdefghijklmn/large

ユーザーのプロフィール画像を取得時に URLに Suffix を追加することで画像のサイズを変更できます。

Image size Suffix
200 x 200 /large
51 x 51 /small

Android SDK API

LINE SDK for Android では、以下のAPIを提供しています。
LINE SDK for Android では、APIを呼び出す際に、access token を自動的にリフレッシュするため、access token を意識することなく、APIを呼び出すことができます。

Retrieve Access Token

Access Token 取得の実装例

Activity activity = ...;
LineAuthManager authManager = ...;
LineLoginFuture loginFuture = authManager.login(activity);
loginFuture.addFutureListener(new LineLoginFutureListener() {
    @Override
    public void loginComplete(LineLoginFuture future) {
      switch(future.getProgress()) {
          case SUCCESS:
            ...
              AccessToken token = future.getAccessToken();
              String mid = token.mid; // User ID
              String accessToken = token.accessToken;
              long expire = token.expire; // Expired datetime
              String refreshToken = token.refreshToken;
              // Send these data to your server.
              break;
            ...
        }
    }
});

メソッド

LineLoginFuture#getAccessToken()

実装例

LINE SDK から access token を取得し、サーバーに転送することにより、Social REST API をサーバー側からコールすることができます。
access token を転送する場合は、事前に access token をハッシュ化し、SSL 通信にて転送すること推奨しています。

Get Profile

事前準備

プロフィール情報を取得するには、次の2つが満たされている必要があります。

メソッド

ApiClient#getMyProfile()

プロフィール情報取得の実装例

ApiClient apiclient = LineSdkContextManager.getSdkContext().getApiClient();
apiClient.getMyProfile(new ApiRequestFutureListener() {
    @Override
    public void requestComplete(ApiRequestFuture future) {
      switch(future.getStatus()) {
          case SUCCESS:
              Profile profile = future.getResponseObject();
              String mid = profile.mid;
              String displayName = profile.displayName;
              String pictureUrl = profile.pictureUrl;
              String statusMessage = profile.statusMessage;
              // do something...
              break;
          case FAILED:
          default:
              Throwable cause = future.getCause();
              // do something for error...
              break;
      };
    }
});

実装例

プロフィール情報のオブジェクトは、リクエストの結果を受け取るためのリスナー ApiRequestFutureListenergetResponseObject() メソッドから取得します。
プロフィール情報のオブジェクトの詳細は、次のとおりです。

プロパティ名 説明
displayName ユーザのニックネーム
mid ユーザを一意で識別する識別子
pictureUrl ユーザのプロフィール画像の URL
statusMessage ステータスメッセージ

プロフィール画像のサムネイル

large の 画像を取得するためにアクセスするURLの例

http://dl.profile.line.naver.jp/abcdefghijklmn/large

ユーザーのプロフィール画像を取得時に URLに Suffix を追加することで画像のサイズを変更できます。

画像サイズ suffix
200 x 200 /large
51 x 51 /small

iOS SDK API

LINE SDK for iOS では、以下のAPIを提供しています。
LINE SDK for iOS では、APIを呼び出す際に、access token を自動的にリフレッシュするため、access token を意識することなく、APIを呼び出すことができます。

Retrieve Access Token

Access Token 取得の実装例

- (void)lineAdapterAuthorizationDidChange:(NSNotification*)aNotification
{
    LineAdapter *_adapter = [aNotification object];
    if ([_adapter isAuthorized])
    {
      LineApiClient *apiClient = [adapter getLineApiClient];
      NSString *accessToken = apiClient.accessToken;
      NSString *refreshToken = apiClient.refreshToken;
      // The above information will be sent to the
      // backend server and processed accordingly.
    }
    else
    {
        ...
    }
}

メソッド

apiClient#accessToken()

実装例

LINE SDK から access token を取得し、サーバーに転送することにより、Social REST API をサーバー側からコールすることができます。
access token を転送する場合は、事前に access token をハッシュ化し、SSL 通信にて転送すること推奨しています。

Get Profile

事前準備

プロフィール情報を取得するには、次の2つが満たされている必要があります。

メソッド

LineApiClient#getMyProfileWithResultBlock:

プロフィール情報取得の実装例

[[adapter getLineApiClient] getMyProfileWithResultBlock:^(NSDictionary *aResult, NSError *aError)
{
    if (aResult)
    {
     // API call was successfully.
     NSLog(@"displayName : %@", aResult[@"displayName"]);
     NSLog(@"mid : %@", aResult[@"mid"]);
     NSLog(@"pictureUrl : %@", aResult[@"pictureUrl"]);
     NSLog(@"statusMessage : %@", aResult[@"statusMessage"]);
    }
    else
    {
     // API call failed.
     NSDictionary *userInfo = [aError userInfo];
     NSLog(@"statusCode : %@", userInfo[@"statusCode"]);
     NSLog(@"statusMessage : %@", userInfo[@"statusMessage"]);
    }
}];

実装例

プロフィール情報を取得する為のコードの例を示します。取得できるオブジェクトの詳細は、次のとおりです。

プロパティ名 説明
displayName ユーザのニックネーム
mid ユーザを一意で識別する識別子
pictureUrl ユーザのプロフィール画像の URL
statusMessage ステータスメッセージ
ユーザがステータスメッセージを記述していない場合は、このプロパティは含まれません

プロフィール画像のサムネイル

large の 画像を取得するためにアクセスするURLの例

http://dl.profile.line.naver.jp/abcdefghijklmn/large

ユーザーのプロフィール画像を取得時に URLに Suffix を追加することで画像のサイズを変更できます。

画像サイズ suffix
200 x 200 /large
51 x 51 /small