LINE Engineering
Blog

LIFF, our latest product for third party developers

Sho Tachibana 2018.06.15

I am a technical evangelist for the LINE platform, including LINE Messaging API and LINE Login.

What is LIFF?

LIFF is one of our latest products out for LINE Messaging API users. So, what is LIFF? LIFF stands for the LINE Front-end Framework, a web app platform that runs inside the LINE app. LIFF apps running on the LINE app can obtain LINE user ID or tokens needed to use the LIFF API. With the information obtained, LIFF apps can provide features using user information, such as sending messages on behalf of the user.

LIFF animation

LIFF apps can be displayed in one of the following three sizes, and you can change your mind about the size after choosing one. Like any other web apps, LIFF apps can handle interactive content, and using the LIFF SDK, you can obtain user profile, and send text and images on behalf of the user.

LIFF size

Let's make a LIFF app together

The fastest way to learn how it works is to make one. Let's make a sample LIFF app together. Our app is going to enable users to draw up an image and send it over a chat.

LIFF sample app

A usual convention of sending a drawing in a chatroom would look something like the following process:

  1. Close the LINE app.
  2. Launch an app for drawing.
  3. Draw an image and save it.
  4. Open the LINE app again.
  5. Tap the input field to get the keyboard.
  6. Tap the file attachment button.
  7. Open the gallery of your device.
  8. Select the drawing.
  9. Send the drawing.

Now, here is what you do with LIFF. Look how UX is simplified and improved dramatically.

  1. Open the LIFF app on the LINE app.
  2. Draw and tap the send button.

Getting started

Creating a channel for your LIFF app

Let's get started with preparation first. To make a LIFF app, you need a valid LINE@ channel to use the Messaging API. Check the Getting started with the Messaging API guide and proceed up to the "Issue a channel access token" of the Building a bot guide. Keep the channel access token.

Building a bot requires you to set a webook URL, but if you are only making a LIFF app, you can skip the setting. For your information, the app icon image for yur channel becomes the favicon for your LIFF app, which gets displayed on the title bar of your LIFF app.

LIFF icon

Registering LIFF app to a channel

Now, let's get really started. Note that LIFF apps are linked to a channel, using the channel access token, and you can make up to ten LIFF apps per channel.

Enter the following command on a terminal or command prompt, with the values replaced as guided below:

  • YOUR_CHANNEL_ACCESS_TOKEN: The access token you obtained in the previous section.
  • SIZE_OF_LIFF: The screen size of your LIFF app; remember the three choices, "compact", "tall", and "full".
  • URL_OF_YOUR_APPLICATION: The URL of the web page or web application with the LIFF app. The link MUST use the HTTPS protocol.
curl -XPOST \
-H "Authorization: Bearer YOUR_CHANNEL_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
 "view": {
 "type": "SIZE_OF_LIFF",
 "url": "URL_OF_YOUR_APPLICATION"
 }
}' \
https://api.line.me/liff/v1/apps

As a successful result of running the command, you will get an App ID in the format shown below, which will be used in the URL to access your LIFF app. So, with our example, the URL to our LIFF app is, line://app/1234567890-XXXXXXXX. And, LIFF apps can be opened in any type of chatroom, 1:1 or group.

{"liffId":"1234567890-XXXXXXXX"}

We provide a set of server APIs for you to check, update and delete the information of LIFF apps. For more information, check out the API Reference.

Developing a LIFF app

Let's get down to the real thing now. We will use Python 3.6, Flask for framework and Bootstrap for layout.

Making a blank webpage

We will start off with a blank webpage for a simple start. To create a blank webpage, we will prepare the following three files.

app.py

from flask import Flask, request, render_template, make_response
from flask_bootstrap import Bootstrap

import os
import uuid
import base64

from PIL import Image
import warnings
warnings.simplefilter('error', Image.DecompressionBombWarning)

app = Flask(__name__)
bootstrap = Bootstrap(app)

@app.route('/')
def do_get():
    return render_template('index.html')

if __name__ == '__main__':
    app.debug = True
    app.run()

index.html

Now write an HTML page for our LIFF app. We'll set the title of the html is set to "Paint Sample". This title will be the text displayed in the title bar of our LIFF app. Apart from the title, nothing is on the page yet.

{% extends "bootstrap/base.html" %}

{%- block metas %}
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
{%- endblock metas %}

{% block title %}Paint Sample{% endblock %}

{% block content %}
{% endblock %}

requirements.txt

List required packages to install in the requirements.txt file.

flask
gunicorn
flask-bootstrap
Pillow

Adding a canvas and a button

On our blank web page, we are going to add a canvas for users to draw on and a button to save the drawing. Modify the following two files we made in previous step.

app.py

Change and add code as instructed below. First, changing. What we are doing is decoding the data obtained from the webpage, saving the decoded data into the imgs folder, and returning the name of the folder.

