Executing Actions
Overview
Actions are a core component of the Manage product. They enable users to cancel, pause, or modify their plans—such as switching to a different tier or adjusting plan terms. Fetching updated data from a Company is also treated as an Action.
This guide walks you through determining what Actions are available, choosing an Action, and executing that Action on a user’s behalf. It assumes you’ve already configured the Transact SDK.
With Continuous Access, some Actions can also be executed with an API request, without the user needing to be present. See Execute via the API.
Discovering Actions
The first step in executing Actions is determining which Actions are available. How you look up available Actions varies based on your use-case. For example, if the user has already connected some Accounts or Atomic has detected recurring transactions from a user’s financial data, you can see available Actions on the Account data itself.
This section demonstrates the different approaches you can take to look up available Actions.
Account Actions
Support for specific Actions can depend on the current state of a user’s Account. For example, an Account that is already pending cancellation cannot be cancelled again, or a Company may support pausing a plan for some Accounts but not for others.
As such, Atomic maintains lists of usable Actions for Accounts and Account Expenses as fields on the Account object returned in the Get Accounts endpoint. These Actions can be retrieved like this:
const response = await fetch(`${API_URL}/pay-link/accounts`, {
headers: AUTH_HEADERS,
});
const { accounts } = await response.json();
for (const account of accounts) {
console.log(account.company.name);
for (const expense of account.expenses) {
console.log(expense.actions);
}
}
Netflix
[
{
actionId: '[ENCODED_ACTION_ID]',
type: 'view-account',
automated: false,
disabled: false,
canInitViaApi: false,
bill: {
_id: '6a0b5fbcf0ae055e029fa4b4',
name: 'Netflix',
companyId: '683f33dfc429f86375c21c98',
}
},
{
actionId: '[ENCODED_ACTION_ID]',
type: 'refresh',
automated: true,
disabled: false,
canInitViaApi: true,
bill: {
_id: '6a0b5fbcf0ae055e029fa4b4',
name: 'Netflix',
companyId: '683f33dfc429f86375c21c98',
}
},
{
actionId: '[ENCODED_ACTION_ID]',
type: 'change-plan',
automated: false,
disabled: false,
canInitViaApi: false,
bill: {
_id: '6a0b5fbcf0ae055e029fa4b4',
name: 'Netflix',
companyId: '683f33dfc429f86375c21c98',
}
},
{
actionId: '[ENCODED_ACTION_ID]',
type: 'pause-plan',
automated: true,
disabled: false,
canInitViaApi: true,
bill: {
_id: '6a0b5fbcf0ae055e029fa4b4',
name: 'Netflix',
companyId: '683f33dfc429f86375c21c98',
}
},
{
actionId: '[ENCODED_ACTION_ID]',
type: 'cancel-plan',
automated: true,
disabled: false,
canInitViaApi: true,
bill: {
_id: '6a0b5fbcf0ae055e029fa4b4',
name: 'Netflix',
companyId: '683f33dfc429f86375c21c98',
}
}
]
Expense-level Actions are most commonly used (and include Account-level Actions). However, there are cases where Expenses are unavailable (such as an Apple Account that has no recurring subscriptions). In such cases, you can look up available Actions using account.actions.
Suggestion ActionsBeta
Suggestions highlight Actions the user is more likely to take. By analyzing the user's Accounts and transactions, the Suggestion Engine generates insights and ties them to Actions that can be presented to the user as a simple CTA. For example, the user is more likely to want to cancel a subscription they haven’t used in a long time.
Suggestions can be retrieved in one of two ways. First, Suggestions for connected Accounts are included as a field on the Account object returned in the Get Accounts endpoint. Second, all Suggestions, whether for a specific Account or more general (based on common savings opportunities), are available in the dedicated Get Suggestions endpoint. These Suggestions and the Actions associated with them can be retrieved like this:
const response = await fetch(`${API_URL}/pay-link/suggestions`, {
headers: AUTH_HEADERS,
});
const { suggestions } = await response.json();
for (const suggestion of suggestions) {
console.log(suggestion.references[0].company.name);
console.log(suggestion.action);
}
Netflix
{
actionId: '[ENCODED_ACTION_ID]',
type: 'change-plan',
automated: false,
disabled: false,
canInitViaApi: false,
bill: {
_id: '6a0b5fbcf0ae055e029fa4b4',
name: 'Netflix',
companyId: '683f33dfc429f86375c21c98',
}
}
Apple
{
actionId: '[ENCODED_ACTION_ID]',
type: 'connect-account',
automated: true,
disabled: false,
canInitViaApi: false
}
Company Actions
Sometimes, instead of starting with a connected Account or a Suggestion, you may want to look up available Actions based on a Company. For example, you may want to show the user what Actions are available for Spotify, regardless of whether the user has connected a Spotify Account.
To look up Actions for a Company, look up the id for that Company, then make a request to the Actions for Company endpoint, like this:
const companyResponse = await fetch(`${API_URL}/company/search`, {
headers: {
...AUTH_HEADERS,
"content-type": "application/json",
},
method: "POST",
body: JSON.stringify({
query: "Spotify",
scopes: ["pay-link"],
}),
});
const companyResult = await companyResponse.json();
const company = companyResult.data[0];
const response = await fetch(
`${API_URL}/pay-link/actions-for-company/${company._id}`,
{
headers: AUTH_HEADERS,
},
);
const { actions } = await response.json();
console.log(company.name);
console.log(actions);
Spotify
[
{
actionId: '[ENCODED_ACTION_ID]',
type: 'connect-account',
automated: true,
disabled: false,
canInitViaApi: false
},
{
actionId: '[ENCODED_ACTION_ID]',
type: 'cancel-plan',
automated: true,
disabled: false,
canInitViaApi: false
},
{
actionId: '[ENCODED_ACTION_ID]',
type: 'pause-plan',
automated: true,
disabled: false,
canInitViaApi: false
},
{
actionId: '[ENCODED_ACTION_ID]',
type: 'switch',
automated: true,
disabled: false,
canInitViaApi: false
}
]
Choosing an Action
Once you have retrieved available Actions, you must determine which Action to execute. There are two general approaches to making this determination: user-driven (in which you display available Actions directly to the user) and algorithm-driven (in which the user doesn't directly interface with a list of Actions).
User-Driven Choice
Patterns for user-driven Action selection may vary, but some common cases include:
- An Account or Expense detail view that includes a series of CTA buttons for the available Actions.
- A carousel of all available Suggestions, with a CTA button for each associated Action.
- A calendar view that shows when upcoming Expenses are due, in which choosing an Expense displays CTA buttons for the available Actions.
Algorithm-Driven Choice
It is typically preferable to allow the user to directly select an available Action, but there are cases in which an algorithm-driven choice may be needed. Some examples may include:
- Bulk cancellation based on a search algorithm, such as "streaming services that haven't been used in more than 30 days."
- A chatbot matching the user's queries to one or more available Actions.
- An algorithm that pauses subscriptions on a set schedule.
Taking an Action
Launch the Transact SDK
To execute an Action, use the actionId field in the relevant Action returned from the API. Call the transact exported by the Transact SDK, using the actionId as a parameter.
let config = AtomicConfig(
scope: .payLink,
publicToken: "PUBLIC_TOKEN",
tasks: [
.action(id: actionId)
]
)
Atomic.presentTransact(
from: self,
config: config,
onLaunch: {
print("Launched")
},
onCompletion: { response in
print("Completed with Response: \(response)")
},
onError: { error in
print("Transact Error: \(error)")
})
) The user experience at this point will depend on whether the Action is automated.
Since manual Actions require a user to make a selection or choice (such as selecting a new plan), Atomic will open a webview directly to the relevant webpage for that user. After making that choice, they can exit the webview and Atomic will execute a refresh Action in the background to sync upstream changes to the Account.
Automated Actions happen without user intervention, unless the user needs to authenticate or provide an MFA. Atomic will display a special view in the Transact SDK that lets the user know the Action is ongoing. It can also prompt for authentication or an MFA step if needed.
Since automated Actions can be run in the background, in many cases users may leave during the execution of the Action.
Refresh Actions are always automated, and typically happen in the background.
Actions can also be initiated before a user has connected the associated account. In that case, when the Action is launched, the Transact SDK will first prompt the user to authenticate with the merchant. Once the account is linked, Atomic will proceed with executing the requested Action without requiring a separate connection step.
Execute via the API
With Continuous Access, you can execute some Actions with an API request, without the user needing to be present. Send the Action’s actionId to the Execute Action endpoint.
Continuous Access must be enabled for your account. Contact your implementation manager.
Before you send the request, check two fields:
canInitViaApion the Action istrue. Onlyrefresh,cancel-plan, andpause-planActions support this, and only when the Company supports Continuous Access and the Account has an active Continuous Access session. If it isfalse, launch the Action with Transact.processingon the Account isfalse. If it istrue, wait until the Account finishes processing.
canInitViaApi reflects conditions when Atomic generated the Action, and those conditions can change. Fetch the Account’s Actions right before you execute one.
if (account.processing) {
// Wait until the Account finishes processing, then refetch its Actions.
} else if (!action.canInitViaApi) {
// Launch the Action with Transact.
} else {
const response = await fetch(`${API_URL}/pay-link/execute-action`, {
method: 'POST',
headers: { ...AUTH_HEADERS, 'Content-Type': 'application/json' },
body: JSON.stringify({ actionId: action.actionId }),
});
if (response.ok) {
const { data } = await response.json();
// Use data.tasks to know which tasks were created for this action
// and you'll be receiving task-status-updated webhooks for progress updates.
} else if (response.status === 409) {
// The Account is already processing. Wait, then refetch its Actions.
} else if (response.status === 429 || response.status >= 500) {
// Try again later.
} else {
// Launch the Action with Transact.
}
}
A successful request returns the accountId, the Task Workflow, and the Tasks created for the Action. One Action can create more than one Task. Save each Task _id to match it against task-status-updated webhooks.
If the request fails:
409: the Account is already processing an Action. Wait untilprocessingisfalse, then refetch the Account’s Actions. Execute the Action only if it is still listed withcanInitViaApiset totrue. The Task that was processing may have been this same Action.429or5xx: try again later.- Any other error: let the user know the Action did not complete. You can then offer to launch the Action with Transact. Transact requires the user, so if they are not in your app, you can prompt them the next time they open it. If the error keeps happening, contact Atomic support with the response.
If the Task’s failure reason is auth-expired, the merchant requires the user to authenticate again. Launch the Action with Transact so the user can reconnect the Account and the Action can complete.
Show Progress in Your UI
Since Actions and subsequent refreshes can occur in the background, we recommend using your UI to let users know when they are in progress. This can reduce confusion, as users may re-attempt Actions if they're not sure they worked.
To do so, use the onLaunch, onFinish, onClose, and onTaskStatusUpdate callbacks in the transact function.
onLaunchfires when the Transact SDK presents the Action to the user. Use this to set in-progress UI state, such as disabling the originating CTA or displaying a loading indicator while the Action runs.onFinishfires when the Action completes successfully and the user dismisses Transact. The event payload includes anactionobject with theaccountIdof the affected Account and thetypeof Action that was executed. Useaction.accountIdto correlate the event with a specific Account in your system and trigger a refetch from theGET /pay-link/accountsendpoint. SeeonFinishfor the full payload.onClosefires when the user exits Transact before reaching the success screen, including when an automated Action is left running in the background. The event payload includes areason(for example,task-pendingwhen the user opts to exit while the Action is still processing) along with anactionobject containing theaccountIdof the affected Account and thetypeof Action that was being executed. Useaction.accountIdto correlate the event with a specific Account in your system. SeeonClosefor the full list of reasons.onTaskStatusUpdatefires whenever the underlying Task transitions state, and is the callback to listen to when you need to detect a failed Action. The event payload includes astatusofprocessing,completed, orfailed, anactionTypeidentifying which Action the update applies to, and afailReasonon failure. Use this to surface error UI when an Action does not succeed. SeeonTaskStatusUpdatefor the full payload.
Actions executed via the API do not fire Transact callbacks. Use the Account’s processing field to show that an Action is in progress, and block new Actions on that Account, from the user and from your own automation, until it is false. Follow each Task with task-status-updated webhooks or Get Task Status. Listen for pay-link-accounts-updated to know when the Account has finished processing.
Handle Cancellation Results
A cancel-plan Action ends completed or failed. Completed means the plan is cancelled or pending cancellation at the merchant, including a plan that was already cancelled before the Action ran. The user often keeps access until the end of the billing period. A pending cancellation shows as an active plan with a pendingChange; its start date is when access ends.
A failed cancel carries a reason in failReason on onTaskStatusUpdate and in data.reason on the task-status-updated webhook. After most failures Atomic refreshes the Account, so its plans are current by the time you check them. These are the reasons a cancel can fail with. Treat any other reason as unknown-failure.
user-abandon: The user did not finish a step the Task needed, usually signing in again. Offer to try again.auth-expired: The user's session with the merchant is no longer valid. Ask the user to sign in again, then retry.device-disconnected: The device running the Task disconnected before it finished. Offer to try again.action-failed: The merchant did not confirm the cancel, or a follow-up read showed the plan still active. Check the plan after the refresh. If it is still active, retry with the user's confirmation.unexpected-response: Atomic could not interpret the merchant's response. Atomic may need to update the integration. Check the plan after the refresh. If it is still active, escalate rather than retry.subscription-not-found: The merchant has no matching subscription on the account. Check the plans after the refresh. If the plan is gone, there is nothing to cancel.plan-selection-required: The cancel could not be matched to a specific subscription, either because none was specified and the account has more than one, or because the merchant requires a specific plan. Refresh the account, then re-issue the cancel against the plan the user selects.subscription-inactive: The subscription is not active at the merchant. Check the plan after the refresh and tell the user it is not billing.subscription-managed-by-partner-provider: A partner such as Apple or Google Play bills the subscription. The partner is named inmanagedBy. Tell the user to cancel with the partner.product-not-supported: The merchant does not allow this user to cancel this plan, for example a member of a family plan. Tell the user to cancel with the merchant or the plan owner.system-unavailable: The merchant was unavailable, so the cancel was not sent. Offer to try again later.connection-error: The connection to the merchant dropped before a response came back. Refresh the account and check the plan before retrying. The cancel may have gone through.unknown-failure: The Task failed for a reason Atomic could not classify. Refresh the account and check the plan before retrying. Escalate if it recurs.
Update Your Data
Since Actions often change the state of the Account, you will want to refetch any Account data upon their completion.
Atomic runs a refresh after any Action that changes the Account, to capture the change. The refresh sends its own task-status-updated webhooks, and once it reaches completed, GET /pay-link/accounts returns the updated data.
You can use webhooks, polling, or client-side events to wait for updates to complete in the Atomic system, and then retrieve the data from the GET /pay-link/accounts endpoint.
You can also listen directly for updates using the pay-link-accounts-updated webhook.
For more in depth discussion of the options for retrieving data, review the relevant guide.