# Subscription Managment: Reader experience

Source: https://dev.arcxp.com/subscriptions/sales/learn/subscription-management-reader-experience/

Arc XP Sales provides a SDK package (and public APIs) to manage common activities performed by end-users (i.e. readers) when interacting with the site. This page will walk you through use cases using the SDK methods and/or Arc XP Sales public APIs.

The most important functionalities are provided through [Arc XP Identity Theme blocks](https://dev.arcxp.com/subscriptions/identity/configure/arc-xp-identity-themes-blocks-configuration-customization-deep-dive/) and Arc XP Sales Theme blocks, allowing many features to be used immediately with minimal configuration and without the need for additional development work.

> **Note:**
> 
> You can distinguish [public APIs](https://dev.arcxp.com/api/subscriptions-apis) because they contain a `/public/` as part of the endpoint. As we mention in [How-to Connect with Arc XP Sales SDKs and APIs on the web](https://dev.arcxp.com/subscriptions/sales/build/how-to-connect-with-sdks-and-apis/) the most of our SDK methods are wrapping calls to public APIs.
> 
> As part of some updates, Arc XP Sales streams relevant events via WebSocket, see [How-to listen Web Socket events and Implement IFX email service provider](https://dev.arcxp.com/subscriptions/identity/build/ifx-email-servic-provider-integration-and-websocket-events/) and [List of Web socket events](https://dev.arcxp.com/subscriptions/sales/learn/list-of-sales-events/) for additional details.

## Prerequisites

- Check the [How-to Connect with Arc XP Sales SDKs and APIs on the web](https://dev.arcxp.com/subscriptions/sales/build/how-to-connect-with-sdks-and-apis/) guide.
- Know the API Origin or CDN. The CDN endpoint has the following format:  
  - `https://[orgName]-[siteName]-[env].api.arc-cdn.net`

If you are using the SDK package, you will need to import the library on each file you are using it. All the methods will be found on the `Sales` object.

**Example**

```js
import Sales from '@arc-publishing/sdk-sales';
...
    await Sales.getConfig().then(config => {
          ...
    });
```

> **Note:**
> 
> Some actions such as `cancellation`, accept `reason` and/or `reason code`. The `reason` corresponds to additional information that can be entered by the end user, while the `reason code` corresponds to any of the reason code identifiers enabled on the Admin tool for the tenant. We don’t have a public API that returns the current list of enabled reason codes. You will need to grab the reason codes from the Admin and hardcode them.
> 
> Some `APIs` and `SDKs` methods should only be called by logged-in users. Make sure the user is logged in before making these calls. `Identity.isLoggedIn()` returns a boolean value indicating if the user is logged in or not. Internally, it checks if `Identity.userIdentity`, `Identity.userIdentity.accessToken`, or `Identity.userIdentity.refreshToken` exit. If none of these exist, the user is not logged in. if the access token is invalid, the system attempts to refresh it and retrieve a new one, then returns true from the method. By calling `Identity.isLoggedIn()` before call other methods you avoid unnecessary calls to our system, which can lead into unexpected errors.

## View tenant settings

There are a lot of configurations that can be customized per tenant (organization+site).

- reCAPTCHA settings checkout.

You may need to retrieve these settings from the site to enable flows and/or validations (e.g., show or hide the reCAPTCHA widget based on the tenant settings).

| SDK Method  | API                         |
| ----------- | --------------------------- |
| getConfig() | GET /sales/public/v1/config |

## Checkout Interaction

As described in [Checkout to purchase a subscription](https://dev.arcxp.com/subscriptions/sales/learn/checkout-to-purchase-a-subscription/), the interaction starts by adding items to the cart. You can retrieve the products an prices published in a live offer by calling the `GET retail/public/v1/offer/live/{campaignName}` endpoint. This call returns the SKU and priceCode, which are required when adding items into the cart.

If the user is logged In, a valid [access token](https://dev.arcxp.com/subscriptions/identity/build/connect-and-login-with-arc-xp-identity-sdks-and-apis/) (e.g., JWT) must be sent with subsequent calls.

### Add item to cart

An end-user can add one or multiple items to a cart. For each item, the SKU, priceCode and quantity are required.

| SDK Method      | API                             |
| --------------- | ------------------------------- |
| addItemToCart() | POST /sales/public/v1/cart/item |

By default, if the checkout (i.e. payment) is not completed within two hours, an [ABANDONED\_CART](https://dev.arcxp.com/subscriptions/sales/learn/list-of-sales-events/#abandoned-cart) event is dispatched. This allows you to send an email to the client reminding them of their pending purchase. However, this time period is configurable through the `abandon_cart_threshold` variable, which can be adjusted.

#### Additional cart interaction

Additional functions can be enabled to the end-user to provide additional interactions with the cart.

- `Clear the user's cart:` Removes all items from the user’s cart. If the user is not logged in then the anonid session cookie is expected by the API.
- `Get the current user's cart:` Gets the cart for the current user. If a cart does not exist, a new one will be created. If the user is not logged in, then a session cookie named anonid will be used for tracking the cart.
- `Remove one or more items from the user's cart:` Removes one or more items from the user’s cart. If the user is not logged in then the cart will be tracked via a session cookie named anonid.

| SDK Method           | API                                |
| -------------------- | ---------------------------------- |
| clearCart()          | DELETE /sales/public/v1/cart/clear |
| getCart()            | GET /sales/public/v1/cart          |
| removeItemFromCart() | DELETE /sales/public/v1/cart/{sku} |

### Get user’s stored addresses

End users usually use the same billing address for purchases. You can provide a list of all billing addresses used in previous orders.

| SDK Method     | API                                     |
| -------------- | --------------------------------------- |
| getAddresses() | GET /sales/public/v1/checkout/addresses |

### Create order

With at least one item in the cart, the end user can create an order. This call requires a billing address, which should be included in the request, as it is used to calculate [taxes](https://dev.arcxp.com/subscriptions/sales/configure/set-up-taxes-custom-taxes-and-external-integrations). This request returns a unique order number along with the order details.

This call may require a reCAPTCHA token if the reCAPTCHA is enabled for checkout.

| SDK Method                        | API                                  |
| --------------------------------- | ------------------------------------ |
| createOrder() or createNewOrder() | POST /sales/public/v1/checkout/order |

#### Additional order interaction

Additional functions can be enabled to the end-user to provide order(s) details. The following calls requires a valid access-token.

- `Retrieve details of one order:` When creating an order, if the request is successful, a unique order number will be returned. You will need to provide this order number if you need to retrieve the order details.
- `Retrieve paginated list of orders:` Retrieve paginated list of previous orders for signed-in user. List includes both orders created by the customer during checkout in addition to orders created during subscription renewals.

An order could have 2 different statuses: (1) Pending, (3) Paid. An order remains in a pending status during checkout if the payment has not been finalized for a created order.

| SDK Method        | API                                             |
| ----------------- | ----------------------------------------------- |
| getOrderDetails() | GET /sales/public/v1/order/detail/{orderNumber} |
| getOrderHistory() | GET /sales/public/v1/order/history              |

### Get list of available payment options

Once an order is created, the user needs to start the payment gateway interaction. To do this, the website will need to grab the list of all the [payment gateway options](https://dev.arcxp.com/subscriptions/sales/configure/payment-gateway-providers/) available for the tenant. Each payment type (i.e., IFX, Stripe Intents, Braintree, PayPal, … ) has their own [identifier](https://dev.arcxp.com/subscriptions/sales/configure/payment-gateway-providers/). Since a client could have multiple settings for the same payment gateway, each payment gateway has their own payment method id.

The `paymentMethodID` returned for each object from the call must be passed as `mid` in subsequet calls.

| SDK Method          | API                                           |
| ------------------- | --------------------------------------------- |
| getPaymentOptions() | GET /sales/public/v1/checkout/payment/options |

### Initialize payment

The `initializePayment()` function returns certain parameters. These paramenters are used either to redirect the user to an external site or to initialize an iframe or the SDKs provided by the payment gateway, enablig the end-user to enter their credit card information.

| SDK Method          | API                                                             |
| ------------------- | --------------------------------------------------------------- |
| initializePayment() | GET /sales/public/v1/checkout/order/{orderNumber}/payment/{mid} |

### Finalize payment

Once the end user has entered their credit card information and the payment gateway has successfully accepted the payment, a token is returned by the payment gateway. This token needs to be sent when calling `finalizePayment()`. If successful, it finalizes the interaction between Arc XP Subscriptions and the payment provider. This call may require a reCAPTCHA token if the reCAPTCHA is enabled for checkout.

| SDK Method        | API                                                             |
| ----------------- | --------------------------------------------------------------- |
| finalizePayment() | PUT /sales/public/v1/checkout/order/{orderNumber}/payment/{mid} |

If this call returns a sucessful response, a subscription is started for each product/price. Several WebSocket events are dispatched, such as [ORDER\_CONFIRMATION](https://dev.arcxp.com/subscriptions/sales/learn/list-of-sales-events/#order-confirmation) and [START\_SUBSCRIPTION](https://dev.arcxp.com/subscriptions/sales/learn/list-of-sales-events/#start-subscription).

It the checkout process was completed by an anonymous user, additional WebSocket events may be dispatched: [VERIFY\_EMAIL](https://dev.arcxp.com/subscriptions/identity/learn/list-of-identity-events/#email-verify-request), [EXPRESS\_CHECKOUT\_PASSWORD\_RESET\_REQUEST](https://dev.arcxp.com/subscriptions/identity/learn/list-of-identity-events/#express-checkout-password-reset-request), and [USER\_SIGN\_UP](https://dev.arcxp.com/subscriptions/identity/learn/list-of-identity-events/#user-sign-up).

## Subscriptions and management

Depending on the [subscription type](https://dev.arcxp.com/subscriptions/sales/learn/what-is-a-subscription/#subscription-types), different actions can be enabled to the user for each subscription.

### Subscription details

The following actions only can be done by a logged in end user.

- `Get all subscriptions:` This method returns all the subscriptions for the end user. Depending of their status, you can enable additional functionalities. For example, only active subscriptions can be canceled, and only canceled subscriptions can be rescued.
- `Get all active subscriptions: ` This method only returns the subscriptions on active status.
- `Get subscription details:` Given a subscription id, this method gets details of an individual subscription.

| SDK Method                  | API                                            |
| --------------------------- | ---------------------------------------------- |
| getAllSubscriptions()       | GET /sales/public/v1/subscription/all          |
| getAllActiveSubscriptions() | GET /sales/public/v1/subscription/allactive    |
| getSubscriptionDetails()    | PUT /sales/public/v1/subscription/{id}/details |

### Share subscription

This section explains the flow you need to implement on your website in case you want to enable the [share subscription](https://dev.arcxp.com/subscriptions/sales/learn/what-is-a-subscription/#shared) option.

**Prerequisites**

- The share subscription feature is available only for active subscriptions with products that have the `allow associate subscribers` option enabled.
- There are two end-users involved: the `subscription owner` and the `associate`. Both users must be logged into the system when performing the following actions.

**Methods involved**

- `Get subscription sharing details:` By providing a subscriptionID, this method returns: the number of shares allowed (`numSharesAllowed`) and an array with the shared subscription (`sharedSubscriptions`). If the `numSharesAllowed` is greather than zero, and the length of `sharedSubscriptions` is less than `numSharesAllowed`, the subscription owner can share the subscriptions with more members.
- `Share subscription:` If the subscription is eligible for sharing, the owner must pass the `subscriptionID` and the email of the user they want to share the subscription with. If the response is sucessfull, an [INVITE\_TO\_SHARE](https://dev.arcxp.com/subscriptions/sales/learn/list-of-sales-events/#share-subscription) event is dispatched. This event provides a `redeemCode`. The `redeemCode` must be sent to the potential associate via an [email service provider](https://dev.arcxp.com/subscriptions/identity/build/ifx-email-servic-provider-integration-and-websocket-events/). This should be shared as a link so that clicking it calls the `redeemAssociateInvitation()` method.
- `Redeem invitation to share a subscription:` Once the associate receives the `redeemCode` and clicks the link, the `redeemAssociateInvitation()` method is called. If the user is logged in and the `redeemCode` is valid, a shared subscription is started, and the user becomes an associate. An [START\_SUBSCRIPTION](https://dev.arcxp.com/subscriptions/sales/learn/list-of-sales-events/#start-subscription) event is dispatched.
- `Stop a shared subscription:` From `getSubscriptionSharingDetails()`, you can retrieve information about the associate subscribers. The subscription owner can terminate any associate’s subscription from their side.

| SDK Method                      | API                                              |
| ------------------------------- | ------------------------------------------------ |
| getSubscriptionSharingDetails() | PUT /sales/public/v1/subscription/{id}/sharing   |
| shareSubscription()             | PUT /sales/public/v1/subscription/{id}/share     |
| redeemAssociateInvitation()     | POST /sales/public/v1/subscription/redeem        |
| stopSharing()                   | PUT /sales/public/v1/subscription/{id}/stopshare |

### Gift subscription

This section explains the flow you need to implement on your website in case you want to sell [gift subscription](https://dev.arcxp.com/subscriptions/sales/learn/what-is-a-subscription/#gift).

**Prerequisites**

- The purchased price must be a [gift price](https://dev.arcxp.com/subscriptions/sales/configure/set-up-products-and-prices/#price-types).
- There are two end-users involved: the person who purchases the subscription, known as the `gift giver`, and the person who redeems and enjoys the subscription, known as the `gift redeemer`.

**Methods involved**

When the `gift giver` purchases a gift subscription, two events are dispatched [ORDER\_CONFIRMATION](https://dev.arcxp.com/subscriptions/sales/learn/list-of-sales-events/#order-confirmation) and [GIFT\_SUBSCRIPTION\_PURCHASE](https://dev.arcxp.com/subscriptions/sales/learn/list-of-sales-events/#gift-subscription-purchase). The gift giver must specify the gift redeemer (recipient), who will then need to redeem a code to activate the subscription.

You can identify an unredeemed gift subscription by calling `getAllSubscriptions()`. Those subscriptions with a single attribute with `key: GIFT_REDEEM_CODE` are unredeemed gift subscriptions. The `value` contains the `redeemCode` that needs to be shared with the redeemer.

- `Set recipient info on an unredeemed gift subscription:` This option should be available to the `gift giver` if the gift subscriptions has not yet been redeemed. If the subscription is eligible to gift, the owner must provide the `reedemCode` and the `recipient information` (e.g., email, name, note, sendNotificationOn). If the response is sucessful a [GIFT\_RECIPIENT\_SET](https://dev.arcxp.com/subscriptions/sales/learn/list-of-sales-events/#gift-recipient-set) event is disptached at `sendNotificationOn` time. The `redeemCode` must be sent to the `gift redeemer` via an [email service provider](https://dev.arcxp.com/subscriptions/identity/build/ifx-email-servic-provider-integration-and-websocket-events/). Share it as a link that, when clicked, calls the `redeemGiftSubscription()` method.
- `Redeem gift subscription:` Once the gift redeemer receives the `redeemCode` and clicks the link, the `redeemGiftSubscription()` method is called. If the user is logged in and the `redeemCode` is valid, a paid subscription is starteda and an [GIFT\_REDEEMED](https://dev.arcxp.com/subscriptions/sales/learn/list-of-sales-events/#gift-redeemed) event is dispatched.

| SDK Method               | API                                                 |
| ------------------------ | --------------------------------------------------- |
| setGiftRecipient()       | PUT /sales/public/v1/subscription/gift/{redeemCode} |
| redeemGiftSubscription() | POST /sales/public/v1/subscription/gift/redeem      |

### Enterprise subscription

Before the end-user can activate an enterprise subscription, previous developer API calls are required. For more details, refer to the [Subscription management: developer interface](https://dev.arcxp.com/api/subscriptions-apis) documentation.

Using the developer APIs, a `nonce` must be generated. This `nonce` is then shared with the end-user (who will activate the subscription) via an [email service provider](https://dev.arcxp.com/subscriptions/identity/build/ifx-email-servic-provider-integration-and-websocket-events/).

- `Redeem an enterprise subscription:` Once the end-user receives the `nonce` and clicks the link, the `redeemEnterpriseSubscription()` method is called. If the user is logged in and the `nonce` is valid, an enterprise subscription is started.

| SDK Method                     | API                                           |
| ------------------------------ | --------------------------------------------- |
| redeemEnterpriseSubscription() | PUT /sales/public/v2/subscriptions/enterprise |

### Group package based on domain

This section explains the flow you need to implement on your website if you want to enable the [Group packages based on domain](https://dev.arcxp.com/subscriptions/sales/learn/what-is-a-subscription/#group) option.

**Prerequisites**

- The group package must be created in the Admin tool. Once created, each group package based on domain will have an accessCode. If a logged-in user falls under the specified domain and uses this accessCode, they will gain access to the subscription.
- There are two types of users involved: Owner (the primary user who manages the group subscription and their associated) and members (additional users who can join the group subscription). Both, the owner and associates need to call specific methods to activate their subscriptions, and for this they will need to be logged in on the system.

**Methods involved**

When a group package based on domain is created via the Admin tool, a [CREATE\_EMAIL\_DOMAIN](https://dev.arcxp.com/subscriptions/sales/learn/list-of-sales-events/#create-email-domail) event is dispatched. This event contains the same `accessCode` provided through the Admin tool. This `accessCode` should be be shared to the owner and all the potential member subscribers via an [email service provider](https://dev.arcxp.com/subscriptions/identity/build/ifx-email-servic-provider-integration-and-websocket-events/). The email sent should contain a link, which when clicked calls `joinGroup()`. If successful a new group subscription is started on the end-user side, and a [START\_SUBSCRIPTION](https://dev.arcxp.com/subscriptions/sales/learn/list-of-sales-events/#start-subscription) event is dispatched for each call.

You can enable additional functionalities for end users, such as:

- `List Members:` Get all GroupSubEmailDomainMembers associated with owner and list.
- `List Domains:` Get all GroupSubEmailDomain associated by owner.
- `Manage Members`: Remove a member from a group subscription.

| SDK Method    | API                                                              |
| ------------- | ---------------------------------------------------------------- |
| joinGroup()   | POST /sales/public/v1/emailgroupsub/join                         |
| listMembers() | GET /sales/public/v1/emailgroupsub/{accessCode}/getAllMembers    |
| listGroups()  | GET /sales/public/v1/emailgroupsub/getAll                        |
| _NA_          | DELETE /sales/public/v1/emailgroupsub/{groupID}/{subscriptionID} |

### Cancel subscription

This option should be available only for paid subscriptions on activated status. This information can be retrieved from the call to `getAllSubscriptions()` and/or `getAllActiveSubscriptions()`.

A subscription can be cancelled by calling `cancelSubscription()`. You will need to pass the subscriptionID. `reason` and/or `reason code` are optional. If successful, a [CANCEL\_SUBSCRIPTION](https://dev.arcxp.com/subscriptions/sales/learn/list-of-sales-events/#cancel-subscription) event is dispatched, and the subscription status is changed from active to cancelled.

| SDK Method           | API                                           |
| -------------------- | --------------------------------------------- |
| cancelSubscription() | PUT /sales/public/v1/subscription/{id}/cancel |

### Rescue subscription

This option should be available only for paid subscriptions on cancelled status. This information can be retrieved from the call to `getAllSubscriptions()` and/or `getAllActiveSubscriptions()`.

A subscription can be rescued by calling `rescueSubscription()`. You will need to pass the subscriptionID. If successful, a [RESCUE\_SUBSCRIPTION](https://dev.arcxp.com/subscriptions/sales/learn/list-of-sales-events/#rescue-subscription) event is dispatched, and the subscription status is changed from cancelled to active.

| SDK Method           | API                                           |
| -------------------- | --------------------------------------------- |
| rescueSubscription() | PUT /sales/public/v1/subscription/{id}/rescue |

### Payment method update

A payment method update only can be done by a logged In user. This option only can be available for paid subscriptions whose status is different to terminated.

For the subscription who payment method wants to be updated, two parameteres are required: `{id}` and `{pid}`. The `{id}` corresponds to `paymentMethod.paymentMethodID`, which is returned from `getAllSubscriptions()`, `getAllActiveSubscriptions()` or `getSubscriptionDetails()`. The `{pid}` corresponds to the `paymentMethodID` returned during the call to `getPaymentOptions()`. The `{pid}` depends on the payment gateway(s) option you want to use during the update.

- `Initialize a payment method update:` Similar to [Initialize payment](#initialize-payment), this method returns certain parameters. These paramenters are used either to redirect the user to an external site or to initialize an iframe or the SDKs provided by the payment gateway, enablig the end-user to enter their credit card information.
- `Finalize a payment method update:` Once the end user has entered their credit card information and the payment gateway has successfully verified the payment method (to be use in upcoming renewals), a token is returned by the payment gateway. This token needs to be sent when calling `finalizePaymentUpdate()`. If successful, it finalizes the interaction between Arc XP Subscriptions and the payment provider. An [UPDATE\_PAYMENT\_METHOD](https://dev.arcxp.com/subscriptions/sales/learn/list-of-sales-events/#update-payment-method) event is dispatched. This call may require a reCAPTCHA token if the reCAPTCHA is enabled for checkout.

| SDK Method                | API                                                             |
| ------------------------- | --------------------------------------------------------------- |
| initializePaymentUpdate() | PUT /sales/public/v1/paymentmethod/{id}/provider/{pid}          |
| finalizePaymentUpdate()   | PUT /sales/public/v1/paymentmethod/{id}/provider/{pid}/finalize |

### Update a billing address

Updating a billing address can only be done by a logged-in user.

The billing address is used to calculate applicable taxes. End-users may want to update their billing address to ensure correct tax calculations during upcoming renewals. This option is available for paid subscriptions with a status other than `terminated`.

To update the billing address, the end-user will need to provide the new billing address and depending on the subscription to which the new billing address applies you will need to make sure a `subscriptionID` is included in the request. If the update is successful, and [UPDATE\_BILLING\_ADDRESS](https://dev.arcxp.com/subscriptions/sales/learn/list-of-sales-events/#update-billing-address) event is dispatched.

| SDK Method             | API                                       |
| ---------------------- | ----------------------------------------- |
| updateBillingAddress() | PUT /sales/public/v1/subscription/address |

### Change price for subscription

You can enable end users to upgrade or downgrade the price of active paid subscriptions.

Arc XP has two sets of API endpoints that enable that:

- **APIs that enable subscription upgrades, downgrades, and refunds**.  
To learn more, see [User-facing APIs for subscription upgrades, downgrades, and renewal adjustments](https://dev.arcxp.com/subscriptions/sales/configure/user-facing-apis-for-subscription-upgrades/).
- **APIs that enable subscription upgrades and downgrades with no refunds**.  
To learn more, see the following section.

**Prerequisites**

- The new price must be configured as [Eligible for subscriber initiated changes](https://dev.arcxp.com/subscriptions/sales/configure/set-up-products-and-prices/#create-price) and published in the system.

For a logged in user, with a `subscriptionId` and the `priceCode` of the new price to apply, you can provide a link that redirects the user into a page where the following steps are involved:

- `Initialize price update:` When the user lands on the page with the `subscriptionID` and the `priceCode` (i.e., `{id}` and `{pc}`, respectively) make a call to `GET /sales/public/v1/subscription/{id}/initializePriceUpdate/{pc}`. This api returns a `initializedId` along with additional information like refund amount, charge amount, tax amount, next renewal date (other relevant information).
- `Finalize price update:` If the user agrees with all the information provided on the previous step, complete the process by calling `PUT /sales/public/v1/subscription/{id}/finalizePriceUpdate/{initialiseId}`.

> **Note:**
> 
> After an upgrade is completed, `GET /sales/public/v1/subscription/{id}/initializePriceUpdate/{pc}` blocks another upgrade until the next billing cycle. This prevents incorrect charges.

Once the flow is completed, some webSockets events may be dispatched: [UPDATE\_SKU\_PRICECODE](https://dev.arcxp.com/subscriptions/sales/learn/list-of-sales-events/#update-sku-pricecode) (On subscription updated with new price, SKU), [REFUND\_PAYMENT](https://dev.arcxp.com/subscriptions/sales/learn/list-of-sales-events/#refund-subscription-payment) (For prorated refund for existing price), [RENEW\_SUBSCRIPTION](https://dev.arcxp.com/subscriptions/sales/learn/list-of-sales-events/#renew-subscription) (For prorated/full charge for new price)

| SDK Method | API                                                                       |
| ---------- | ------------------------------------------------------------------------- |
| _NA_       | GET /sales/public/v1/subscription/{id}/initializePriceUpdate/{pc}         |
| _NA_       | PUT /sales/public/v1/subscription/{id}/finalizePriceUpdate/{initialiseId} |
