API de Monetization Provider

Versión: 1.0.0

Introducción

La API cliente de Monetization Provider te permite integrar tu propia solución de monetización con Privacidad y mensajería en Ad Manager.

Para integrar tu propia solución de monetización con el Offerwall, sigue estos pasos:

  • Habilita la opción "Selección personalizada" para el Offerwall desde la pestaña Privacidad y mensajería de Ad Manager.

  • Agrega JavaScript personalizado en el sitio en el que se publica el Offerwall. Puedes encontrar detalles sobre la implementación en las siguientes secciones.

  • Este código JavaScript debe crear una instancia de un proveedor de monetización personalizado como se define a continuación y registrarlo con Privacidad y mensajería en la ventana con la clave de registro: 'publisherCustom'.

Glosario

Término Definición
Proveedor de monetización Un objeto JavaScript nativo que proporciona tu solución de monetización personalizada. Por ejemplo, puedes proporcionar un servicio de suscripción, un servicio de micropagos y mucho más. El Offerwall invoca los métodos de tu proveedor para monetizar tu contenido con tu solución personalizada.
Derecho Es una recompensa que tu solución de monetización otorga a los usuarios por completar una acción de monetización. En el alcance de esta API, un derecho otorga a los usuarios acceso al contenido de tu sitio web sin ver el Offerwall. Tú determinas la cantidad de cargas de página gratuitas o la duración del tiempo otorgado a los usuarios que seleccionan tu opción de monetización personalizada.
Portal de monetización Un punto de entrada a un flujo de monetización. Los portales definen los flujos independientes que ofrece tu solución de monetización. Por ejemplo, un portal puede ser para la "monetización", en el que el usuario puede suscribirse a tu servicio. Otro portal puede ser para “acceder”, en el que el usuario puede acceder para acceder a una suscripción existente.
Clave de registro Es el identificador de un proveedor de monetización, que se usa para registrar la implementación de tu proveedor con Privacidad y mensajería de Google en el momento de la carga de la página.

Implementación de API de muestra

Este es un ejemplo de una implementación funcional que define un proveedor de monetización, crea una instancia de este y lo registra en Privacidad y mensajería de Google.

