> ## Documentation Index
> Fetch the complete documentation index at: https://docs-dev-update-anonymous-sessons-ea.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> Unbounceのランディングページで、ワンクリックのソーシャル認証を利用してユーザー情報を取得する方法。

# Unbounceのランディングページでユーザー情報を取得する

export const AuthCodeBlock = ({filename, icon, language, highlight, children}) => {
  const [displayText, setDisplayText] = useState(children);
  const [copyText, setCopyText] = useState(children);
  const wrapperRef = React.useRef(null);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      if (!window.autorun || !window.rootStore) {
        return;
      }
      unsubscribe = window.autorun(() => {
        let processedChildrenForDisplay = children;
        let processedChildrenForCopy = children;
        for (const [key, value] of window.rootStore.variableStore.values.entries()) {
          const escapedKey = key.replaceAll(/[.*+?^${}()|[\]\\]/g, (String.raw)`\$&`);
          let displayValue = value;
          if (key === "{yourClientSecret}" && value !== "{yourClientSecret}") {
            displayValue = value.substring(0, 3) + "*****MASKED*****";
          }
          processedChildrenForDisplay = processedChildrenForDisplay.replaceAll(new RegExp(escapedKey, "g"), displayValue);
          processedChildrenForCopy = processedChildrenForCopy.replaceAll(new RegExp(escapedKey, "g"), value);
        }
        setDisplayText(processedChildrenForDisplay);
        setCopyText(processedChildrenForCopy);
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  useEffect(() => {
    if (!wrapperRef.current) return;
    const originalWriteText = navigator.clipboard.writeText.bind(navigator.clipboard);
    let isOverriding = false;
    const handleClick = e => {
      const button = e.target.closest('[data-testid="copy-code-button"]');
      if (!button || !wrapperRef.current.contains(button)) return;
      isOverriding = true;
      navigator.clipboard.writeText = text => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
          return originalWriteText(copyText);
        }
        return originalWriteText(text);
      };
      setTimeout(() => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
        }
      }, 100);
    };
    const wrapper = wrapperRef.current;
    wrapper.addEventListener('click', handleClick, true);
    return () => {
      wrapper.removeEventListener('click', handleClick, true);
      if (navigator.clipboard.writeText !== originalWriteText) {
        navigator.clipboard.writeText = originalWriteText;
      }
    };
  }, [copyText]);
  return <div ref={wrapperRef}>
      <CodeBlock filename={filename} icon={icon} language={language} lines highlight={highlight}>
        {displayText}
      </CodeBlock>
    </div>;
};

<h2 id="auth0-configuration">
  Auth0 Configuration
</h2>

1. Auth0アカウントを作成し、[Auth0 Dashboard](https://manage.auth0.com/#)に移動します。
2. [Dashboard > アプリケーション](https://manage.auth0.com/#/applications)に移動し、**+ Create Application** をクリックします。`シングルページアプリケーション` を選択して、**設定** に進みます。**Client ID** と **Domain** を控えておきます。
3. **Allowed Callback URLs** と **Allowed Origins (CORS)** の両方に `コールバック URL` を追加します。UnbounceページのURLを指定してください。例: `http://unbouncepages.com/changeit`
4. [Dashboard > Authentication > Social](https://manage.auth0.com/#/connections/social)に移動し、使用したいソーシャルプロバイダーを有効にします。

<h2 id="unbounce-configuration">
  Unbounce の設定
</h2>

1. ボタンなど、プロバイダーでのログインをトリガーする新しい UI 要素を作成します。**Properties > Element Metadata** で、その UI 要素の ID を確認してください。
2. Unbounce のランディングページに新しい JavaScript を追加し、`Placement` で `Before Body End Tag` を選択して、以下のコードを追加します。また、依存関係として jQuery にも必ずチェックを入れてください。

export const codeExample = `<script src="https://cdn.auth0.com/js/auth0/9.11/auth0.min.js"></script>
<script type="application/javascript">
  var webAuth = new auth0.WebAuth({
    domain:       '{yourDomain}',
    clientID:     '{yourClientId}',
    audience: 'https://{yourClientId}/userinfo'
    redirectUri:  '{yourUnbouncePageUrl}', // 例: http://unbouncepages.com/changeit
    scope: 'openid profile email',
    responseType: 'token id_token',
  });
</script>`;

<AuthCodeBlock children={codeExample} language="html" />

先ほど設定したアプリケーションの<Tooltip tip="Client ID: Auth0 から登録済みリソースに付与される識別値。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=Client+ID">Client ID</Tooltip>とDomainを使用します。

次に、ソーシャルプロバイダーから送られてくる情報を Unbounce に渡す方法を用意する必要があります。

1. Form を作成し、各項目に `Hidden fields` を追加します。たとえば、`name` フィールドや `email` フィールドです。
2. Unbounce の JavaScript エディターに戻ります。
3. 各ボタンに、ソーシャル認証をトリガーするクリックハンドラーを追加します。

   1. 先ほど控えたボタン ID と [接続名](/docs/ja-jp/authenticate/identity-providers/locate-the-connection-id) に置き換えます。たとえば、Google には `google-oauth2`、LinkedIn には `linkedin` を使用します。
   2. ID を正しく置き換えていることを確認してください。`#name` と `#email` の代わりに、該当する Form フィールドの ID を指定する必要があります (Form の編集中に `Field Name and ID` で確認できます) 。

```js lines theme={null}
$('#{buttonId}').bind('click', function() { 
  webAuth.authorize({
    connection: '{yourConnectionName}'
  });
});

// 認証完了後、parseHashメソッドはURLハッシュフラグメントを解析して、Auth0認証レスポンスの結果を取得します。

webAuth.parseHash({ hash: window.location.hash }, function(err, authResult) { 
  if (err) { 
    return console.log(err); 
  }

  if (authResult != null && authResult.accessToken != null) {
    webAuth.client.userInfo(authResult.accessToken, function(err, user) {
      $('#name').val(user.name); 
      $('#email').val(user.email); 
    }); 
  } 

});
```

これで、ユーザーが Form を送信すると、Unbounce Admin Panel の `Leads` セクションで <Tooltip tip="Identity Provider（IdP）：デジタルアイデンティティを保存・管理するサービス。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=IdP">IdP</Tooltip> から提供された情報を確認できるようになります。
