# 6.[応用編]LIFFアプリを埋め込む

  • 4章ではプレーンなHTMLを作成してLIFFアプリとして埋め込みました
  • ですがより複雑なことをやろうとするとReactなどのライブラリを使ったほうができることは増えてきます
  • この章ではReactを使ったLIFFアプリの作り方を紹介します

# ゴール

  • Reactを使ってLIFFアプリを作成できること
  • LIFFアプリでLINEのユーザ情報にアクセスできること

# 6-1.Reactアプリの雛形作成

  • まずは雛形を生成するためのライブラリをインストールします
npm install -g snowpack@next
1
  • Reactプロジェクトを生成します
npx create-snowpack-app line-bot-handson-liff-react --template @snowpack/app-template-react --use-yarn
1
  • 生成できたらプロジェクトに移動しておきます
cd line-bot-handson-liff-react
1
  • 以下のようなファイルが生成されました
% tree -I node_modules
.
├── LICENSE
├── README.md
├── babel.config.json
├── jest.config.js
├── jest.setup.js
├── package.json
├── public
│   ├── favicon.ico
│   ├── index.html
│   └── robots.txt
├── snowpack.config.json
├── src
│   ├── App.css
│   ├── App.jsx
│   ├── App.test.jsx
│   ├── index.css
│   ├── index.jsx
│   └── logo.svg
└── yarn.lock
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 6-2.LIFF SDKのセットアップ

# LIFF IDの確認

LIFF ID

# 実装の追加

  • LIFF SDKを読み込むようにしていきます
  • public/index.htmlを修正します
    • 14行目にLIFF SDKの読み込み処理を追加しています

 





 





 



<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="description" content="Web site created using create-snowpack-app" />
    <title>LIFF App</title>
  </head>
  <body>
    <div id="root"></div>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <script type="module" src="/_dist_/index.js"></script>
    <script src="https://static.line-scdn.net/liff/edge/2.1/sdk.js"></script>
  </body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  • src/lib/liff.jsを作成し以下の内容を記述してください
export const liff = window.liff;
1
  • LIFFを適用していきます
  • src/App.jsxを修正してください
    • 丸ごと置き換えてしまってください
    • liffIdは自分のIDをセットしてください
import React from 'react';
import useLiff from './hooks/useLiff';

// LIFF IDを設定
const liffId = '1111111111-XXXXXXXX';

function App() {
  const { loading, error } = useLiff({ liffId });

  if (loading) return <p>...loading</p>;
  if (error) return <p>{error.message}</p>;

  return (
    <div>
      <h1>Hello LIFF</h1>
    </div>
  );
}

export default App;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  • 最後にLIFFのAPIを呼び出すファイルを作成します
  • src/hooks/useLiff.jsを作成し以下の内容を記述してください
import { useState, useEffect } from 'react';
import { liff } from '../lib/liff';

function useLiff({ liffId }) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const initLiff = async ({ liffId }) => {
    setLoading(true);
    try {
      // LIFF APIのinitを呼び出して初期化
      await liff.init({ liffId });
      if (liff.isLoggedIn()) {
        console.log('logged in!');
        alert('success liff init');
      } else {
        console.log('not logged in');
        liff.login();
      }
    } catch (error) {
      alert({ error });
      setError(error);
    } finally {
      setLoading(false);
    }
  };

  // useLiff関数の初期化時に実行される
  useEffect(() => {
    initLiff({ liffId });
  }, [liffId]);

  return { loading, error };
}

export default useLiff;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

# デプロイ

  • まだ処理は入れていませんがこの段階で一度デプロイしてしまいましょう
  • Netlifyのアカウントを持っていない人は作成してください
  • Netlify CLIをインストールします
npm i -g netlify-cli
1
  • コマンドラインでNetlifyにログインします
netlify login
1
  • 実行するとブラウザが立ち上がるのでAuthorizeを選択してください
  • 最後にline-bot-handson-liff-reactディレクトリで以下のコマンドを実行するとデプロイ完了です
yarn build
netlify deploy --prod --dir=build
1
2
  • コマンドを実行するといくつか尋ねられます
    • 1つめの質問はCreate & configure a new siteを選択します
    • 2つめ以降はそのままエンター連打で大丈夫です

Netlify deploy1

  • 完了するとログの一番下にURLが表示されます
    • この後使うのでメモしておいてください

Netlify deploy

# LIFFアプリとして登録

  • 最後にデプロイしたページをLIFFアプリとして登録します
  • LINEのデベロッパーコンソールから設定します
  • 4章で登録したLIFFアプリを編集します

LIFF

  • エンドポイントURLを先程デプロイしたURLに変更しましょう

LIFFエンドポイント

# 動作確認

  • スマホでアクセスして動きを見てみます

success

  • Succesのアラートが出れば正常にLIFFアプリとして読み込まれてるということです

