@adapty/capacitor - v3.12.0-beta.1
    Preparing search index...

    Class Adapty

    Entry point for the Adapty SDK.

    This is the main Adapty class, excluding UI rendering functionality.

    Implements

    • AdaptyPlugin
    Index

    Constructors

    Properties

    addListener: AddListenerFn = ...

    Adds an event listener for SDK events.

    You can listen to various events from the Adapty SDK such as profile updates. The listener will be called whenever the corresponding event occurs.

    The name of the event to listen to.

    The function to call when the event occurs.

    A listener handle that can be used to remove the listener.

    Listen to profile updates

    import { adapty } from '@adapty/capacitor';

    const listener = adapty.addListener('onLatestProfileLoad', (profile) => {
    console.log('Profile updated:', profile);
    const isSubscribed = profile.accessLevels['YOUR_ACCESS_LEVEL']?.isActive;
    if (isSubscribed) {
    console.log('User has premium access');
    }
    });

    // Later, remove the listener
    listener.remove();

    Methods

    • Initializes the Adapty SDK.

      Parameters

      Returns Promise<void>

      A promise that resolves when the SDK is activated.

      This method must be called in order for the SDK to work. It is preferred to call it as early as possible in the app lifecycle, so background activities can be performed and cache can be updated.

      
      

      Usage with your user identifier from your system

      await adapty.activate({
      apiKey: 'YOUR_PUBLIC_SDK_KEY',
      params: {
      customerUserId: 'YOUR_USER_ID'
      }
      });

      Error if the SDK is already activated or if the API key is invalid.

    • Creates a URL for a web paywall.

      Parameters

      Returns Promise<string>

      A promise that resolves with the web paywall URL.

      This method generates a URL that can be used to open a web version of the paywall. You can use this URL in a custom web view or a browser.

      Error if an error occurs while creating the URL.

      import { adapty } from '@adapty/capacitor';

      try {
      const paywall = await adapty.getPaywall({ placementId: 'YOUR_PLACEMENT_ID' });
      const url = await adapty.createWebPaywallUrl({ paywallOrProduct: paywall });
      console.log('Web paywall URL:', url);
      } catch (error) {
      console.error('Failed to create web paywall URL:', error);
      }
    • Gets the current installation status.

      Returns Promise<AdaptyInstallationStatus>

      A promise that resolves with the installation status.

      Installation status provides information about when the app was installed, how many times it has been launched, and other installation-related details. The status can be "not_available", "not_determined", or "determined" with details.

      Error if an error occurs while retrieving the installation status.

      import { adapty } from '@adapty/capacitor';

      try {
      const status = await adapty.getCurrentInstallationStatus();
      if (status.status === 'determined') {
      console.log('Install time:', status.details.installTime);
      console.log('Launch count:', status.details.appLaunchCount);
      }
      } catch (error) {
      console.error('Failed to get installation status:', error);
      }
    • Fetches the onboarding by the specified placement.

      Parameters

      • options: GetOnboardingOptions

        The options for fetching the onboarding

        • placementId

          The identifier of the desired placement.

        • locale

          Optional. The identifier of the onboarding localization. Default: 'en'.

        • params

          Optional. Additional parameters for fetching the onboarding.

      Returns Promise<AdaptyOnboarding>

      A promise that resolves with the requested AdaptyOnboarding.

      When you create an onboarding with the no-code builder, it's stored as a container with configuration that your app needs to fetch and display. This container manages the entire experience - what content appears, how it's presented, and how user interactions are processed.

      Error if the onboarding with the specified ID is not found.

      import { adapty } from '@adapty/capacitor';

      try {
      const onboarding = await adapty.getOnboarding({
      placementId: 'YOUR_PLACEMENT_ID',
      locale: 'en',
      params: {
      fetchPolicy: 'reload_revalidating_cache_data',
      loadTimeoutMs: 5000
      }
      });
      console.log('Onboarding fetched successfully');
      } catch (error) {
      console.error('Failed to fetch onboarding:', error);
      }
    • Fetches the onboarding of the specified placement for the All Users audience.

      Parameters

      • options: GetOnboardingForDefaultAudienceOptions

        The options for fetching the onboarding

        • placementId

          The identifier of the desired placement.

        • locale

          Optional. The identifier of the onboarding localization. Default: 'en'.

        • params

          Optional. Additional parameters for fetching the onboarding.

      Returns Promise<AdaptyOnboarding>

      A promise that resolves with the requested AdaptyOnboarding.

      It's crucial to understand that the recommended approach is to fetch the onboarding by the getOnboarding method. The getOnboardingForDefaultAudience method should be used only if faster fetching outweighs the drawbacks:

      • Potential backward compatibility issues
      • Loss of personalization (no targeting based on country, attribution, or custom attributes)

      Error if the onboarding with the specified ID is not found.

      import { adapty } from '@adapty/capacitor';

      try {
      const onboarding = await adapty.getOnboardingForDefaultAudience({
      placementId: 'YOUR_PLACEMENT_ID',
      locale: 'en',
      });
      } catch (error) {
      console.error('Failed to fetch onboarding:', error);
      }
    • Fetches the paywall by the specified placement.

      Parameters

      • options: GetPaywallOptions

        The options for fetching the paywall

        • placementId

          The identifier of the desired placement. This is the value you specified when creating a placement in the Adapty Dashboard.

        • locale

          Optional. The identifier of the paywall localization. Default: 'en'. See Localizations and locale codes for more information.

        • params

          Optional. Additional parameters for fetching the paywall, including fetch policy and load timeout.

      Returns Promise<AdaptyPaywall>

      A promise that resolves with the requested AdaptyPaywall.

      With Adapty, you can remotely configure the products and offers in your app by simply adding them to paywalls – no need for hardcoding them. The only thing you hardcode is the placement ID. This flexibility allows you to easily update paywalls, products, and offers, or run A/B tests, all without the need for a new app release.

      Error if the paywall with the specified ID is not found or if your bundle ID does not match with your Adapty Dashboard setup.

      import { adapty } from '@adapty/capacitor';

      try {
      const paywall = await adapty.getPaywall({
      placementId: 'YOUR_PLACEMENT_ID',
      locale: 'en',
      });
      console.log('Paywall fetched successfully');
      } catch (error) {
      console.error('Failed to fetch paywall:', error);
      }
    • Fetches the paywall of the specified placement for the All Users audience.

      Parameters

      • options: GetPaywallForDefaultAudienceOptions

        The options for fetching the paywall

        • placementId

          The identifier of the desired placement.

        • locale

          Optional. The identifier of the paywall localization. Default: 'en'.

        • params

          Optional. Additional parameters for fetching the paywall.

      Returns Promise<AdaptyPaywall>

      A promise that resolves with the requested AdaptyPaywall.

      With Adapty, you can remotely configure the products and offers in your app by simply adding them to paywalls – no need for hardcoding them. The only thing you hardcode is the placement ID.

      However, it's crucial to understand that the recommended approach is to fetch the paywall through the placement ID by the getPaywall method. The getPaywallForDefaultAudience method should be a last resort due to its significant drawbacks:

      • Potential backward compatibility issues
      • Loss of targeting (all users see the same paywall)

      See documentation for more details.

      Error if the paywall with the specified ID is not found.

      import { adapty } from '@adapty/capacitor';

      try {
      const paywall = await adapty.getPaywallForDefaultAudience({
      placementId: 'YOUR_PLACEMENT_ID',
      locale: 'en',
      });
      } catch (error) {
      console.error('Failed to fetch paywall:', error);
      }
    • Fetches a list of products associated with a provided paywall.

      Parameters

      Returns Promise<AdaptyPaywallProduct[]>

      A promise that resolves with a list of AdaptyPaywallProduct associated with a provided paywall.

      Error if an error occurs while fetching products.

      import { adapty } from '@adapty/capacitor';

      try {
      const paywall = await adapty.getPaywall({ placementId: 'YOUR_PLACEMENT_ID' });
      const products = await adapty.getPaywallProducts({ paywall });
      console.log('Products:', products);
      } catch (error) {
      console.error('Failed to fetch products:', error);
      }
    • Fetches a user profile.

      Returns Promise<AdaptyProfile>

      A promise that resolves with the user's AdaptyProfile.

      The getProfile method provides the most up-to-date result as it always tries to query the API. If for some reason (e.g. no internet connection), the Adapty SDK fails to retrieve information from the server, the data from cache will be returned. It is also important to note that the Adapty SDK updates AdaptyProfile cache on a regular basis, in order to keep this information as up-to-date as possible.

      Error if an error occurs while fetching the profile.

      import { adapty } from '@adapty/capacitor';

      try {
      const profile = await adapty.getProfile();
      const isSubscribed = profile.accessLevels['YOUR_ACCESS_LEVEL']?.isActive;
      if (isSubscribed) {
      console.log('User has access to premium features');
      }
      } catch (error) {
      console.error('Failed to get profile:', error);
      }
    • Logs in a user with a provided customerUserId.

      Parameters

      • options: { customerUserId: string; params?: IdentifyParamsInput }

        The identification options

        • customerUserId: string

          A unique user identifier.

        • Optionalparams?: IdentifyParamsInput

          Optional. Additional parameters for identification, including platform-specific settings.

      Returns Promise<void>

      A promise that resolves when identification is complete.

      If you don't have a user id on SDK initialization, you can set it later at any time with this method. The most common cases are after registration/authorization when the user switches from being an anonymous user to an authenticated user.

      Error if an error occurs during identification.

      import { adapty } from '@adapty/capacitor';

      try {
      await adapty.identify({ customerUserId: 'YOUR_USER_ID' });
      console.log('User identified successfully');
      } catch (error) {
      console.error('Failed to identify user:', error);
      }
    • Checks if the Adapty SDK is activated.

      Returns Promise<boolean>

      A promise that resolves to true if the SDK is activated, false otherwise.

      Error if an error occurs while checking activation status.

    • Logs out the current user.

      Returns Promise<void>

      A promise that resolves when the user is logged out.

      You can then login the user using identify method.

      Error if an error occurs during logout.

      import { adapty } from '@adapty/capacitor';

      try {
      await adapty.logout();
      console.log('User logged out successfully');
      } catch (error) {
      console.error('Failed to logout user:', error);
      }
    • Logs a paywall view event.

      Parameters

      Returns Promise<void>

      A promise that resolves when the event is logged.

      Adapty helps you to measure the performance of the paywalls. We automatically collect all the metrics related to purchases except for custom paywall views. This is because only you know when the paywall was shown to a customer.

      Whenever you show a paywall to your user, call this function to log the event, and it will be accumulated in the paywall metrics.

      Error if an error occurs while logging the event.

      import { adapty } from '@adapty/capacitor';

      const paywall = await adapty.getPaywall({ placementId: 'YOUR_PLACEMENT_ID' });
      // ...after opening the paywall
      await adapty.logShowPaywall({ paywall });
    • Performs a purchase of the specified product.

      Parameters

      • options: MakePurchaseOptions

        The purchase options

        • product

          The product to be purchased. You can get it using getPaywallProducts method.

        • params

          Optional. Additional parameters for the purchase, including Android subscription update params.

      Returns Promise<AdaptyPurchaseResult>

      A promise that resolves with the AdaptyPurchaseResult object containing details about the purchase. If the result is 'success', it also includes the updated user's profile.

      In paywalls built with Paywall Builder, purchases are processed automatically with no additional code.

      Error if an error occurs during the purchase process.

      Basic purchase

      import { adapty } from '@adapty/capacitor';

      try {
      const result = await adapty.makePurchase({ product });

      if (result.type === 'success') {
      const isSubscribed = result.profile?.accessLevels['YOUR_ACCESS_LEVEL']?.isActive;
      if (isSubscribed) {
      console.log('User is now subscribed!');
      }
      }
      } catch (error) {
      console.error('Purchase failed:', error);
      }
    • Opens a web paywall in the default browser.

      Parameters

      Returns Promise<void>

      A promise that resolves when the web paywall is opened.

      Error if an error occurs while opening the web paywall.

      import { adapty } from '@adapty/capacitor';

      try {
      const paywall = await adapty.getPaywall({ placementId: 'YOUR_PLACEMENT_ID' });
      await adapty.openWebPaywall({ paywallOrProduct: paywall });
      } catch (error) {
      console.error('Failed to open web paywall:', error);
      }
    • Opens a native modal screen to redeem Apple Offer Codes.

      Returns Promise<void>

      A promise that resolves when the redemption sheet is presented.

      iOS 14+ only. Since iOS 14.0, your users can redeem Offer Codes. To enable users to redeem offer codes, you can display the offer code redemption sheet.

      Error if an error occurs or if called on Android.

      import { adapty } from '@adapty/capacitor';

      try {
      await adapty.presentCodeRedemptionSheet();
      } catch (error) {
      console.error('Failed to present code redemption sheet:', error);
      }
    • Removes all attached event listeners.

      Returns Promise<void>

      A promise that resolves when all listeners are removed.

      This method removes all event listeners that were added via addListener. It's recommended to call this method when cleaning up resources, such as when unmounting a component.

      import { adapty } from '@adapty/capacitor';

      // Remove all listeners
      await adapty.removeAllListeners();
    • Sets the variation ID of the purchase.

      Parameters

      • options: { transactionId: string; variationId?: string }

        The options object

        • transactionId: string

          The transaction ID of the purchase.

        • OptionalvariationId?: string

          Optional. The variation ID from the AdaptyPaywall.

      Returns Promise<void>

      A promise that resolves when the transaction is reported.

      In Observer mode, Adapty SDK doesn't know where the purchase was made from. you can manually assign variation to the purchase. After doing this, you'll be able to see metrics in Adapty Dashboard.

      Error if an error occurs while reporting the transaction.

      import { adapty } from '@adapty/capacitor';

      try {
      await adapty.reportTransaction({
      transactionId: 'transaction_123',
      variationId: 'variation_456'
      });
      } catch (error) {
      console.error('Failed to report transaction:', error);
      }
    • Restores user purchases and updates the profile.

      Returns Promise<AdaptyProfile>

      A promise that resolves with the updated user's AdaptyProfile.

      Restoring purchases allows users to regain access to previously purchased content, such as subscriptions or in-app purchases, without being charged again. This feature is especially useful for users who may have uninstalled and reinstalled the app or switched to a new device.

      In paywalls built with Paywall Builder, purchases are restored automatically without additional code from you.

      Error if an error occurs during the restore process.

      import { adapty } from '@adapty/capacitor';

      try {
      const profile = await adapty.restorePurchases();
      const isSubscribed = profile.accessLevels['YOUR_ACCESS_LEVEL']?.isActive;

      if (isSubscribed) {
      console.log('Access restored successfully!');
      } else {
      console.log('No active subscriptions found');
      }
      } catch (error) {
      console.error('Failed to restore purchases:', error);
      }
    • Sets the fallback paywalls.

      Parameters

      • options: { fileLocation: FileLocation }

        The options object

        • fileLocation: FileLocation

          The location of the fallback file for each platform.

      Returns Promise<void>

      A promise that resolves when fallback placements are saved.

      Fallback file will be used if the SDK fails to fetch the paywalls from the dashboard. It is not designed to be used for the offline flow, as products are not cached in Adapty.

      Error if an error occurs while setting the fallback.

      import { adapty } from '@adapty/capacitor';

      try {
      await adapty.setFallback({
      fileLocation: {
      ios: { fileName: 'fallback_paywalls.json' },
      android: { relativeAssetPath: 'fallback_paywalls.json' }
      }
      });
      } catch (error) {
      console.error('Failed to set fallback:', error);
      }
    • Sets an integration identifier for the current user.

      Parameters

      • options: { key: string; value: string }

        The options object

        • key: string

          The key of the integration identifier.

        • value: string

          The value of the integration identifier.

      Returns Promise<void>

      A promise that resolves when the integration identifier is set.

      Integration identifiers can be used to link Adapty profiles to external systems and track users across different platforms.

      Error if an error occurs while setting the identifier.

      import { adapty } from '@adapty/capacitor';

      try {
      await adapty.setIntegrationIdentifier({
      key: 'firebase_app_instance_id',
      value: 'YOUR_FIREBASE_ID'
      });
      } catch (error) {
      console.error('Failed to set integration identifier:', error);
      }
    • Sets the preferred log level and/or custom logger configuration.

      Parameters

      • options: { logger?: LoggerConfig; logLevel?: LogLevel }

        The options object

        • Optionallogger?: LoggerConfig

          Optional. Custom logger configuration.

        • OptionallogLevel?: LogLevel

          Optional. The new preferred log level.

      Returns Promise<void>

      A promise that resolves when the log level is set.

      By default, the log level is set to error.

      There are four levels available:

      • error: only errors will be logged
      • warn: messages from the SDK that do not cause critical errors, but are worth paying attention to
      • info: various information messages, such as those that log the lifecycle of various modules
      • verbose: any additional information that may be useful during debugging, such as function calls, API queries, etc.

      Error if the log level is invalid.

      import { adapty } from '@adapty/capacitor';

      // Set log level
      await adapty.setLogLevel({ logLevel: 'verbose' });

      // Or set custom logger
      await adapty.setLogLevel({
      logger: {
      handler: (level, scope, message, data) => {
      sendLogToYourServer(`[${level}] ${message}`, data);
      }
      }
      });
    • Updates attribution data for the current user.

      Parameters

      • options: { attribution: Record<string, any>; source: string }

        The options object

        • attribution: Record<string, any>

          An object containing attribution data.

        • source: string

          The source of the attribution data (e.g., 'adjust', 'appsflyer').

      Returns Promise<void>

      A promise that resolves when the attribution data is updated.

      Attribution data can be used to track marketing campaigns and user acquisition sources.

      Error if parameters are invalid or not provided.

      import { adapty } from '@adapty/capacitor';

      try {
      const attribution = {
      'Adjust Adid': 'adjust_adid',
      'Adjust Network': 'adjust_network',
      'Adjust Campaign': 'adjust_campaign',
      'Adjust Adgroup': 'adjust_adgroup',
      };

      await adapty.updateAttribution({ attribution, source: 'adjust' });
      } catch (error) {
      console.error('Failed to update attribution:', error);
      }
    • Updates the user's consent for collecting refund data.

      Parameters

      • options: { consent: boolean }

        The options object

        • consent: boolean

          Whether to collect refund data.

      Returns Promise<void>

      A promise that resolves when the consent is updated (or immediately on Android).

      iOS only. This method has no effect on Android. Use this method to update whether the SDK should collect refund data for the user.

      Error if an error occurs on iOS.

      import { adapty } from '@adapty/capacitor';

      try {
      await adapty.updateCollectingRefundDataConsent({ consent: true });
      } catch (error) {
      console.error('Failed to update consent:', error);
      }
    • Updates a profile for the current user.

      Parameters

      Returns Promise<void>

      A promise that resolves when the profile is updated.

      You can set optional attributes such as email, phone number, etc. to the user of your app. You can then use attributes to create user segments or just view them in CRM.

      The attributes that you've previously set won't be reset. Custom attributes can be removed by passing null as their values.

      Error if parameters are invalid or there is a network error.

      Basic profile update

      import { adapty } from '@adapty/capacitor';

      try {
      await adapty.updateProfile({
      email: '[email protected]',
      phoneNumber: '+18888888888',
      firstName: 'John',
      lastName: 'Appleseed',
      gender: 'other',
      birthday: new Date().toISOString(),
      });
      console.log('Profile updated successfully');
      } catch (error) {
      console.error('Failed to update profile:', error);
      }

      Custom attributes

      await adapty.updateProfile({
      codableCustomAttributes: {
      key_1: 'value_1',
      key_2: 2,
      },
      });

      // To remove keys, pass null as their values
      await adapty.updateProfile({
      codableCustomAttributes: {
      key_1: null,
      },
      });
    • Updates the user's refund preference.

      Parameters

      Returns Promise<void>

      A promise that resolves when the preference is updated (or immediately on Android).

      iOS only. This method has no effect on Android. Use this method to set the user's preference for handling refunds.

      Error if an error occurs on iOS.

      import { adapty } from '@adapty/capacitor';

      try {
      await adapty.updateRefundPreference({ refundPreference: 'ask_to_cancel' });
      } catch (error) {
      console.error('Failed to update refund preference:', error);
      }