<script>
  // This class defines a monetization provider by implementing four core functions that every provider
  // must support: initialize, getUserEntitlementState, monetize, and destroy.
  class CustomMonetizationProvider {
    userEntitlementState;

    async initialize(initializeParams) {
      // Replace this function's code with your implementation of the initialize function.
      this.userEntitlementState = googlefc.monetization.UserEntitlementStateEnum.ENTITLED_NO;
      return {initializeSuccess: true, apiVersionInUse: "1.0.0", signInMonetizationPortalSupported: false};
    }

    async getUserEntitlementState() {
      // Replace this function's code with your implementation of the getUserEntitlementState function.
      return this.userEntitlementState;
    }

    async monetize(monetizeParams) {
      // Replace this function's code with your implementation of the monetize function.
      if (monetizeParams.monetizationPortal == googlefc.monetization.MonetizationPortalEnum.PORTAL_PRIMARY_ACCESS) {
        return await this.showSubscriptionPrompt();
      } else {
        console.log('Unsupported monetization portal.');
      }
    }

    async destroy(destructionParams) {
      // Replace this function's code with your implementation of the destroy function.
      console.log('Custom provider is no longer initialized.');
    }

    // ==== The helper functions in this section are only used for this demo, and should be omitted from your actual implementation. ===
    async showSubscriptionPrompt() {
      return new Promise(resolve => {
        const sharedStyles = 'border: 2px solid #6b6e7666; border-radius: 8px; padding: 10px; background: white;';
        const modalStyles =  'width: 500px; z-index: 100; top: 50%; left: 50%; position: absolute; transform: translate(-50%, -50%);';
        const overlayStyles = 'height: 100%; width: 100%; background: black; opacity: 0.6; z-index: 99; position: absolute; top: 0;';

        const modal = this.createElement("div", modalStyles + sharedStyles);
        const overlay = this.createElement("div", overlayStyles);
        const header = this.createElement("h1", 'text-align: center; color: black;', "Subscribe for access.");
        const subscribeButton = this.createElement("button", sharedStyles + 'color: #5499C7; margin-left: 40%;', "Subscribe");
        const backButton = this.createElement("button", sharedStyles + 'color: #5499C7;', "Back");

        this.exitSubscriptionPromptOnButtonClick(subscribeButton, resolve, googlefc.monetization.UserEntitlementStateEnum.ENTITLED_YES, modal, overlay);
        this.exitSubscriptionPromptOnButtonClick(backButton, resolve, googlefc.monetization.UserEntitlementStateEnum.ENTITLED_NO,modal, overlay);

        modal.append(backButton, header, subscribeButton);
        document.body.append(overlay, modal);
      });
    }

    createElement(tag, styles = '', textContent ='') {
      const element = document.createElement(tag);
      element.style.cssText = styles;
      element.textContent = textContent;
      return element;
    }

    exitSubscriptionPromptOnButtonClick(button, resolve, userEntitlementStateEnum, modal, overlay) {
      button.addEventListener("click", () => {
        document.body.removeChild(modal);
        document.body.removeChild(overlay);
        this.userEntitlementState = userEntitlementStateEnum;
        resolve({userEntitlementState: userEntitlementStateEnum});
      });
    }
    // =============================================================================================================================
  };

  // Important: code to register a custom monetization provider with Google Privacy & messaging.
  window.googlefc = window.googlefc || {};
  window.googlefc.monetization = window.googlefc.monetization || {};
  window.googlefc.monetization.providerRegistry =
    window.googlefc.monetization.providerRegistry || new Map();

  window.googlefc.monetization.providerRegistry.set(
    'publisherCustom', new CustomMonetizationProvider());
</script>

El fragmento de código anterior es una implementación de esqueleto que incluye todo lo que se requiere para integrar un proveedor de monetización con la sección Privacidad y mensajería. Ten en cuenta que, para cada función de proveedor, se agregó un código de ejemplo que debes reemplazar con tu propia implementación.

Resumen de métodos

Un proveedor de monetización es un objeto que proporciona la funcionalidad de monetización en las páginas web exponiendo un conjunto principal de funciones. Estas funciones se describen con más detalle a continuación.

Método Resumen
initialize Inicializa el proveedor de monetización junto con los recursos necesarios para realizar acciones de monetización.
getUserEntitlementState Obtén el estado de derechos del usuario en el momento de la invocación.
monetize Renderiza tu solución de monetización personalizada en la página web. Tu solución de monetización puede adoptar cualquier forma, como un anuncio recompensado, un diálogo de servicio de suscripción y mucho más.
destroy Destruye el proveedor, junto con los recursos o trabajos que se estaban ejecutando durante la inicialización. Después de la destrucción, el Offerwall ya no invoca ningún método del proveedor.

Definiciones de métodos

A continuación, se describe con más detalle la definición de cada método de proveedor de monetización.

initialize

initialize(initializeParams:InitializeParams): Promise<InitializeResponse>

Inicializa el proveedor de monetización. Una vez inicializado, el proveedor debería estar listo para responder a cualquier otra función del proveedor. Se garantiza que esta función se invoque antes que cualquier otra función del proveedor y se espera que se invoque una vez como máximo en una carga de página determinada.

Ejemplo:

  async initialize(initializeParams: InitializeParams): Promise<InitializeResponse> {
    const isInitializationSuccessful = await this.initializeMyProvider(initializeParams);
    const initializeResponse = {initializeSuccess: isInitializationSuccessful,
                                                   apiVersionInUse: "1.0.0",
                                                   signInMonetizationPortalSupported: true};
    resolve(initializeResponse);
  }

getUserEntitlementState

getUserEntitlementState(): Promise<UserEntitlementStateEnum>

Obtén el estado de derechos del usuario en el momento de la invocación. El Offerwall se oculta si el usuario tiene derecho, ya que debería recibir acceso gratuito al sitio web.

