# UI を構築する Stripe ダッシュボードの機能を拡張するカスタム UI を構築、テスト、および編集します。 TypeScript、React、Stripe の [UI Extensions SDK](https://docs.stripe.com/stripe-apps/reference/extensions-sdk-api.md) と [UI ツールキット](https://docs.stripe.com/stripe-apps/design.md)を使用して Stripe ダッシュボードを拡張することで、アプリをユーザーインターフェイスで使用できるようにします。このガイドでは、ビューを作成および削除することによって単純な UI を構築する方法を説明します。 技術概要については、[UI Extensions の仕組みをご覧ください](https://docs.stripe.com/stripe-apps/how-ui-extensions-work.md)。 ## ビューを追加する ビューを使用してアプリの UI を開発します。ビューは、React コンポーネントと指定のビューポートのペアリングです。React コンポーネントは、Stripe の UI ツールキットの UI コンポーネントで構成されています。ビューポートは、その UI を表示する Stripe ダッシュボードのページまたはセクションです。 1. 次のように、プロジェクトのルートディレクトリーで `add` コマンドを使用します。 ```bash stripe apps add view ``` 1. 指示に従います。 - ビューが表示されるビューポートを選択します。[使用できるビューポート](https://docs.stripe.com/stripe-apps/reference/viewports.md)のリストをご覧ください。 - ビューに名前を指定します (MyComponentName など)。CLI は、ビューポートの選択に従って名前を提案します。 Stripe は、自動的に*アプリマニフェスト* (In a Stripe App, the app manifest is a stripe-app.json file in your app's root directory. It defines your app's ID, views, permissions, and other essential properties)の `views` 配列にビューを追加し、`src/views` ディレクトリーに新しい React コンポーネントファイルを作成し、それと同時にユニットテストファイルを作成します。 ## アプリケーションをプレビューする アプリをローカルで実行し、更新し、変更内容をダッシュボードでプレビューできます。 1. プロジェクトのルートディレクトリーから、開発サーバーを起動します。 ```bash stripe apps start ``` 1. **Enter** を押してブラウザーを開きます。 1. **続行** をクリックして、Stripe アカウントでアプリをプレビューします。アプリをプレビューする前に[ローカルネットワークアクセスを有効](https://docs.stripe.com/stripe-apps/enable-local-network-access.md)にしてください。 1. 開発サーバーを停止するには、コマンドラインから **Ctrl+C** と入力します。 開発者サーバーが実行されているときは、アプリに変更を加えると、ページを更新することなくそれがダッシュボードに自動的に表示されます。エラーは、解決されるまで、Stripe ダッシュボード、ブラウザーの開発者ツール、Stripe CLI に自動的に表示されます。 ### プレビューの切り替え アプリのローカルバージョンのプレビューを無効にすると、*サンドボックス環境* (A sandbox is an isolated test environment that allows you to test Stripe functionality in your account without affecting your live integration. Use sandboxes to safely experiment with new features and changes)または[テスト環境でインストールしたアプリの最新バージョン](https://docs.stripe.com/stripe-apps/upload-install-app.md)をプレビューできるようになります。テスト環境またはサンドボックス環境でアプリのいずれのバージョンもインストールしたことがない場合、プレビューを切り替えることはできません。 最近インストールしたバージョンのアプリをテスト環境またはサンドボックス環境でプレビューするには、開発サーバーを起動し、次の手順に従います。 1. アプリで、アプリの右上にあるオーバーフローメニュー ⋯ をクリックします。 1. **アプリのプレビューを無効化**をクリックし、**続行**をクリックします。 ## ダッシュボードで Stripe オブジェクトにアクセスする ビューポートにコンポーネントを割り当てると、コンポーネントは `environment.objectContext` オブジェクトを使用して、そのページの Stripe オブジェクトに関するコンテキストを受け取ることができます。 たとえば、`stripe.dashboard.customer.detail` ビューポートを使用するビューを作成する場合、`environment.objectContext` オブジェクトは `customer` オブジェクトタイプと、現在のユーザーの ID を返します。次に、それらの値を使用して、[Customer (顧客)](https://docs.stripe.com/api/customers.md?lang=node) オブジェクトに関する詳細情報を取得し、住所、説明などの属性を変更できます。 ビューポートが提供するオブジェクトのインデックスについては、[ビューポートのリファレンスドキュメント](https://docs.stripe.com/stripe-apps/reference/viewports.md)をご覧ください。 ### 例: 顧客名を更新する 次のコードでは、[Stripe Node.js API クライアント](https://docs.stripe.com/api.md?lang=node)と、ビューポートの `environment.objectContext` ID を使用して、顧客名を更新します。 1. アプリに `customer_write` 権限を追加します。 ```bash stripe apps grant permission "customer_write" "Allows the app to update the name of the customer." ``` 1. アプリで Stripe API を使用し、顧客名を更新します。 ```js import {createHttpClient, STRIPE_API_KEY} from '@stripe/ui-extension-sdk/http_client'; import Stripe from 'stripe'; // Initiate communication with the stripe client. const stripe = new Stripe(STRIPE_API_KEY, { httpClient: createHttpClient(), apiVersion: '2022-08-01', }) const App = ({environment, userContext}) => { // Call the Stripe API to make updates to customer details. const updateCurrentCustomer = async (newCustomerName) => { try { // If the user has permission to update customers, this should succeed. const updatedCustomer = await stripe.customers.update( // We can use the current objectContext to get the customer ID. environment.objectContext.id, {name: newCustomerName} ); console.log(updatedCustomer.name); } catch (error) {} }; } ``` ### 例: ダッシュボードのデータを更新する アプリがダッシュボードのデータを変更する場合は、[useRefreshDashboardData](https://docs.stripe.com/stripe-apps/reference/extensions-sdk-api.md#useRefreshDashboardData) 関数を使用して、データを更新するコールバックを生成します。 ```js import {useCallback} from 'react'; import {useRefreshDashboardData} from '@stripe/ui-extension-sdk/context'; const App = () => { // Get the callback used to refresh the dashboard data const refreshDashboardData = useRefreshDashboardData(); // Stripe API call const updateCustomer = useCallback(async () => { try { await updateCurrentCustomer(); // Call to refresh the data in the Dashboard refreshDashboardData(); } catch (error) {} }, [refreshDashboardData]); } ``` ## サードパーティーの API を使用する UI 拡張機能は、サードパーティー API (独自の API またはパブリック API) を呼び出して、アプリでデータのリクエストや送信を行うことができます。 1. 次のように `grant url` コマンドを使用して、サードパーティー API の URL を追加します。 ```bash stripe apps grant url "https://*.api.example.com/path/" "Send data to example service..." ``` **connect-src** URL は、次の要件を満たしている必要があります。 | 要件 | 例 | | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------ | | 安全な HTTPS プロトコルを使用します。 | **https://www.example.com/api/users/** | | パスを含みます。 | - 有効な例: **https://www.example.com/api/users/** - 無効な例: **https://www.example.com/** | | 末尾にスラッシュを付けたベースパスを使用して、それ以降のすべてのパスを許可します。 | **https://www.example.com/api/** は、**https://www.example.com/api/users/abc123/address** への呼び出しを有効にします。 | | Stripe API へのコールにすることはできません。 | | | ワイルドカード (`*`) を使用する場合は、左端の DNS ラベルに含める必要があります。 | **https://\*.example.com/api/users/** | > ブラウザーで CSP の問題に悩まされている場合は、`connect-src` URL の末尾にスラッシュを追加してください。 Stripe Apps によって、プロジェクトの*アプリマニフェスト* (In a Stripe App, the app manifest is a stripe-app.json file in your app's root directory. It defines your app's ID, views, permissions, and other essential properties)の `connect-src` 配列に URL が追加されます。 ```js "ui_extension": { "views": [], "actions": [], "content_security_policy": { "connect-src": [ "https://*.api.example.com/", "https://o0.ingest.example.io/api/", ], "purpose": "Send data to example service. The Example app sends data to the Example service to provide its functionality and sends anonymous error reports to our partner Example for debugging purposes" } } ``` connect-src URL の削除には、Stripe CLI を使用することもできます。 ```bash stripe apps revoke connect-src "https://*.api.example.com/path/" ``` 1. ブラウザーでアプリをプレビューするには、開発サーバーを起動して、CLI のプロンプトに従います。 ```bash stripe apps start ``` 1. アプリで、サードパーティー API の URL を指定した `fetch` コールを追加します。 たとえば、*アプリマニフェスト* (In a Stripe App, the app manifest is a stripe-app.json file in your app's root directory. It defines your app's ID, views, permissions, and other essential properties)に `https://www.example.com/api/users` connect-src URL を追加する場合は、次の fetch コールを使用できます。 ```js const makeRequestToService = (endpoint, requestData) => { return fetch(`https://www.example.com/api/${endpoint}/`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: requestData, }); }; ``` 1. ローカルの開発環境と本番環境で異なる*アプリマニフェスト* (In a Stripe App, the app manifest is a stripe-app.json file in your app's root directory. It defines your app's ID, views, permissions, and other essential properties)値を使用するには、[拡張マニフェストファイルを読み込みます](https://docs.stripe.com/stripe-apps/reference/app-manifest.md#extended-manifest)。 1. サードパーティー API に JavaScript クライアントライブラリがある場合には、`npm add` コマンドを使用してアプリに依存関係を追加できます。 ## アプリケーションをデバッグする アプリの開発中は、ブラウザーの開発者ツールのコンソールをデバッグツールとして使用できます。 アプリに関連するメッセージを分離するには、以下のようにします。 1. *アプリマニフェスト* (In a Stripe App, the app manifest is a stripe-app.json file in your app's root directory. It defines your app's ID, views, permissions, and other essential properties)でアプリ ID を見つけます。 1. 開発者ツールのブラウザーの**コンソール**パネルで、**絞り込み**ボックスに `[Stripe App ]` と入力します。`[Stripe App com.example.helloworld]` のように表示されます。 ## ビューのテストを記述する ビューのテストを作成することをお勧めします。単体テストにより、ビューが意図したとおりに動作することを検証できるだけでなく、今後のコード変更がより安全になります。 ビューを作成すると、末尾が `.test.tsx` のテストファイルにデフォルトのビューのテストが組み込まれます。 ```ts import {render, getMockContextProps} from "@stripe/ui-extension-sdk/testing"; import {ContextView} from "@stripe/ui-extension-sdk/ui"; import App from "./App"; describe("App", () => { it("renders ContextView", () => { const {wrapper} = render(); expect(wrapper.find(ContextView)).toContainText("save to reload this view"); }); }); ``` `npm run test` コマンドまたは `yarn test` コマンドで付属の [Jest](https://jestjs.io/) テストランナーを使用して、すべてのテストを実行できます。[Testing Library](https://testing-library.com/docs/react-testing-library/intro) や [Enzyme](https://enzymejs.github.io/enzyme) などの一般的な React テストツールを使用したことがある方には、`@stripe/ui-extension-sdk/testing` に含まれているテストパッケージの操作感はなじみのあるものです。 典型的なテストは次のように行われます。 - ビューを表示する。 - テキストの存在などの、初期状態に関するアサーションを行う。 - ビューと対話する。 - 新しいテキストの表示などの、新しい状態に関するアサーションを行う。 テストパッケージの手法と機能の詳細は、[UI テストのリファレンス](https://docs.stripe.com/stripe-apps/ui-testing.md)をご覧ください。 ## Optional: ビューを削除する プロジェクトのルートディレクトリーから、次のようにしてビューを削除できます。 ```bash stripe apps remove view VIEW_NAME ``` `VIEW_NAME` は、削除するビューの名前に置き換えてください。 ## See also - [UI コンポーネント](https://docs.stripe.com/stripe-apps/components.md) - [アプリの設定ページの追加](https://docs.stripe.com/stripe-apps/app-settings.md)