0

Capture authorized payment

by
Published Apr 8, 2025

Captures an authorized payment, by ID.

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
 * Capture authorized payment
27
 * Captures an authorized payment, by ID.
28
 */
29
export async function main(
30
  auth: Paypal,
31
  authorization_id: string,
32
  PayPal_Request_Id: string,
33
  Prefer: string,
34
  body: { invoice_id?: string; note_to_payer?: string } & {
35
    amount?: { currency_code: string; value: string };
36
    invoice_id?: string;
37
    final_capture?: false | true;
38
    payment_instruction?: {
39
      platform_fees?: {
40
        amount: { currency_code: string; value: string };
41
        payee?: { email_address?: string; merchant_id?: string };
42
      }[];
43
      disbursement_mode?: "INSTANT" | "DELAYED";
44
      payee_pricing_tier_id?: string;
45
      payee_receivable_fx_rate_id?: string;
46
    };
47
    note_to_payer?: string;
48
    soft_descriptor?: string;
49
  },
50
) {
51
  const token = await getToken(auth);
52
  const url = new URL(
53
    `https://api-m.paypal.com/v2/payments/authorizations/${authorization_id}/capture`,
54
  );
55

56
  const response = await fetch(url, {
57
    method: "POST",
58
    headers: {
59
      "PayPal-Request-Id": PayPal_Request_Id,
60
      Prefer: Prefer,
61
      "Content-Type": "application/json",
62
      Authorization: "Bearer " + token,
63
    },
64
    body: JSON.stringify(body),
65
  });
66
  if (!response.ok) {
67
    const text = await response.text();
68
    throw new Error(`${response.status} ${text}`);
69
  }
70
  return await response.json();
71
}
72