Ejemplo:

  async getUserEntitlementState(): Promise<googlefc.monetization.UserEntitlementStateEnum> {
      resolve(this.isUserLoggedIn() ? this.isUserEntitledOnThisPage()
        : googlefc.monetization.UserEntitlementStateEnum.ENTITLED_NO);
  }

monetizar

monetize(monetizeParams:MonetizeParams): Promise<MonetizeResponse>

Renderiza tu solución de monetización y controla las acciones de monetización del usuario. La monetización puede adoptar cualquier forma, ya sea un anuncio recompensado, un servicio de suscripción y mucho más. Una vez que el Offerwall invoca este método, se oculta hasta que se resuelve la promesa. Por lo tanto, es responsabilidad del proveedor bloquear el contenido de la página hasta que se resuelva la promesa. Una vez que se resuelva la promesa, el proveedor también debe asegurarse de que ya no sea visible en la página web.

Te recomendamos que uses el código de idioma y los estilos sugeridos que se proporcionan en InitializeParams dentro de tu solución de monetización. Esto garantiza una experiencia visual fluida entre el Offerwall y el proveedor.

El Offerwall establece el parámetro de portal de monetización para indicar a qué portal quiere acceder. Los dos tipos de portales disponibles son PORTAL_PRIMARY_ACCESS, que no es opcional, y PORTAL_SIGN_IN, que sí lo es. Puedes indicar si admites el portal opcional PORTAL_SIGN_IN en tu respuesta a la función initialize.

Cuando resuelvas la promesa de la función de monetización, debes hacer lo siguiente:

  • Oculta tu solución de monetización renderizada.

  • Muestra si el usuario tiene derecho al contenido de la página. Esto determina si el Offerwall se sigue mostrando o se oculta.

  • Muestra cualquier dato adicional sobre la interacción del usuario, si corresponde, como el importe pagado, el tipo y el valor de los derechos, y la recurrencia de la monetización.

Ejemplo:

  async monetize(monetizeParams: MonetizeParams): Promise<MonetizeResponse> {
    const result;
    if (monetizeParams.monetizationPortal == googlefc.monetization.MonetizationPortalEnum.PORTAL_PRIMARY_ACCESS) {
      result = await this.showMyBuyFlow();
    } else if (monetizeParams.monetizationPortal == googlefc.monetization.MonetizationPortalEnum.PORTAL_SIGN_IN) {
      result = await this.showMySignInFlow();
    }

    if (!result.monetized) {
      resolve({userEntitlementState: googlefc.monetization.UserEntitlementStateEnum.ENTITLED_NO});
    }

    const monetizeResponse = {
      userEntitlementState: googlefc.monetization.UserEntitlementStateEnum.ENTITLED_YES,
      newlyGrantedUserEntitlementType: googlefc.monetization.EntitlementTypeEnum.TYPE_PAGEVIEW_COUNT,
      newlyGrantedUserEntitlementValue: 4,
      newlyPaidAmountByUser: {currencyCode: "USD", units: 5, nanos: 0},
      // This monetization event does not auto-recur, so leaving property
      // recurrenceOfNewMonetizationEvent undefined.
    }
    resolve(monetizeResponse);
  }

destruir

destroy(destroyParams:DestroyParams): void

Destruye el proveedor. Se garantiza que esta función se invoque por última vez en el ciclo de vida del proveedor, y debes esperar que se invoque una vez como máximo en una carga de página determinada.

Ejemplo:

  destroy(destroyParams: DestroyParams): void {
    this.recordDestroyReason(destroyParams.destroyReason);
    this.destroyAllOfMyResourcesOnPage();
  }

Definiciones de tipos

A continuación, se describe con más detalle la definición de cada tipo de datos en la API.

Definiciones de objetos

En esta sección, se enumeran todas las definiciones de objetos de la API.

InitializeParams

Es el tipo de parámetro de la función initialize.

