shell java ruby go php perl python

Messaging API

With the Messaging API, you can develop a bot that interacts with users in LINE chats.

The Messaging API is made up of the following components.

Webhooks

Receive notifications in real-time when a user sends a message or friends your account.

Reply message

Reply to messages from users.

Push message

Send messages to users at any time.

Multicast

Send messages to multiple users at any time.

Content

Download image, video, and audio data sent from users.

Profile

Get user profile information.

Leave

Leave a group or room.

LINE Bot SDK

The LINE Bot SDK is provided in multiple languages to make it easier for you to start developing bot applications with the Messaging API. These SDKs were also used to generate the sample code found in our API documentation.

Stay connected

Follow our official Twitter account to receive the latest news on documentation, APIs, and issues and to report issues related to our documentation or APIs.

You can also add our official LINE Developers account as a friend on LINE to stay up to date on all the latest news for developers.

Getting started

See Getting started to start developing with the Messaging API.

Common specifications

The following are specifications that are common to all the APIs provided by the Messaging API.

Rate limits

The limit for the number of requests you can make for each API are shown below. Rate limits vary depending on your plan.

Plan Limit
Developer Trial 1,000/min
Other plans 10,000/min

Status codes

The following status codes are returned by the APIs.

Error code Description
200 OK Request successful
400 Bad Request Problem with the request
401 Unauthorized Valid Channel access token is not specified
403 Forbidden Not authorized to use the API. Confirm that your account or plan is authorized to used the API.
429 Too Many Requests Exceeded the rate limit for API calls
500 Internal Server Error Error on the internal server

Response headers

The following HTTP headers are included in Messaging API responses.

Response header Description
X-Line-Request-Id ID generated for each request

Error response

Example of JSON error response

{
  "message":"The request body has 2 error(s)",
  "details":[
    {"message":"May not be empty","property":"messages[0].text"},
    {"message":"Must be one of the following values: [text, image, video, audio, location, sticker, template, imagemap]","property":"messages[1].type"}
  ]
}


{
  "message":"Invalid reply token"
}

The following JSON data is returned in the response body when an error occurs.

Field Type Description
message String Summary of the error
details[].message String Details of the error

OR

Field Type Description
message String Details of the error

Webhooks

Example webhook request body

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

When an event, such as when a user adds your account or sends a message, is triggered, an HTTPS POST request is sent to the webhook URL that is configured on the Channel Console. You can access the Channel Console from the accounts page of the LINE Business Center.

Your bot server should receive and handle this request appropriately for the event.

Request headers

Request header Description
X-Line-Signature Used for signature validation

Request body

The request body contains a JSON object with an array of webhook event objects

Field Type Description
events Array of webhook event objects Information about the event

Response

Your server should return the status code 200 for a HTTP POST request sent by a webhook.

Signature validation

Example of signature validation

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

Example of signature validation

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

