0

Reauthorize authorized payment

by
Published Apr 8, 2025

Reauthorizes an authorized PayPal account payment, by ID.

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
 * Reauthorize authorized payment
27
 * Reauthorizes an authorized PayPal account 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: { amount?: { currency_code: string; value: string } },
35
) {
36
  const token = await getToken(auth);
37
  const url = new URL(
38
    `https://api-m.paypal.com/v2/payments/authorizations/${authorization_id}/reauthorize`,
39
  );
40

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