interface InitializeParams {
  // The loaded monetization provider API version. i.e. "1.0.0"
  currentApiVersion: string;
  // The language code suggested for the provider to use, as defined by BCP 47.
  suggestedLanguageCode?: string;
  // The styles suggested for the provider to use.
  suggestedStyles?: Styles;
  // The publisher's logo url.
  publisherLogoUrl?: string;
}

Styles

Es el tipo para definir estilos.

interface Styles {
  // The primary color of the Offerwall.
  primaryColor?: string;
  // The background color of the Offerwall.
  backgroundColor?: string;
}

InitializeResponse

Es el tipo de respuesta de la función initialize.

interface InitializeResponse {
  // Whether or not initialization was successful. If initialization is
  // unsuccessful, the Offerwall does not proceed to call other provider methods
  // except for destroy.
  initializeSuccess: boolean;
  // The monetization provider API version that the provider is using. If the
  // indicated major version is not equal to the major version of the API
  // currently on the page, provider execution is halted.
  apiVersionInUse: string;
  // Whether or not the optional sign-in monetization portal is supported. If
  // you indicate that it is supported, the Offerwall renders a sign-in link
  // that will invoke your sign-in portal upon user click.
  signInMonetizationPortalSupported: boolean;
  // Whether or not the provider is disabled. If disabled, the Offerwall can
  // only render with other eligible choices; if no other choices are eligible,
  // the Offerwall won't ever render on the page.
  isProviderDisabled?: boolean;
}

MonetizeParams

Es el tipo de parámetro de la función monetize.

interface MonetizeParams {
  // The monetization portal that the Offerwall wants to invoke. You can
  // indicate whether you support any optional portals in your
  // InitializeResponse; the only portal that isn't optional is
  // MonetizationPortalEnum.PORTAL_PRIMARY_ACCESS. The Offerwall provides the
  // portal enum for the flow requested by the user.
  monetizationPortal: googlefc.monetization.MonetizationPortalEnum;
}

MonetizeResponse

Es el tipo de respuesta de la función monetize.

interface MonetizeResponse {
  // The user's current entitlement state.
  userEntitlementState: googlefc.monetization.UserEntitlementStateEnum;
  // The user's granted entitlement type, only populated if an entitlement was
  // granted within the scope of the current MonetizationProvider.monetize
  // invocation.
  newlyGrantedUserEntitlementType?: googlefc.monetization.EntitlementTypeEnum;
  // The user's granted entitlement value, only populated if an entitlement was
  // granted within the scope of the current MonetizationProvider.monetize
  // invocation.
  newlyGrantedUserEntitlementValue?: number;
  // The amount paid by the user, only populated if a payment occurred within
  // the scope of the current MonetizationProvider.monetize invocation.
  newlyPaidAmountByUser?: Money;
  // The recurrence of the monetization event, populated only if the
  // monetization event occurred within the scope of the current
  // MonetizationProvider.monetize invocation & the monetization event is
  // expected to auto-recur without further action from the user (e.g.
  // registering for a monthly subscription)
  recurrenceOfNewMonetizationEvent?: googlefc.monetization.MonetizationRecurrenceEnum;
}

Money

Es el tipo para definir un importe de dinero en una moneda específica. Consulta la definición original de money.proto.

interface Money {
  // The three-letter currency code defined in ISO 4217.
  currencyCode: string;
  // The whole units of the amount.
  // For example if `currencyCode` is `"USD"`, then 1 unit is one US dollar.
  units?: number;
  // Number of nano (10^-9) units of the amount.
  // The value must be between -999,999,999 and +999,999,999 inclusive.
  // If `units` is positive, `nanos` must be positive or zero.
  // If `units` is zero, `nanos` can be positive, zero, or negative.
  // If `units` is negative, `nanos` must be negative or zero.
  // For example $-1.75 is represented as `units`=-1 and `nanos`=-750,000,000.
  nanos?: number;
}

DestroyParams

Es el tipo de parámetro de la función destroy.