Example of signature validation

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`

Example of signature validation

$channelSecret = ...; // Channel secret string
$httpRequestBody = ...; // Request body string
$hash = hash_hmac('sha256', $httpRequestBody, $channelSecret, true);
$signature = base64_encode($hash);
// Compare X-Line-Signature request header string and the signature

Example of signature validation

use Digest::SHA 'hmac_sha256';
use MIME::Base64 'decode_base64';

my $channel_secret= ... # Channel secret string
my $http_body = ... # Request body string
my $signature = decode_base64(hmac_sha256($http_body, $channel_secret));
# Compare X-Line-Signature request header string and the signature

Example of signature validation

import base64
import hashlib
import hmac

channel_secret = ... # Channel secret string
body = ... # Request body string
hash = hmac.new(channel_secret.encode('utf-8'),
    body.encode('utf-8'), hashlib.sha256).digest()
signature = base64.b64encode(hash)
# Compare X-Line-Signature request header and the signature

The signature in the X-Line-Signature request header must be verified to confirm that the request was sent from the LINE Platform.

Authentication is performed as follows.

  1. With the Channel secret as the secret key, your application retrieves the digest value in the request body created using the HMAC-SHA256 algorithm.
  2. The server confirms that the signature in the request header matches the digest value which is Base64 encoded.

Webhook event object

Example 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"
      }
    }
  ]
}

JSON object which contains events generated on the LINE Platform.

Common fields

The following are the fields found in the webhook event object

Field Type Description
type String Identifier for the type of event
timestamp Number Time of the event in milliseconds
source User
Group
Room
JSON object which contains the source of the event

Source user

JSON object which contains the source user of the event.

Field Type Description
type String user
userId String ID of the source user

Source group

JSON object which contains the source group of the event.

Field Type Description
type String group
groupId String ID of the source group

Source room

JSON object which contains the source room of the event.

Field Type Description
type String room
roomId String ID of the source room

Message event

Event object which contains the sent message.
The message field contains a message object which corresponds with the message type. You can reply to message events.

Field Type Description
type String message
replyToken String Token for replying to this event
message Text
Image
Video
Audio
Location
Sticker
Contents of the message

Text message

Text message example

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

Message object which contains the text sent from the source.

Field Type Description
id String Message ID
type String text
text String Message text

Image message

Image message example

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

Message object which contains the image content sent from the source. The binary image data can be retrieved from the content endpoint.

Field Type Description
id String Message ID
type String image

Video message

Video message example

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

Message object which contains the video content sent from the source. The binary video data can be retrieved from the content endpoint.

Field Type Description
id String Message ID
type String video

Audio message

Audio message example

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

Message object which contains the audio content sent from the source. The binary audio data can be retrieved from the content endpoint.

Field Type Description
id String Message ID
type String audio

Location message

Location message example

{
  "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 which contains the location data sent from the source.

Field Type Description
id String Message ID
type String location
title String Title
address String Address
latitude Decimal Latitude
longitude Decimal Longitude

Sticker message

Sticker message example

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

Message object which contains the sticker data sent from the source.
For a list of basic LINE stickers and sticker IDs, see sticker list.

Field Type Description
id String Message ID
type String sticker
packageId String Package ID
stickerId String Sticker ID

Follow event

Follow event example

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

Event object for when your account is added as a friend (or unblocked). You can reply to follow events.

Field Type Description
type String follow
replyToken String Token for replying to this event

Unfollow event

Unfollow event example

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

Event object for when your account is blocked.

Field Type Description
type String unfollow

Join event

Join event example

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

Event object for when your account joins a group or talk room. You can reply to join events.

Field Type Description
type String join
replyToken String Token for replying to this event

Leave event

Leave event example

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

Event object for when your account leaves a group.

Field Type Description
type String leave

Postback event

Postback event example

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

Event object for when a user performs an action on a template message which initiates a postback. You can reply to postback events.

Field Type Description
type String postback
replyToken String Token for replying to this event
postback.data String Postback data

Beacon event

Beacon event example

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

Event object for when a user enters or leaves the range of a LINE Beacon. You can reply to beacon events.

Field Type Description
type String beacon
replyToken String Token for replying to this event
beacon.hwid String Hardware ID of the beacon that was detected
beacon.type String Type of beacon event

Depending on the type of event, the beacon.type field contains the following strings.

beacon.type Description
enter Entered beacon’s reception range
leave Left beacon’s reception range
banner Tapped beacon banner

Reply message

Reply message request example

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
$httpClient = new \LINE\LINEBot\HTTPClient\CurlHTTPClient('<channel access token>');
$bot = new \LINE\LINEBot($httpClient, ['channelSecret' => '<channel secret>']);

$textMessageBuilder = new \LINE\LINEBot\MessageBuilder\TextMessageBuilder('hello');
$response = $bot->replyMessage('<replyToken>', $textMessageBuilder);

echo $response->getHTTPStatus() . ' ' . $response->getRawBody();
use LINE::Bot::API;
use LINE::Bot::API::Builder::SendMessage;

my $bot = LINE::Bot::API->new(
    channel_secret       => "<channel secret>",
    channel_access_token => "<channel access token>",
);

my $messages = LINE::Bot::API::Builder::SendMessage->new(
)->add_text(
    text => 'hello',
);
my $res = $bot->reply_message("<replyToken>", $messages->build);
unless ($res->is_success) {
    # error handling
    ....
}
from linebot import LineBotApi
from linebot.models import TextSendMessage
from linebot.exceptions import LineBotApiError

line_bot_api = LineBotApi('<channel access token>')

try:
    line_bot_api.reply_message('<reply_token>', TextSendMessage(text='Hello World!'))
except LineBotApiError as e:
    # error handle
    ...

Respond to events from users, groups, and rooms.

Webhooks are used to notify you when an event occurs. For events that you can respond to, a replyToken is issued for replying to messages.

Because the replyToken becomes invalid after a certain period of time, responses should be sent as soon as a message is received. Reply tokens can only be used once.

HTTP request

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

Request headers

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

Request body

Include an array of send message objects for your message.

Field Type Required Description
replyToken String Yes replyToken received via webhook
messages Array of send message objects Yes Messages
Max: 5

Response

Example JSON response

{}

Returns the status code 200 and an empty JSON object.

Push message

Push message request example

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
$httpClient = new \LINE\LINEBot\HTTPClient\CurlHTTPClient('<channel access token>');
$bot = new \LINE\LINEBot($httpClient, ['channelSecret' => '<channel secret>']);

$textMessageBuilder = new \LINE\LINEBot\MessageBuilder\TextMessageBuilder('hello');
$response = $bot->pushMessage('<to>', $textMessageBuilder);

echo $response->getHTTPStatus() . ' ' . $response->getRawBody();
use LINE::Bot::API;
use LINE::Bot::API::Builder::SendMessage;

my $bot = LINE::Bot::API->new(
    channel_secret       => "<channel secret>",
    channel_access_token => "<channel access token>",
);

my $messages = LINE::Bot::API::Builder::SendMessage->new(
)->add_text(
    text => 'hello',
);
my $res = $bot->push_message("<to>", $messages->build);
unless ($res->is_success) {
    # error handling
    ....
}
from linebot import LineBotApi
from linebot.models import TextSendMessage
from linebot.exceptions import LineBotApiError

line_bot_api = LineBotApi('<channel access token>')

try:
    line_bot_api.push_message('<to>', TextSendMessage(text='Hello World!'))
except LineBotApiError as e:
    # error handle
    ...

Send messages to a user, group, or room at any time.

HTTP request

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

Request headers

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

Request body

Include an array of send message objects for your message.

Field Type Required Description
to String Yes ID of the receiver
messages Array of send message objects Yes Messages
Max: 5

Response

Example JSON response

{}

Returns the status code 200 and an empty JSON object.

Multicast

Multicast request example

curl -X POST \
-H 'Content-Type:application/json' \
-H 'Authorization: Bearer {ENTER_ACCESS_TOKEN}' \
-d '{
    "to": ["xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"],
    "messages":[
        {
            "type":"text",
            "text":"Hello, world1"
        },
        {
            "type":"text",
            "text":"Hello, world2"
        }
    ]
}' https://api.line.me/v2/bot/message/multicast

Send messages to multiple users at any time.

HTTP request

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

Request headers

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

Request body

Include an array of send message objects with the messages to be sent.

Field Type Required Description
to Array of strings Yes IDs of the receivers
Max: 150 users
messages Array of send message objects Yes Messages
Max: 5

Response

Example JSON response

{}

Returns the status code 200 and an empty JSON object.

Send message object

JSON object which contains the contents of the message you send.

Text

Text example

{
    "type": "text",
    "text": "Hello, world"
}
Field Type Required Description
type String Yes text
text String Yes Message text
Max: 2000 characters

Text example with emoticon


{
    "type": "text",
    "text": "Hello, world 􀂲"
}

You can include emoticons in your message text. Because emoticons are a part of Unicode, they must be converted from their character codes.
Note that the character code, 0x1000B2, is used in the example on the right. Although the emoticon does not show up correctly in the browser, it will show up in LINE.
For a list of emoticons that can be sent with the Messaging API, see emoticon list.

Image

Image example

{
    "type": "image",
    "originalContentUrl": "https://example.com/original.jpg",
    "previewImageUrl": "https://example.com/preview.jpg"
}
Field Type Required Description
type String Yes image
originalContentUrl String Yes Image URL (Max: 1000 characters)
HTTPS
JPEG
Max: 1024 x 1024
Max: 1 MB
previewImageUrl String Yes Preview image URL (Max: 1000 characters)
HTTPS
JPEG
Max: 240 x 240
Max: 1 MB

Video

Video example

{
    "type": "video",
    "originalContentUrl": "https://example.com/original.mp4",
    "previewImageUrl": "https://example.com/preview.jpg"
}
Field Type Required Description
type String Yes video
originalContentUrl String Yes URL of video file (Max: 1000 characters)
HTTPS
mp4
Less than 1 minute
Max: 10 MB
previewImageUrl String Yes URL of preview image (Max: 1000 characters)
HTTPS
JPEG
Max: 240 x 240
Max: 1 MB

Audio

Audio example

{
    "type": "audio",
    "originalContentUrl": "https://example.com/original.m4a",
    "duration": 240000
}
Field Type Required Description
type String Yes audio
originalContentUrl String Yes URL of audio file (Max: 1000 characters)
HTTPS
m4a
Less than 1 minute
Max 10 MB
duration Number Yes Length of audio file (milliseconds)

Location

Location example

{
    "type": "location",
    "title": "my location",
    "address": "〒150-0002 東京都渋谷区渋谷2丁目21−1",
    "latitude": 35.65910807942215,
    "longitude": 139.70372892916203
}
Field Type Required Description
type String Yes location
title String Yes Title
Max: 100 characters
address String Yes Address
Max: 100 characters
latitude Decimal Yes Latitude
longitude Decimal Yes Longitude

Sticker

Sticker example

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

For a list of the sticker IDs for stickers that can be sent with the Messaging API, see Sticker list.

Field Type Required Description
type String Yes sticker
packageId String Yes Package ID
stickerId String Yes Sticker ID

Imagemap message

Imagemaps are images with one or more links. You can assign one link for the entire image or multiple links which correspond to different regions of the image.

Imagemap with two tappable regions on the left and the right

{
  "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 Required Description
type String Yes imagemap
baseUrl String Yes Base URL of image (Max: 1000 characters)
HTTPS
altText String Yes Alternative text
Max: 400 characters
baseSize.width Number Yes Width of base image (set to 1040px)
baseSize.height Number Yes Height of base image(set to the height that corresponds to a width of 1040px)
actions Array of Imagemap action object Yes Action when tapped
Max: 50

Base URL

To use an imagemap, you must include URLs with the image width (px) at the end of the base URL so that the client can download the image at the required resolution.

For example, if the base URL is,

https://example.com/images/cats

the URL for a client device to download a 700px image would be

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

Below are the image resolutions required by client devices.

The image used for the imagemap must meet the following specifications:

Imagemap action object

Object which specifies the actions and tappable regions of an imagemap.

When a region is tapped, the user is redirected to the URI specified in uri and the message specified in message is sent.

URI action

Field Type Required Description
type String Yes uri
linkUri String Yes Webpage URL
Max: 1000 characters
area Imagemap area object Yes Defined tappable area

Message action

Field Type Required Description
type String Yes message
text String Yes Message to send
Max: 400 characters
area Imagemap area object Yes Defined tappable area

Imagemap area object

Defines the size of the full imagemap with the width as 1040px. The top left is used as the origin of the area.

Field Type Required Description
x Number Yes Horizontal position of the tappable area
y Number Yes Vertical position of the tappable area
width Number Yes Width of the tappable area
height Number Yes Height of the tappable area

Template messages

Template messages are messages with predefined layouts which you can customize. There are three types of templates available that can be used to interact with users through your bot.

Field Type Required Description
type String Yes template
altText String Yes Alternative text for unsupported devices.
Max: 400 characters
template Buttons
Confirm
Carousel
Yes Object with the contents of the template.

Buttons

Buttons template message example

{
  "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"
          }
      ]
  }
}

Template message with an image, title, text, and multiple action buttons.

Field Type Required Description
type String Yes buttons
thumbnailImageUrl String No Image URL (Max: 1000 characters)
HTTPS
JPEG or PNG
Aspect ratio: 1:1.51
Max width: 1024px
Max: 1 MB
title String No Title
Max: 40 characters
text String Yes Message text
Max: 160 characters (no image or title)
Max: 60 characters (message with an image or title)
actions Array of template actions Yes Action when tapped
Max: 4

Confirm

Confirm template message example

{
  "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"
          }
      ]
  }
}

Template message with two action buttons.

Field Type Required Description
type String Yes confirm
text String Yes Message text
Max: 240 characters
actions Array of template actions Yes Action when tapped
Set 2 actions for the 2 buttons

Carousel template message example

{
  "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"
                }
            ]
          }
      ]
  }
}

Template message with multiple columns which can be cycled like a carousel.

Field Type Required Description
type String Yes carousel
columns Array of column objects Yes Array of columns
Max: 5

Column object

Field Type Required Description
thumbnailImageUrl String No Image URL (Max: 1000 characters)
HTTPS
JPEG or PNG
Aspect ratio: 1:1.51
Max width: 1024px
Max: 1 MB
title String No Title
Max: 40 characters
text String Yes Message text
Max: 120 characters (no image or title)
Max: 60 characters (message with an image or title)
actions Array of template actions Yes Action when tapped
Max: 3

Template action

Action to include in your template message.

Postback action

When this action is tapped, a postback event is returned via webhook with the specified string in the data field.

If you have included the text field, the string in the text field is sent as a message from the user.

Field Type Required Description
type String Yes postback
label String Yes Label for the action
Max: 20 characters
data String Yes String returned via webhook in the postback.data property of the postback event
Max: 300 characters
text String No Text sent when the action is performed
Max: 300 characters

Message action

When this action is tapped, the string in the text field is sent as a message from the user.

Field Type Required Description
type String Yes message
label String Yes Label for the action
Max: 20 characters
text String Yes Text sent when the action is performed
Max: 300 characters

URI action

When this action is tapped, the URI specified in the uri field is opened.

Field Type Required Description
type String Yes uri
label String Yes Label for the action
Max: 20 characters
uri String Yes URI opened when the action is performed (Max: 1000 characters)
http, https, tel

Content

Content request example

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>")
case response
when Net::HTTPSuccess then
  tf = Tempfile.open("content")
  tf.write(response.body)
else
  p "#{response.code} #{response.body}"
end
$httpClient = new \LINE\LINEBot\HTTPClient\CurlHTTPClient('<channel access token>');
$bot = new \LINE\LINEBot($httpClient, ['channelSecret' => '<channel secret>']);
$response = $bot->getMessageContent('<messageId>');
if ($response->isSucceeded()) {
    $tempfile = tmpfile();
    fwrite($tempfile, $response->getRawBody());
} else {
    error_log($response->getHTTPStatus() . ' ' . $response->getRawBody());
}
use LINE::Bot::API;

my $bot = LINE::Bot::API->new(
    channel_secret       => "<channel secret>",
    channel_access_token => "<channel access token>",
);

my $res = $bot->get_message_content("<messageId>");
unless ($res->is_success) {
    # error handling
    ....
}
my $filename = $ret->fh->filename;
open my $fh, '<', $file or die "$!: $file";
from linebot import LineBotApi

line_bot_api = LineBotApi('<channel access token>')

message_content = line_bot_api.get_content('<message_id>')
with open(file_path, 'wb') as fd:
    for chunk in message_content.iter_content():
        fd.write(chunk)

Retrieve image, video, and audio data sent by users.

HTTP request

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

Request headers

Request header Description
Authorization Bearer {Channel Access Token}

URL parameters

Parameter Description
messageId Message ID

Response

Returns status code 200 and the content in binary.

Profile

Profile request example

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>")
case response
when Net::HTTPSuccess then
  contact = JSON.parse(response.body)
  p contact['displayName']
  p contact['pictureUrl']
  p contact['statusMessage']
else
  p "#{response.code} #{response.body}"
end
$httpClient = new \LINE\LINEBot\HTTPClient\CurlHTTPClient('<channel access token>');
$bot = new \LINE\LINEBot($httpClient, ['channelSecret' => '<channel secret>']);
$response = $bot->getProfile('<userId>');
if ($response->isSucceeded()) {
    $profile = $response->getJSONDecodedBody();
    echo $profile['displayName'];
    echo $profile['pictureUrl'];
    echo $profile['statusMessage'];
}
use LINE::Bot::API;

my $bot = LINE::Bot::API->new(
    channel_secret       => "<channel secret>",
    channel_access_token => "<channel access token>",
);

my $res = $bot->get_profile("<userId>");
unless ($res->is_success) {
    # error handling
    ....
}

say $ret->display_name;
say $ret->user_id;
say $ret->picture_url;
say $ret->status_message;
from linebot import LineBotApi
from linebot.exceptions import LineBotApiError

line_bot_api = LineBotApi('<channel access token>')

try:
    profile = line_bot_api.get_profile('<user_id>')
    print(profile.display_name)
    print(profile.user_id)
    print(profile.picture_url)
    print(profile.status_message)
except LineBotApiError as e:
    # error handle
    ...

Get user profile information.

HTTP request

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

Request headers

Request header Description
Authorization Bearer {Channel Access Token}

URL parameters

Parameter Description
userId User ID

Response

Response body example

{
    "displayName":"LINE taro",
    "userId":"Uxxxxxxxxxxxxxx...",
    "pictureUrl":"http://obs.line-apps.com/...",
    "statusMessage":"Hello, LINE!"
}

Returns the status code 200 and a JSON object with the following parameters.

Field Type Description
displayName String Display name
userId String User ID
pictureUrl String Image URL
statusMessage String Status message

Leave

Leave request example

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
$httpClient = new \LINE\LINEBot\HTTPClient\CurlHTTPClient('<channel access token>');
$bot = new \LINE\LINEBot($httpClient, ['channelSecret' => '<channel secret>']);
$response = $bot->leaveRoom('<roomId>');
echo $response->getHTTPStatus() . ' ' . $response->getRawBody();
use LINE::Bot::API;

my $bot = LINE::Bot::API->new(
    channel_secret       => "<channel secret>",
    channel_access_token => "<channel access token>",
);

my $res = $bot->leave_room("<roomId>");
unless ($res->is_success) {
    # error handling
    ....
}
from linebot import LineBotApi
from linebot.exceptions import LineBotApiError

line_bot_api = LineBotApi('<channel access token>')

try:
    line_bot_api.leave_room('<room_id>')
except LineBotApiError as e:
    # error handle
    ...

Leave a group or room.

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 Description
Authorization Bearer {Channel Access Token}

URL parameters

Parameter Description
groupId Group ID
roomId Room ID

Response

JSON response example

{}

Returns the status code 200 and an empty JSON object.

Issue Channel access token

Example of issuing Channel access token

curl -X POST  \
-H "Content-Type:application/x-www-form-urlencoded" \
--data-urlencode 'grant_type=client_credentials' \
--data-urlencode 'client_id={ENTER_CLIENT_ID}' \
--data-urlencode 'client_secret={ENTER_CLIENT_SECRET}' \
https://api.line.me/v2/oauth/accessToken

Issues a new Channel access token which is used for the Messaging API. This Channel access token cannot be refreshed. Up to 10 Channel access tokens can be issued. If the maximum is exceeded, existing Channel access tokens will be invalidated in the order of when they were first issued.

HTTP request

POST https://api.line.me/v2/oauth/accessToken

Request header

Item Description
Content-Type application/x-www-form-urlencoded

Request body

Request body in a form-urlencoded format.

Name Type Description
grant_type String client_credentials
client_id String Channel ID. Found on the Channel Console.
client_secret String Channel secret. Found on the Channel Console.

Response

JSON response example

{
"access_token":"W1TeHCgfH2Liwa.....",
"expires_in":2592000,
"token_type":"Bearer"
}

Returns response in JSON format.

Property Type Description
token_type String Bearer
access_token String Channel access token
expires_in Integer Time until Channel access token expires in seconds from time the token is issued

Revoke Channel access token

Example of revoking Channel access token

curl -X POST \
-H "Content-Type: application/x-www-form-urlencoded" \
--data-urlencode 'access_token={ENTER_ACCESS_TOKEN}' \
https://api.line.me/v2/oauth/revoke

Invalidates a Channel access token which is used for the Messaging API.

HTTP request

POST https://api.line.me/v2/oauth/revoke

Request header

Item Description
Content-Type application/x-www-form-urlencoded

Request body

Request body in a form-urlencoded format.

Name Type Description
access_token String Channel access token

Response

JSON response example

{}

Returns the status code 200 and an empty JSON object. No error occurs if an invalid Channel access token is specified.

LINE Beacon

LINE Beacon is a service which lets your bot receive notifications through webhooks when a connected LINE user enters or leaves the range of to a beacon. This lets you better target specific users with customized services.

Connecting your bot with Beacon

Enable Beacon for your Messaging API account on the LINE Official Account Manager.

Receiving webhooks from a LINE user

  1. Make sure that your smartphone has bluetooth turned on
  2. Select Use LINE Beacon
    • LINE > Settings > Privacy > Use LINE Beacon
  3. Add the bot account as a friend
    • Information is only sent from LINE users who have added the bot account as a friend
  4. Make sure that the beacon is turned on and bring your smartphone close to it
    • Information is sent to the LINE Platform once the LINE app detects the beacon

Bringing information together with Beacon Banner

In certain stores and buildings, a banner (Beacon Banner) will appear above the friend list or talk list when the user comes close to a beacon. By tapping the banner, it’s possible to select the “Use LINE Beacon” option, add the bot account as a friend, and send a message all at the same time.

Example of Beacon Banner
(Example of “Beacon Banner”. The green area of this picture is the banner.)

If you are interested in using the Beacon Banner feature, please make an inquiry at LINE Partner.

Mission stickers

Send mission stickers to users who have completed a specified mission.

HTTP request

Mission sticker request example

curl -X POST \
-H 'Content-Type: application/json' \
-H 'X-Line-ChannelId:{ENTER_CHANNEL_ID}' \
-H 'X-Line-ChannelSecret: {ENTER_CHANNEL_SECRET}' \
-H 'X-Line-Trusted-User-With-ACL: {ENTER_TRUSTED_USER}' \
-d '{
"to": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "messages": [
    {
      "packageId": "0000",
      "isPresent": false
    } 
  ]
}'
https://api.line.me/v2/missionSticker/send

POST https://api.line.me/v2/missionSticker/send

Request headers

Item Description
Content-Type application/json
X-Line-ChannelId Channel ID. Found on the Channel Console.
X-Line-ChannelSecret Channel secret. Found on the Channel Console.
X-Line-Trusted-User-With-ACL Value used when getting permission to use mission stickers

Request body

Request body is in JSON.

Name Type Description
to String User ID of targer user
messages Array Array with packageId and isPresent objects. Maximum of 1 messages object.
messages[].packageId String Package ID
messages[].isPresent Boolean false

JSON response example

{"ticketId":"AB1234-1234567890"}

Response

Response is returned in JSON.

Success

Property Type Description
ticketId String Value used internally by LINE. ticketId is returned if the call is successful.

Error

Property Type Description
message String Description of error

Error response

Message Description
authentication failed One or more of the X-Line-ChannelId, X-Line-ChannelSecret, and X-Line-Trusted-User-With-ACL header fields are invalid or the server making the API call is not registered on the server IP whitelist.
CHANNEL_MISSION_STICKER_NOT_USABLE Account does not have permission to use mission stickers.

Social REST API

How to use the APIs

To use the REST APIs, you need to have an access token.

Validating access tokens

Example of validating the access token

curl -X POST \
-H 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'access_token={ENTER_ACCESS_TOKEN}' \
https://api.line.me/v2/oauth/verify

{
   "scope":"P",
   "client_id":"1350031035",
   "expires_in":2591965
}

Validates the access token.

HTTP request

POST https://api.line.me/v2/oauth/verify

Request header

Item Description
Content-Type application/x-www-form-urlencoded

Request body

The request body is in a form-urlencoded format.

Name Type Description
access_token String Access token

Response

Responses are returned in JSON.

Property Type Description
scope String Permissions obtained through the access token.
client_id String Channel ID for which the access token is issued.
expires_in Integer Expiration date of the access token. Expressed as the remaining number of seconds to expiry from when the API was called.

Refreshing access tokens

Example of refreshing an access token

curl -X POST \
-H 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=refresh_token' \
--data-urlencode 'client_id={ENTER_CLIENT_ID}' \
--data-urlencode 'client_secret={ENTER_CLIENT_SECRET}' \
--data-urlencode 'refresh_token={ENTER_REFRESH_TOKEN}' \
https://api.line.me/v2/oauth/accessToken

{
   "token_type":"Bearer",
   "scope":"P",
   "access_token":"bNl4YEFPI/hjFWhTqexp4MuEw...",
   "expires_in":2591977,
   "refresh_token":"8iFFRdyxNVNLWYeteMMJ"
}

HTTP request

POST https://api.line.me/v2/oauth/accessToken

Request header

Item Description
Content-Type application/x-www-form-urlencoded

Request body

The request body is in a form-urlencoded format.

Name Type Description
grant_type String Fixed refresh_token
refresh_token String Refresh token to reissue an access token
client_id String Channel ID. Found on the Channel Console.
client_secret String Channel secret. Found on the Channel Console.

Response

The response is returned in JSON.

Property Type Description
token_type String Fixed Bearer
scope String Permissions obtained through the access token.
accessToken String Access token
expires_in Integer Expiration date of the access token. Expressed in the remaining number of seconds to expiry from when the API was called.
refresh_token String Token used to reissue an access token. Valid for 10 days from the expiration of the access token.

Revoking tokens

Example of revoking an access token

curl -X POST \
-H 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'refresh_token={ENTER_REFRESH_TOKEN}' \
https://api.line.me/v2/oauth/revoke

{}

Invalidates the access token. Cannot be used to invalidate Channel access tokens which are used for the Messaging API

HTTP request

POST https://api.line.me/v2/oauth/revoke

Request header

Item Description
Content-Type application/x-www-form-urlencoded

Request body

The request body is in a form-urlencoded format.

Name Type Description
refresh_token String Refresh token to invalidate an access token

Response

Returns an HTTP 200 status code. There are no error responses.

Getting user profiles

Example of getting a user profile

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

{
  "userId":"Ufr47556f2e40dba2456887320ba7c76d",
  "displayName":"Brown",
  "pictureUrl":"https://example.com/abcdefghijklmn",
  "statusMessage":"Hello, LINE!"
}

You can retrieve a user’s display name, profile image, and status message.

HTTP request

GET https://api.line.me/v2/profile

Request header

Item Description
Authorization Bearer {ACCESS_TOKEN}

Response

The response is in JSON.

Property Type Description
displayName String User’s display name
userId String Identifier of the user
pictureUrl String Profile image URL. “https” image URL. Not included in the response if the user doesn’t have a profile image.
statusMessage String User’s status message. Not included in the response if the user doesn’t have a status message.

Profile image thumbnails

Example of how to retrieve a large profile image

https://obs.line-apps.com/abcdefghijklmn/large

You can change the user’s profile image size by adding a suffix to the URL.

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

Error responses

The following error responses are returned when an error occurs.

HTTP status Description
200 OK Request successful
400 Bad Request Problem with the request. Check the request parameters and JSON format.
401 Unauthorized Check that the authorization header is correct.
403 Forbidden Not authorized to use the API. Confirm that your account or plan is authorized to use the API.
429 Too Many Requests Make sure that you are within the rate limits for requests.
500 Internal Server Error Temporary error on the API server.

Android SDK

LineApiError

Class

Package com.linecorp.linesdk
Extends Object
Implements Parcelable

Methods

getHttpResponseCode()

Gets the API error’s HTTP response code

Method header

public int getHttpResponseCode()

Return value

The HTTP response code as an int value.

getMessage()

Gets the error message associated with the API error.

Method header

public String getMessage()

Return value

The error message in the String format.

LineAccessToken

Class

Package com.linecorp.linesdk
Extends Object
Implements Parcelable

Methods

getAccessToken()

Method header

public String getAccessToken()

Gets the string representation of the access token.

Return value

Returns the access token as a String.

getEstimatedExpirationTimeMillis()

Method header

public long getEstimatedExpirationTimeMillis()

Returns the estimated time in UNIX time of when the access token will expire. The expiration time that is returned by this method is not exact because it is calculated using time values that are cached on the client.

Return value

The estimated time in UNIX time of when the access token will expire.

getExpiresInMillis()

Method header

public long getExpiresInMillis()

Returns the amount of time in milliseconds until the token expires.

Return value

The amount of time in milliseconds until the token expires.

getIssuedClientTimeMillis()

Method header

public long getIssuedClientTimeMillis()

The time in UNIX time of when the access token information was last updated. This value is updated upon login, when the token is refreshed, and when the token is verified.

Return value

The time in UNIX time of when the access token information was last updated.

LineApiClient

Interface

Package com.linecorp.linesdk.api

Methods

getCurrentAccessToken()

Method header

LineApiResponse<LineAccessToken> getCurrentAccessToken()

Gets the access token that the SDK is using for the current user.

Return value

Returns LineApiResponse which contains LineAccessToken with the user’s access token if the API call is successful. If the API call fails, the payload of LineApiResponse is null.

getProfile()

Method header

LineApiResponse<LineProfile> getProfile()

Gets the profile information of the current user.

Return value

Returns LineApiResponse which contains LineProfile with the user’s profile information if the API is successful. If the API call fails, the payload of LineApiResponse is null.

logout()

Method header

LineApiResponse<?> logout()

Revokes the current user’s access token.

Return value

Returns LineApiResponse which contains the result of the API call.

refreshAccessToken()

Method header

LineApiResponse<LineAccessToken> refreshAccessToken()

Refreshes the access token that the SDK is using for the current user.

Return value

Returns LineApiResponse which contains a LineAccessToken with the new access token. If the API call fails, the payload of LineApiResponse is null.

verifyToken()

Method header

LineApiResponse<LineCredential> verifyToken()

Checks to see if the access token that the SDK is using for the current user is valid.

Return value

Returns LineApiResponse which contains a successful response and a LineCredential object which contains the access token if the access token is valid. If the access token is invalid, a failure response is returned.

LineApiClientBuilder

Class

Package com.linecorp.linesdk.api
Extends None
Implements None

Constructor

Constructor header

public LineApiClientBuilder(@NonNull Context context, int channelId) 

Parameters

Parameter Description
context Android context
channelId Channel ID

Methods

build()

Method header

public LineApiClient build()

Creates and returns an instance of LineApiClient.

Return value

Returns an instance of LineApiClient.

disableTokenAutoRefresh()

Method header

public LineApiClientBuilder disableTokenAutoRefresh()

Disables the SDK’s token auto-refresh feature.

Return value

Returns the current instance of LineApiClientBuilder.

LineApiResponse

Class

Package com.linecorp.linesdk
Extends Object
Implements None

Methods

getErrorData()

Gets information about an API error that has occurred. This method should only be called if an API call has failed.

Method header

public LineApiError getErrorData()

Return value

If an API error has occurred, this method returns a LineApiError object that contains information about the error. If no errors occur, the LineApiError object is still returned but it will not contain any useful information.

getResponseCode()

Gets the response code that the API call returned.

Method header

public LineApiResponseCode getResponseCode()

Return value

Returns LineApiResponseCode which tells us if the API call was successful.

getResponseData()

Method header

public R getResponseData()

Gets data that is associated with the response if it exists. If no data is associated with the response, it will throw NoSuchElementException. You must check if the response succeeded by using the isSuccess() method before calling this API.

Return value

Returns the response data in the same format as the generic type associated with LineApiResponse.

isNetworkError()

Method header

public boolean isNetworkError()

Checks if the API call failed with a network error.

Return value

Returns true if the API call fails with a network error. Returns false otherwise.

isServerError()

Method header

public boolean isServerError()

Checks if the API call failed with a server error.

Return value

Returns true if the API call fails with a server error. Returns false otherwise.

isSuccess()

Method header

public boolean isSuccess()

Checks if the API call was successful.

Return value

Returns true if the API call is successful and false if it fails.

LineCredential

Class

Package com.linecorp.linesdk
Extends Object
Implements Parcelable

Methods

getAccessToken()

Method header

public LineAccessToken getAccessToken()

Gets the current user’s access token.

Return value

Returns a LineAccessToken object that contains the user’s access token.

getPermission()

Method header

public List<String> getPermission()

Returns a list of permissions that the current user’s access token holds.

Return value

Returns a string list of permission codes that are associated with the current user’s access token. The following is a list of possible permission codes.

Permission code Description
P The token can be used to get the user’s profile information.

LineLoginApi

Class

Package com.linecorp.linesdk.auth
Extends None
Implements None

Methods

getLoginIntent()

Method header

public static Intent getLoginIntent(Context context, int channelId)

Gets an intent for performing LINE login. If the LINE app is installed, the SDK logs in using app-to-app authentication through the LINE app. If the LINE app is not installed, the SDK uses the browser to log in.

Parameters

Parameter Description
context Android context
channelId Channel ID

Return value

Returns a login Intent that defaults to using LINE Auto Login.

getLoginIntentWithoutLineAppAuth()

Method header

public static Intent getLoginIntentWithoutLineAppAuth(Context context, int channelId)

Gets a login intent that only uses browser login.

Parameters

Parameter Description
context Android context
channelId Your Channel ID

Return value

Returns a login Intent that only uses browser login.

LineLoginResult

Class

Package com.linecorp.linesdk.auth
Extends Object
Implements Parcelable

Methods

isSuccess()

Checks to see if login was successful.

Method header

public boolean isSuccess() 

Return value

Returns true if the LINE login is successful or false if the LINE login fails.

getResponseCode()

Gets the response code that the login returned.

Method header

public LineApiResponseCode getResponseCode()

Return value

Returns LineApiResponseCode which tells us if the login was successful.

getLineProfile()

Gets the current user’s profile information.

Method header

public LineProfile getLineProfile() 

Return value

Returns the user’s LINE profile as a LineProfile object.

getLineCredential()

Gets the current user’s credentials.

Method header

public LineCredential getLineCredential() 

Return value

Returns the user’s authentication credentials as a LineCredential object.

getErrorData()

Gets information about a login error that has occurred. This method should only be called if the login has failed.

Method header

public getErrorData()

Return value

If a login error has occurred, this method returns a LineApiError object that contains information about the error. If there are no errors, the LineApiError object is still returned but it will not contain any useful information.

LineProfile

Class

Package: com.linecorp.linesdk
Extends: Object
Implements: Parcelable

getDisplayName()

Method header

public String getDisplayName()

Gets the current user’s display name.

Return value

Returns the current user’s display name in String format.

getPictureUrl()

Method header

public Uri getPictureUrl()

Gets the current user’s profile image URL.

Return value

Returns a Uri object that contains the current user’s profile image URL.

You can change the size of the user’s profile thumbnail image by adding a suffix to the URL.

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

getStatusMessage()

Method header

public String getStatusMessage()

Get the current user’s status message.

Return value

Returns the current user’s status message in String format.

getUserId()

Method header

public String getUserId()

Get the current user’s user ID.

Return value

Returns the current user’s user ID in String format.

iOS SDK

LineSDKAPI

Class

Superclass NSObject
Declared in LineSDKAPI.h

Methods

initWithConfiguration

Method prototype

- (instancetype)initWithConfiguration:(LineSDKConfiguration *)configuration NS_DESIGNATED_INITIALIZER;

Initializes LineSDKAPI using LineSDKConfiguration.

currentAccessToken

Method prototype

- (nullable LineSDKAccessToken *)currentAccessToken;

Gets the access token that the SDK is using for the current user.

Return value

Returns LineSDKAccessToken which contains the current user’s access token. Returns nil if there no access token is available.

getProfileWithCallbackQueue:completion

Method prototype

- (void)getProfileWithCallbackQueue:(dispatch_queue_t)queue completion:(LineSDKAPIGetProfileCompletion)completion NS_SWIFT_NAME(getProfile(queue:completion:));

Gets the current user’s profile information. To specify a dispatch queue where the completion block is to be executed, pass the desired queue into the queue parameter.

Parameters

Parameter Description
queue Queue where the completion block is executed. The completion block is executed in the main queue if this is nil.
completion Completion block called when the user’s profile information is returned.

Completion block arguments

Argument Description
profile The current user’s profile information.
error Error returned by the API call. nil if successful.

getProfileWithCompletion

Method prototype

- (void)getProfileWithCompletion:(void(^)(LineSDKProfile * _Nullable profile, NSError * _Nullable error))completion NS_SWIFT_NAME(getProfile(completion:));

Gets the current user’s profile information. The completion block is executed in the main queue.

Parameters

Parameter Description
completion Completion block called when the user’s profile information is returned.

Completion block arguments

Argument Description
profile The current user’s profile information.
error Error returned by the API call. nil if successful.

logoutWithCallbackQueue:completion

Method prototype

- (void)logoutWithCallbackQueue:(dispatch_queue_t)queue completion:(LineSDKAPILogoutCompletion)completion NS_SWIFT_NAME(logout(queue:completion:));

Revokes the current user’s access token. To specify a dispatch queue where the completion block is to be executed, pass the desired queue into the queue parameter.

Parameters

Parameter Description
queue Queue where the completion block is executed. The completion block is executed in the main queue if this is nil.
completion Completion block called when the logout is completed.

Completion block arguments

Argument Description
success YES if logout succeeds, NO if the logout fails.
error Error returned by the API call. nil if successful.

logoutWithCompletion

Method prototype

- (void)logoutWithCompletion:(void(^)(BOOL success, NSError * _Nullable error))completion;

Revokes the current user’s access token. The completion block is executed in the main queue.

Parameters

Parameter Description
completion Completion block called when the logout is complete.

Completion block arguments

Argument Description
success YES if logout succeeds, NO if the logout fails.
error Error returned by the API call. nil if successful.

refreshTokenWithCallbackQueue:completion

- (void)refreshTokenWithCallbackQueue:(dispatch_queue_t)queue completion:(LineSDKAPITokenRefreshCompletion)completion NS_SWIFT_NAME(refreshToken(queue:completion:));

Refreshes the access token that the SDK is using for the current user. To specify a dispatch queue where the completion block is to be executed, pass the desired queue into the queue parameter.

Parameters

Parameter Description
queue Queue where the completion block is executed. The completion block is executed in the main queue if this is nil.
completion Completion block called when the user’s token is refreshed.

Completion block arguments

Argument Description
accessToken The refreshed access token.
error Error returned by the API call. nil if successful

refreshTokenWithCompletion

Method prototype

- (void)refreshTokenWithCompletion:(void(^)(LineSDKAccessToken * _Nullable accessToken, NSError * _Nullable error))completion;

Refreshes the access token that the SDK is using for the current user. The completion block is executed in the main queue.

Parameters

Parameter Description
completion Completion block called when the user’s token is refreshed.

Completion block arguments

Argument Description
accessToken The refreshed access token.
error Error returned by the API call. nil if successful

verifyTokenWithCallbackQueue:Completion

Method prototype

- (void)verifyTokenWithCallbackQueue:(dispatch_queue_t)queue completion:(LineSDKAPIVerifyTokenCompletion)completion NS_SWIFT_NAME(verifyToken(queue:completion));

Checks to see if the access token that the SDK is using for the current user is valid. To specify a dispatch queue where the completion block is to be executed, pass the desired queue into the queue parameter.

Parameters

Parameter Description
queue Queue where the completion block is executed. The completion block is executed in the main queue if this is nil.
completion Completion block called when the user’s token is verified.

Completion block arguments

Argument Description
result The result of the verify call.
error Error returned by the API call. nil if successful

verifyTokenWithCompletion

Method prototype

- (void)verifyTokenWithCompletion:(void(^)(LineSDKVerifyResult * _Nullable result, NSError * _Nullable error))completion;

Checks to see if the access token that the SDK is using for the current user is valid. The completion block is executed in the main queue.

Parameters

Parameter Description
completion Completion block called when the user’s token is verified.

Completion block arguments

Argument Description
result The result of the verify call.
error Error returned by the API call. nil if successful

LineSDKAccessToken

Class

Superclass NSObject
Declared in LineSDKAccessToken.h

Properties

accessToken

Declaration

@property (nonatomic, copy, readonly) NSString *accessToken;

Access token stored by this object.

expiresIn

Declaration

@property (nonatomic, readonly) NSTimeInterval expiresIn;

The amount of time in milliseconds until the token expires.

Methods

estimatedExpiredDate

Method prototype

- (NSDate *)estimatedExpiredDate;

Returns the estimated time in UNIX time of when the access token will expire. The expiration time that is returned by this method is not exact because it is calculated using time values that are cached on the client.

Return value

The estimated time in UNIX time of when the access token will expire.

LineSDKCredential

Class

Superclass NSObject
Declared in LineSDKAPI.h

Properties

accessToken

Declaration

@property (nonatomic, strong, readonly, nullable) LineSDKAccessToken *accessToken;

Access token stored by this object.

permissions

Declaration

@property (nonatomic, strong, readonly) NSOrderedSet<NSString *> *permissions;

A set of permissions that the current user’s access token holds. The following is a list of the possible permission codes.

Permission code Description
P The token can be used to get the user’s profile information.

LineSDKLogin

Class

Superclass NSObject
Declared in LineSDKLogin.h
Protocols LineSDKLoginDelegate

Properties

configuration

Declaration

@property (nonatomic, strong, readonly) LineSDKConfiguration *configuration;

Contains various LINE SDK configuration values such as the Channel ID and the current access token.

Methods

canLoginWithLineApp

Method prototype

- (BOOL)canLoginWithLineApp;

Checks to see if it is possible to log in using the LINE app.

Return value

Returns YES if it is possible to log in using the LINE app and NO if it is not possible. If NO is returned, this means that the LINE app is not installed on the device.

handleOpenURL

Method prototype

- (BOOL)handleOpenURL:(NSURL *)aURL;

This method is used to handle the return data from the LINE app during app-to-app authentication. You must call it in your application’s openURL method as in the example in the right panel.

openURL Example

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
return [[LineSDKLogin sharedInstance] handleOpenURL:url];
}

Parameters

Parameter Description
aURL The URL passed into the openURL call.

Return value

YES if the URL is successfully handled by the SDK. NO if it fails.

installLineApp

Method prototype

- (void)installLineApp;

Transitions to the app store to install the LINE app.

isAuthorized

Method prototype

- (BOOL)isAuthorized;

Checks to see if the current user is logged in and has an access token.

Parameters

Return value

Returns YES if the SDK has an access token for the current user. This signifies that the user is logged in. Returns NO if there is no access token stored in the SDK.

isAuthorizing

Method prototype

- (BOOL)isAuthorizing;

Checks if login is in progress.

Return value

Returns YES if login is in progress and NO if there is no login in progress.

sharedInstance

Method prototype

+ (instancetype)sharedInstance;

Returns the singleton instance of LineSDKLogin.

startLogin

Method prototype

- (void)startLogin;

Begins the login process. If the LINE app is installed, the SDK defaults to using app-to-app authentication. If it is not installed, the SDK logs in using a browser.

startWebLoginWithSafariViewController

Method prototype

- (void)startWebLoginWithSafariViewController:(BOOL)useSafariViewControllerIfAvailable;

Begins the login process. This function uses a browser or Safari View Controller to log in, not app-to-app authentication.

Parameters

Parameter Description
useSafariViewControllerIfAvailable If YES, Safari View Controller is used to perform the login. If NO, a browser will be used to perform the login.

LineSDKConfiguration

Class

Superclass NSObject
Declared in LineSDKConfiguration.h

Properties

channelID

Declaration

@property (nonatomic, strong, readonly) NSString *channelID;

The LINE Channel ID that the application is configured to use. This value is read from the LineSDKConfig section in the application’s Info.plist.

Methods

Method prototype

- (nullable LineSDKAccessToken *)currentAccessToken;

Returns the access token that is currently stored by the SDK.

LineSDKLoginDelegate

Protocol

Extends protocol NSObject
Declared in LineSDKLogin.h

Defines the methods used to receive event notifications from LineSDKLogin objects.

Methods

didLogin

- (void)didLogin:(LineSDKLogin *)login
credential:(nullable LineSDKCredential *)credential
profile:(nullable LineSDKProfile *)profile
error:(nullable NSError *)error;

Parameters

Parameter Description
login The LineSDKLogin object that is used to make the login request.
credential The credentials granted by the login request.
profile The profile information of the current user.
error Information about the failure if the login request fails. nil if the login request is successful.

LineSDKProfile

Class

Superclass NSObject
Declared in LineSDKProfile.h

Properties

displayName

Declaration

@property (nonatomic, copy, readonly) NSString *displayName;

The user’s display name.

pictureURL

Declaration

@property (nonatomic, copy, readonly, nullable) NSURL *pictureURL;

The user’s profile image URL.

statusMessage

Declaration

@property (nonatomic, copy, readonly, nullable) NSString *statusMessage;

The user’s status message.

userId

Declaration

@property (nonatomic, copy, readonly) NSString *userID;

The current user’s user ID.

LineSDKVerifyResult

Class

Superclass NSObject
Declared in LineSDKVerifyResult.h

Properties

channelID

Declaration

@property (nonatomic, copy, readonly) NSString *channelID;

The Channel ID that is being used by the application.

expiresIn

Declaration

@property (nonatomic, readonly) NSTimeInterval expiresIn;

The amount of time in milliseconds until the token expires.

permissions

Declaration

@property (nonatomic, copy, readonly, nullable) NSOrderedSet<NSString *> *permissions;

A set of permissions that the current user’s access token holds. The following is a list of the possible permission codes.

Permission code Description
P The token can be used to get the user’s profile information.