Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions cron/daily/54-refresh-paypal-user-accounts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/**
* Daily CRON job to refresh PayPal user identity information for payees who have connected their
* PayPal accounts via OAuth. This ensures that hosts always see up-to-date account information
* (name, email, verification status) and helps detect disconnected or changed accounts.
*
* Accounts that were verified more than REFRESH_AFTER_DAYS days ago are refreshed.
* Accounts where the refresh fails (e.g., token revoked) are flagged by clearing `data.verified`.
*
* See: https://github.com/opencollective/opencollective/issues/8382
*/

import '../../server/env';

import moment from 'moment';
import { Op } from 'sequelize';

import logger from '../../server/lib/logger';
import { refreshPaypalUserAccount } from '../../server/lib/paypal';
import { HandlerType, reportErrorToSentry } from '../../server/lib/sentry';
import { ConnectedAccount } from '../../server/models';
import { runCronJob } from '../utils';

/** Refresh accounts that haven't been updated in this many days */
const REFRESH_AFTER_DAYS = Number(process.env.REFRESH_AFTER_DAYS) || 7;
const DRY_RUN = process.env.DRY_RUN === 'true';
const BATCH_SIZE = 50;

const run = async () => {
const cutoff = moment.utc().subtract(REFRESH_AFTER_DAYS, 'days').toDate();

// Find user-level PayPal ConnectedAccounts (those without a clientId are user-level, not host-level)
const accounts = await ConnectedAccount.findAll({
where: {
service: 'paypal',
clientId: null,
refreshToken: { [Op.not]: null },
updatedAt: { [Op.lt]: cutoff },
},
order: [['updatedAt', 'ASC']],
limit: BATCH_SIZE,
});

logger.info(
`Found ${accounts.length} PayPal user ConnectedAccount(s) due for refresh (last updated before ${cutoff.toISOString()})`,
);

if (DRY_RUN) {
logger.info('[DRY_RUN] Would refresh the above accounts. Exiting.');
return;
}

let refreshed = 0;
let failed = 0;

for (const account of accounts) {
try {
const result = await refreshPaypalUserAccount(account);
if (result) {
refreshed++;
logger.debug(`Refreshed PayPal ConnectedAccount #${account.id} (Collective #${account.CollectiveId})`);
} else {
failed++;
// refreshPaypalUserAccount returned null — mark as not verified so the payee is prompted to reconnect
await account.update({
data: {
...account.data,
verified: false,
refreshFailedAt: new Date().toISOString(),
},
});
logger.warn(
`Failed to refresh PayPal ConnectedAccount #${account.id} (Collective #${account.CollectiveId}) — marked as unverified`,
);
}
} catch (err) {
failed++;
logger.error(`Error refreshing PayPal ConnectedAccount #${account.id}: ${err.message}`);
reportErrorToSentry(err, {
handler: HandlerType.CRON,
extra: { connectedAccountId: account.id, collectiveId: account.CollectiveId },
});
}
}

logger.info(
`PayPal user account refresh complete: ${refreshed} refreshed, ${failed} failed out of ${accounts.length} accounts`,
);
};

if (require.main === module) {
runCronJob('refresh-paypal-user-accounts', run, 24 * 60 * 60);
}
41 changes: 41 additions & 0 deletions server/lib/paypal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -388,3 +388,44 @@
}

export { paypal };

/**
* Refresh a payee's PayPal user ConnectedAccount using the stored refresh token.
* Updates the access token, refresh token, and re-fetches identity information from PayPal.
* Returns the updated ConnectedAccount, or null if the refresh failed (e.g. account was disconnected).
*/
export const refreshPaypalUserAccount = async (
connectedAccount: ConnectedAccount,
): Promise<ConnectedAccount | null> => {
const { refreshPaypalUserToken, retrievePaypalUserInfo } = await import('../paymentProviders/paypal/api');

Check failure on line 400 in server/lib/paypal.ts

View workflow job for this annotation

GitHub Actions / typescript

Property 'retrievePaypalUserInfo' does not exist on type 'typeof import("/home/runner/work/opencollective-api/opencollective-api/server/paymentProviders/paypal/api")'.

Check failure on line 400 in server/lib/paypal.ts

View workflow job for this annotation

GitHub Actions / typescript

Property 'refreshPaypalUserToken' does not exist on type 'typeof import("/home/runner/work/opencollective-api/opencollective-api/server/paymentProviders/paypal/api")'.

const storedRefreshToken = connectedAccount.refreshToken;
if (!storedRefreshToken) {
logger.warn(`refreshPaypalUserAccount: ConnectedAccount #${connectedAccount.id} has no refresh token — skipping`);
return null;
}

try {
const tokenResult = await refreshPaypalUserToken(storedRefreshToken);
const userInfo = await retrievePaypalUserInfo(tokenResult.access_token);

await connectedAccount.update({
token: tokenResult.access_token,
refreshToken: tokenResult.refresh_token,
username: userInfo.email,
data: {
...connectedAccount.data,
payerId: userInfo.user_id,
verified: userInfo.verified_account,
name: userInfo.name,
email: userInfo.email,
verifiedAt: new Date().toISOString(),
},
});

return connectedAccount;
} catch (e) {
logger.error(`refreshPaypalUserAccount: failed to refresh ConnectedAccount #${connectedAccount.id} — ${e.message}`);
return null;
}
};
Loading