interface DestroyParams {
  // The reason for destroying the provider.
  destroyReason: googlefc.monetization.DestroyReasonEnum;
}

Definiciones de enumeraciones

En esta sección, se enumeran todas las definiciones de enum en la API.

googlefc.monetization.UserEntitlementStateEnum

La enumeración del derecho indica que un usuario puede ser un proveedor de monetización.

googlefc.monetization.UserEntitlementStateEnum {
  ENTITLED_UNKNOWN = 0,
  // The user is currently entitled to access page content.
  ENTITLED_YES = 1,
  // The user is not currently entitled to access page content.
  ENTITLED_NO = 2,
}

googlefc.monetization.MonetizationPortalEnum

Enumeración de los diferentes portales de monetización o puntos de entrada de monetización que un proveedor puede admitir. Consulta el glosario para obtener más información sobre los portales de monetización.

googlefc.monetization.MonetizationPortalEnum {
  PORTAL_UNKNOWN = 0,
  // The primary access portal represents a provider's main entry point into a
  // monetization flow, and must always be supported.
  PORTAL_PRIMARY_ACCESS = 1,
  // The sign in portal represents a provider's monetization entry point that
  // usually begins with the user performing some sign-in or registration
  // action. Provider support for this monetization portal type is optional.
  PORTAL_SIGN_IN = 2,
}

googlefc.monetization.EntitlementTypeEnum

Enumeración de los diferentes tipos de derechos que un proveedor de monetización puede otorgar a un usuario.

googlefc.monetization.EntitlementTypeEnum {
  TYPE_UNKNOWN = 0,
  // This type is used if the user is awarded a positive integer value of
  // Offerwall-free pageviews.
  TYPE_PAGEVIEW_COUNT = 1,
  // This type is used if the user is awarded a positive integer value of
  // seconds (duration) in which they can access Offerwall-free page content any
  // number of times.
  TYPE_DURATION_SECONDS = 2,
}

googlefc.monetization.DestroyReasonEnum

Enumeración de los motivos por los que se puede destruir un proveedor de monetización.

googlefc.monetization.DestroyReasonEnum {
  REASON_UNKNOWN = 0,
  // The Offerwall no longer needs to invoke the monetization provider on the
  // pageview.
  REASON_CALLER_FINISHED = 1,
  // The Offerwall encountered an erroneous state with the monetization provider
  // in the midst of the provider's lifecycle.
  REASON_ERROR_STATE = 2,
  // The API version that the monetization provider is currently using is no
  // longer supported.
  REASON_UNSUPPORTED_API_VERSION = 3,
}

googlefc.monetization.MonetizationRecurrenceEnum

Enumeración de las diferentes cadencias de recurrencia de monetización que se pueden iniciar con alguna acción del usuario.

googlefc.monetization.MonetizationRecurrenceEnum {
  MONETIZATION_RECURRENCE_UNKNOWN = 0,
  MONETIZATION_RECURRENCE_WEEKLY = 1,
  MONETIZATION_RECURRENCE_MONTHLY = 2,
  MONETIZATION_RECURRENCE_ANNUALLY = 3,
}

Registro del proveedor

googlefc.monetization.providerRegistry?: Map<string, Object>

Es el objeto JavaScript a nivel de la ventana que se usa para registrar proveedores de monetización. El registro incluye pasar tu objeto de proveedor creado con una clave a través de una clave de registro estática a un registro que se encuentra en el espacio de nombres de la ventana: window.googlefc.monetization

// Register a custom monetization provider with Google Privacy & messaging.
window.googlefc = window.googlefc || {};
window.googlefc.monetization = window.googlefc.monetization || {};
window.googlefc.monetization.providerRegistry =
                            window.googlefc.monetization.providerRegistry || new Map();

window.googlefc.monetization.providerRegistry.set(
                            'publisherCustom', new CustomMonetizationProvider());

Historial de versiones

Versión Fecha de lanzamiento Resumen
1.0.0 24/7/2023 Lanzamiento inicial de la API de Monetization Provider.