0

List all payment tokens

by
Published Apr 8, 2025

Returns all payment tokens for a customer.

Script paypal Verified

The script

Submitted by hugo697 Bun
Verified 428 days ago
1
//native
2
type Paypal = {
3
  clientId: string;
4
  clientSecret: string;
5
};
6

7
async function getToken(auth: Paypal): Promise<string> {
8
  const url = new URL(`https://api-m.paypal.com/v1/oauth2/token`);
9
  const response = await fetch(url, {
10
    method: "POST",
11
    headers: {
12
      Authorization: `Basic ${btoa(`${auth.clientId}:${auth.clientSecret}`)}`,
13
    },
14
    body: new URLSearchParams({
15
      grant_type: "client_credentials",
16
    }),
17
  });
18
  if (!response.ok) {
19
    const text = await response.text();
20
    throw new Error(`Could not get token: ${response.status} ${text}`);
21
  }
22
  const json = await response.json();
23
  return json.access_token;
24
}
25
/**
26
 * List all payment tokens
27
 * Returns all payment tokens for a customer.
28
 */
29
export async function main(
30
  auth: Paypal,
31
  customer_id: string | undefined,
32
  page_size: string | undefined,
33
  page: string | undefined,
34
  total_required: string | undefined,
35
) {
36
  const token = await getToken(auth);
37
  const url = new URL(
38
    `https://api-m.paypal.com/v3/vault/payment-tokens`,
39
  );
40
  for (const [k, v] of [
41
    ["customer_id", customer_id],
42
    ["page_size", page_size],
43
    ["page", page],
44
    ["total_required", total_required],
45
  ]) {
46
    if (v !== undefined && v !== "" && k !== undefined) {
47
      url.searchParams.append(k, v);
48
    }
49
  }
50
  const response = await fetch(url, {
51
    method: "GET",
52
    headers: {
53
      Authorization: "Bearer " + token,
54
    },
55
    body: undefined,
56
  });
57
  if (!response.ok) {
58
    const text = await response.text();
59
    throw new Error(`${response.status} ${text}`);
60
  }
61
  return await response.json();
62
}
63