Skip to main content

Blog

kintoneのAPIプロキシーでFormデータを送信する方法

Posted over 2 years ago
この記事をシェア:

Stripe APIなど、外部のAPIに対して、JSONではなくFormデータを送信する方法を調べました。

Stripe APIをkintoneのApp Proxyから呼び出す

サンプルとして、Stripe APIを呼び出すラッパー関数を作ります。

async function callStripeAPI<Body = any, Result = any>(
  path: string,
  method: "GET" | "POST" | "PUT" | "DELETE",
  body?: Body
) {
  const apiResult = await new Promise<Result>((resolve, reject) => {
    kintone.plugin.app.proxy(
      PLUGIN_ID,
      `https://api.stripe.com/v1/${path}`,
      method,
      {
        "Content-Type": "application/x-www-form-urlencoded",
        "Authorization": "Bearer sk_test_xxx",
      },
      body || {},
      (response) => {
        const result = JSON.parse(response);
        resolve(result);
      },
      (e) => {
        console.log(e);
        reject(e);
      }
    );
  });
  return apiResult;
}

今回は簡略化のためにAPIキーを直接記述していますが、kintoneプラグインでは、Proxy Configを利用して安全にAPIキーを管理する仕組みが用意されています。

Qiitaに「kintoneプラグインのAPIプロキシー機能を使って、プラグインからStripe APIを呼び出す方法」として記事を公開していますので、実案件で試されたい方は、こちらもあわせてご確認ください。

Formデータは、URLSearchParamsで生成する

new FormData()も試したのですが、kintone.plugin.app.proxyでAPIを呼び出す場合、URLSearchParamsを使うのが良いみたいです。

    const recordData = kintone.app.record.get();
    const searchParams = new URLSearchParams("");
    searchParams.set("name", recordData.record.宛名.value);
    searchParams.set("description", "Created by kintone plugin");
    const customers = await callStripeAPI(
      "customers",
      "POST",
      searchParams.toString()
    );
    console.log(customers);
  });

Constructorでname-xxxのように文字列として設定しても良さそうですが、個人的な好みもあってsetで都度登録させています。

この書き方ならば、kintoneプラグイン経由でStripeとkintoneを連携させたりもできるようになります。

参考URLなど

Tools to Support Stripe Development

We provide helpful tools to extend the Stripe Dashboard and streamline development and testing.

View All Tools

Support This Project

If you find this content helpful, consider supporting the project through GitHub Sponsors. Your support helps maintain and improve these tools.