0

Post transfers

by
Published Oct 30, 2023

To send funds from your Stripe account to a connected account, you create a new transfer object. Your Stripe balance must be able to cover the transfer amount, or you’ll receive an “Insufficient Funds” error.

Script stripe Verified

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 398 days ago
1
type Stripe = {
2
  token: string;
3
};
4
/**
5
 * Post transfers
6
 * To send funds from your Stripe account to a connected account, you create a new transfer object. Your Stripe balance must be able to cover the transfer amount, or you’ll receive an “Insufficient Funds” error.
7
 */
8
export async function main(
9
  auth: Stripe,
10
  body: {
11
    amount?: number;
12
    currency: string;
13
    description?: string;
14
    destination: string;
15
    expand?: string[];
16
    metadata?: { [k: string]: string };
17
    source_transaction?: string;
18
    source_type?: "bank_account" | "card" | "fpx";
19
    transfer_group?: string;
20
  }
21
) {
22
  const url = new URL(`https://api.stripe.com/v1/transfers`);
23

24
  const response = await fetch(url, {
25
    method: "POST",
26
    headers: {
27
      "Content-Type": "application/x-www-form-urlencoded",
28
      Authorization: "Bearer " + auth.token,
29
    },
30
    body: encodeParams(body),
31
  });
32
  if (!response.ok) {
33
    const text = await response.text();
34
    throw new Error(`${response.status} ${text}`);
35
  }
36
  return await response.json();
37
}
38

39
function encodeParams(o: any) {
40
  function iter(o: any, path: string) {
41
    if (Array.isArray(o)) {
42
      o.forEach(function (a) {
43
        iter(a, path + "[]");
44
      });
45
      return;
46
    }
47
    if (o !== null && typeof o === "object") {
48
      Object.keys(o).forEach(function (k) {
49
        iter(o[k], path + "[" + k + "]");
50
      });
51
      return;
52
    }
53
    data.push(path + "=" + o);
54
  }
55
  const data: string[] = [];
56
  Object.keys(o).forEach(function (k) {
57
    if (o[k] !== undefined) {
58
      iter(o[k], k);
59
    }
60
  });
61
  return new URLSearchParams(data.join("&"));
62
}
63