# 6-3.LINEのユーザ情報の取得

  • LIFFの機能を使ってLINEのユーザ情報にアクセスしてみます
  • src/hooks/useLiff.jsを修正します






 
 




















 
 
 
 
 
 
 
 
 
 
 
 
 





 
 




import { useState, useEffect } from 'react';
import { liff } from '../lib/liff';

function useLiff({ liffId }) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  // ユーザ情報を格納するstateを追加
  const [profile, setProfile] = useState(null);

  const initLiff = async ({ liffId }) => {
    setLoading(true);
    try {
      // LIFF APIのinitを呼び出して初期化
      await liff.init({ liffId });
      if (liff.isLoggedIn()) {
        console.log('logged in!');
      } else {
        console.log('not logged in');
        liff.login();
      }
    } catch (error) {
      alert({ error });
      setError(error);
    } finally {
      setLoading(false);
    }
  };

  // ユーザ情報を取得する関数を追加
  const fetchProfile = async () => {
    setLoading(true);
    try {
      // LIFF APIのgetProfileを実行し結果をセット
      setProfile(await liff.getProfile());
    } catch (error) {
      console.log({ error });
      setError(error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    initLiff({ liffId });
  }, [liffId]);

  // fetchProfileとprofileを追加
  return { loading, error, fetchProfile, profile };
}

export default useLiff;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
  • src/App.jsxを修正して取得した情報を画面に出すようにします







 
 







 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 


import React from 'react';
import useLiff from './hooks/useLiff';

// 自身のLIFF IDを設定
const liffId = '1234567890-abcedfgh';

function App() {
  // profileとfetchProfileを追加
  const { loading, error, profile, fetchProfile } = useLiff({ liffId });

  if (loading) return <p>...loading</p>;
  if (error) return <p>{error.message}</p>;

  return (
    <div>
      <h1>Hello LIFF</h1>
      {/* 追加 */}
      <section>
        {/* ボタンをクリックしたらfetchProfileを実行 */}
        <button onClick={() => fetchProfile()}>Get Profile</button>
        {/* 取得したProfileを表示 */}
        {profile && (
          <div>
            <p>UserID: {profile.userId}</p>
            <p>DisplayName: {profile.displayName}</p>
          </div>
        )}
      </section>
    </div>
  );
}

export default App;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  • ビルドしてデプロイしましょう
yarn build
netlify deploy --prod --dir=build
1
2
  • スマホからアクセスするとLINEのユーザ名が取得できています
    • ID、名前のほかはプロフィール画像とステータスメッセージを取得できます

profile

# 6-4.リンク集も表示するようにする

  • 最後に4章と同じ内容も表示するようにしておきます
  • src/App.jsxを修正します
    • return文を修正しています















 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 





import React from 'react';
import useLiff from './hooks/useLiff';

// 自身のLIFF IDを設定
const liffId = '1234567890-abcedfgh';

function App() {
  const { loading, error, profile, fetchProfile } = useLiff({ liffId });

  if (loading) return <p>...loading</p>;
  if (error) return <p>{error.message}</p>;

  return (
    <div>
      <h1>Hello LIFF</h1>
      <section>
        <button onClick={() => fetchProfile()}>Get Profile</button>
        {profile && <p>こんにちは {profile.displayName}さん</p>}
      </section>
      <h2>ハンズオン資料</h2>
      <ul>
        <li>
          <a href="https://firebase-handson.ozaki25.now.sh/" target="_blank">
            Firebase Authenticationハンズオン
          </a>
        </li>
        <li>
          <a href="https://graphql-handson.ozaki25.now.sh/" target="_blank">
            GraphQLハンズオン
          </a>
        </li>
        <li>
          <a href="https://jamstack-handson.ozaki25.now.sh/" target="_blank">
            Jamstackハンズオン
          </a>
        </li>
        <li>
          <a href="https://line-bot-handson.ozaki25.now.sh/" target="_blank">
            LINE Botハンズオン
          </a>
        </li>
      </ul>
    </div>
  );
}

export default App;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
  • CSSを適用するためにpublic/index.htmlに二行追加します








 
 









<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="description" content="Web site created using create-snowpack-app" />
    <title>LIFF App</title>
    <link rel="stylesheet" href="https://fonts.xz.style/serve/inter.css" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@exampledev/new.css@1.1.2/new.min.css" />
  </head>
  <body>
    <div id="root"></div>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <script type="module" src="/_dist_/index.js"></script>
    <script src="https://static.line-scdn.net/liff/edge/2.1/sdk.js"></script>
  </body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  • ビルドしてデプロイしましょう
yarn build
netlify deploy --prod --dir=build
1
2
  • スマホからアクセスすると4章と同じリンク集も表示されています

links

# 参考記事

Last Updated: 2020/05/26