LIFF SDK V2でLIFFを外部ブラウザでも利用できるようにする #LINE_API

2019.10.21

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

はじめに

こんにちは、中村です。
LINE上でWebアプリを提供するプラットフォームLIFFで利用できるLIFF SDK V2がリリースされました。

LIFF v2がリリースされ、外部ブラウザ対応やQRコードリーダー等便利な機能が追加されました。

今回のリリースで外部ブラウザからLIFFアプリにアクセスができるようになりした。本記事では実際に外部ブラウザでアクセスし同様の機能が動くか確認します。LIFFの登録方法はこちらをご確認ください。

LIFFアプリをチャネルに追加する

LIFF SDK V2でブラウザでも利用できるようにする

LIFFへはHTTPSのエンドポイントを登録する必要がありますので、CloudfrontとS3で環境を構築していきます。

AWSマネジメントコンソールを利用しても良いのですが、Cloudformationを利用することで環境構築をコード管理できます。

AWSTemplateFormatVersion: 2010-09-09
Description: Static contents distribution using S3 and CloudFront.

Parameters:
  SPABucketName:
    Type: String
    Description: Set bucket name

  Env:
    Type: String
    Default: itg
    AllowedValues: ["itg", "stg", "prd"]
    Description: Set environment

Resources:
  # S3 bucket contains static contents
  AssetsBucket:
    Type: AWS::S3::Bucket
    DeletionPolicy: Retain
    Properties:
      BucketName: !Sub ${SPABucketName}-${Env}-${AWS::Region}-${AWS::AccountId}

  # S3 bucket policy to allow access from CloudFront OAI
  AssetsBucketPolicy:
    Type: AWS::S3::BucketPolicy
    Properties:
      Bucket: !Ref AssetsBucket
      PolicyDocument:
        Statement:
          - Action: s3:GetObject
            Effect: Allow
            Resource: !Sub arn:aws:s3:::${AssetsBucket}/*
            Principal:
              AWS: !Sub arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${CloudFrontOriginAccessIdentity}
 
  # CloudFront Distribution for contents delivery
  AssetsDistribution:
    Type: AWS::CloudFront::Distribution
    Properties:
      DistributionConfig:
        Origins:
        - Id: S3Origin
          DomainName: !GetAtt AssetsBucket.DomainName
          S3OriginConfig:
            OriginAccessIdentity: !Sub origin-access-identity/cloudfront/${CloudFrontOriginAccessIdentity}
        Enabled: true
        DefaultRootObject: index.html
        Comment: !Sub ${AWS::StackName} distribution
        DefaultCacheBehavior:
          TargetOriginId: S3Origin
          ForwardedValues:
            QueryString: false
          ViewerProtocolPolicy: https-only
          DefaultTTL: 0
          MinTTL: 0
          MaxTTL: 0

  # Cloudfront Origin Access Identity
  CloudFrontOriginAccessIdentity:
    Type: AWS::CloudFront::CloudFrontOriginAccessIdentity
    Properties:
      CloudFrontOriginAccessIdentityConfig:
        Comment: !Ref AWS::StackName
 
Outputs:
  URL:
    Value: !Join [ "", [ "https://", !GetAtt [ AssetsDistribution, DomainName ]]]

環境が作成されたら、S3へHTML, CSS, JavaScriptをデプロイすると、Cloudfront経由でアクセスができます。またLINE開発者コンソールでLIFFアプリに登録が必要になりますので、HTTPSのエンドポイントを登録してください。ここまで完了し、LIFF URLからもアクセスが確認できたら成功です。後ほど、コードの中で利用するのでLIFF URL line://app/xxxxxxxxxxxxxxxxをメモしておいてください。

ソースコードはこのような形になります。

<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
        <title>Sandbox LIFF V2</title>
    </head>
    <body>
        <button id="logout">ログアウトする</button>
        <h1 id="name"></h1>
        <p id="userId"></p>
        <img id="picture" alt="profile" width="100%"/>
        <script src="https://static.line-scdn.net/liff/edge/2.1/sdk.js"></script>
        <script>
            liff.init({
                liffId: 'xxxxxxxx' //先ほどメモしたものを入力してください。
            })
            .then(async () => {
                if (liff.isInClient()) {
                    const accessToken = liff.getAccessToken();
                    const profile = await liff.getProfile();
                    document.getElementById('name').innerText = profile.displayName;
                    document.getElementById('userId').innerText = profile.userId;
                    document.getElementById('picture').src = profile.pictureUrl;
                } else {
                    if (liff.isLoggedIn()) {
                        console.log('Logged in.');
                        const accessToken = liff.getAccessToken();
                        const profile = await liff.getProfile();
                        document.getElementById('name').innerText = profile.displayName;
                        document.getElementById('userId').innerText = profile.userId;
                        document.getElementById('picture').src = profile.pictureUrl;
                    } else {
                        liff.login();
                    }
                }
                document.getElementById('logout').addEventListener('click', function() {
                    if (liff.isLoggedIn()) {
                        liff.logout();
                        window.location.reload();
                    }
                });
            })
            .catch((err) => {
                console.log(err.code, err.message);
            });
        </script>
    </body>
</html>

LIFFを初期化後、以下を確認しています。

  • LINE内ブラウザでアクセスしたか
  • 外部ブラウザアクセス時にLINEログインしたか

さらにユーザーID、登録名、プロフィール画像を取得し表示しています。ここまで完了したらデプロイして、LIFF URLとHTTPSエンドポイントでアクセスして確認してみます。

LIFF URLへアクセスした時

LIFF URLの場合は情報が表示されます。

HTTPSエンドポイントへアクセスした時

HTTPSエンドポイントヘアクセスした場合は、LINEログイン後情報が表示されます。

まとめ

外部ブラウザ対応によりWebでもLIFFでも同様の機能を提供できるようになりました。まだ紹介しておりませんが、LIFF SDK V2には他にも新機能が追加されておりますので別記事にてご紹介します。