# Change the following
# app = Flask(__name__)
app = Flask(__name__, static_folder='imgs')

Add the following code. We will need a thumbnail to share the image on a chatroom, so make a thumbnail that is equal to or greater than 240px for width and height.

# Add the following
@app.route('/saveimage', methods=['POST'])
def saveimage():
    event = request.form.to_dict()

    dir_name = 'imgs'
    img_name = uuid.uuid4().hex

    # Saving image in the 'imgs' folder temporarily. Should be deleted after a certain period of time
    if not os.path.exists(dir_name):
        os.makedirs(dir_name)
    with open(os.path.join(dir_name, '{}.jpg'.format(img_name)), 'wb') as img:
        img.write(base64.b64decode(event['image'].split(",")[1]))

    original = Image.open(os.path.join(dir_name, '{}.jpg'.format(img_name)))
    # Needs simple validation of format for security since Pillow supports various type of Images
    if(original.format != 'JPEG'):
        return make_response('Unsupported image type.', 400)

    original.thumbnail((240, 240), Image.ANTIALIAS)
    original.save(os.path.join(dir_name, '{}_240.jpg'.format(img_name)), 'JPEG')

    return make_response(img_name, 200)

index.html

By adding the following code, we are adding a canvas for users to draw anything they want, and a button for users to save their drawing.

{%- endblock metas %}

<!--Add-->
{% block scripts %}
{{super()}}
  <script src="https://cdn.jsdelivr.net/npm/signature_pad@2.3.2/dist/signature_pad.min.js"></script>
  <script>
    const canvas = document.querySelector('#canvas');
    const signaturePad = new SignaturePad(canvas, {
    backgroundColor: 'rgb(238,238,238)',
    });

    $(window).on('load', function(){
    canvas.setAttribute('width', $('.container').width());
    canvas.setAttribute('height', window.innerHeight - $('#btn').outerHeight() - 10);
    signaturePad.clear();
    });
 </script>
{% endblock %}
<!--End Add-->

{% block title %}Paint Sample{% endblock %}

<!--Add-->
{% block content %}
<div class="container">
  <canvas id="canvas"></canvas>
  <button id="btn" type="button" class="btn btn-primary btn-block">Share</button>
</div>
{% endblock %}
<!--End Add-->

Sending the image and sender name to a chatroom

Lastly, we need to send out the image saved and the sender's name to the chatroom, and we will use the LIFF SDK for it. Modify your index.html as shown below.

index.html

With the following code, once a user taps the button, the drawing on the canvas will be saved and sent out to the chatroom together with the sender's name. For more information on the LIFF SDK, see API Reference.

<script>
    $(window).on('load', function(){
    canvas.setAttribute('width', $('.container').width());
    canvas.setAttribute('height', window.innerHeight - $('#btn').outerHeight() - 10);
    signaturePad.clear();
    // Add
    liff.init(function (data) {});
    });
</script>
 <!-- Add -->
 <script src="https://d.line-scdn.net/liff/1.0/sdk.js"></script>
 <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
 <script>
   $('#btn').on('click', function() {
     $.ajax({
       type: 'POST',
       url: '/saveimage',
       data: {
         'image': signaturePad.toDataURL('image/jpeg')
       },
       success: function (res, status) {
         liff.getProfile().then(function (profile) {
           liff.sendMessages([
             {
               type: 'image',
               originalContentUrl: 'https://' + document.domain + '/imgs/' + res + '.jpg',
               previewImageUrl: 'https://' + document.domain + '/imgs/' + res + '_240.jpg'
             },
             {
               type: 'text',
               text: 'From:' + profile.displayName
             }
           ]).then(function () {
             liff.closeWindow();
           }).catch(function (error) {
             window.alert('Error sending message: ' + error.message);
           });
         }).catch(function (error) {
             window.alert("Error getting profile: " + error.message);
         });
       },
       error: function (res) {
         window.alert('Error saving image: ' + res.status);
       },
       complete: function(data) {
       }
     });
   });
 </script>

Using LIFF app in a chatroom

Now, let's try out our LIFF app in a chatroom. Become a friend with a bot, send the link to our LIFF app, and tap the link. Our LIFF app will be displayed over the chatroom, and it's time to show off your artistic skills.

LIFF chatroom

It wasn't so difficult after all, was it?

Summary

With LIFF, LINE users can share interactive content with each other, without having to close the LINE app or having to log into LINE on web. LIFF apps allow you to share text or images to a chatroom. Now we will leave you to enjoy making wonderful LIFF apps. Do share your LIFF apps with us by tweeting with a hashtag, "#LINE_API". We will be waiting!

LINE BOT Messaging API

Sho Tachibana 2018.06.15

I am a technical evangelist for the LINE platform, including LINE Messaging API and LINE Login.

Add this entry to Hatena bookmark

Back to blog list