0

Capture authorized payment on subscription

by
Published Apr 8, 2025

Captures an authorized payment from the subscriber on the subscription.

Script paypal Verified

The script

Submitted by hugo697 Bun
Verified 427 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
/**
27
 * Capture authorized payment on subscription
28
 * Captures an authorized payment from the subscriber on the subscription.
29
 */
30
export async function main(
31
  auth: Paypal,
32
  id: string,
33
  PayPal_Request_Id: string,
34
  body: {
35
    note: string;
36
    capture_type: "OUTSTANDING_BALANCE";
37
    amount: { currency_code: string; value: string };
38
  }
39
) {
40
  const token = await getToken(auth);
41
  const url = new URL(
42
    `https://api-m.paypal.com/v1/billing/subscriptions/${id}/capture`
43
  );
44

45
  const response = await fetch(url, {
46
    method: "POST",
47
    headers: {
48
      "PayPal-Request-Id": PayPal_Request_Id,
49
      "Content-Type": "application/json",
50
      Authorization: "Bearer " + token,
51
    },
52
    body: JSON.stringify(body),
53
  });
54
  if (!response.ok) {
55
    const text = await response.text();
56
    throw new Error(`${response.status} ${text}`);
57
  }
58
  return await response.json();
59
}
60