### Code examples

On each request this plugin is instantiated as a global object, you do not need to instantiate it again:

        $AudiencePlayerWordpressPlugin

### API queries

The AudiencePlayer API is based on GraphQL. The integrated AudiencePlayer API client for PHP offers convenient shorthand wrapper methods for the most commonly used queries and mutations but also provides the possibility to directly execute a "raw" GraphQL operation.

        # Fetch user details
        $AudiencePlayerWordpressPlugin->api()->query
            ->ArticleList()
            ->paginate(25, 0)
            ->properties(['id', 'name', 'metas' => ['key', 'value']])
            ->sort('published_at', 'desc')
            ->execute();

        # Same query conducted as a "raw" operation
        $AudiencePlayerWordpressPlugin->api()->executeRawGraphQLCall(
            AudiencePlayerApiClient::OAUTH_SCOPE_USER,  # the oauth-scope you wish to address the api with
            'query { ArticleList (limit:25 offset:0)    # raw GraphQL operation (query/mutation)
             {id name metas{key value}}}'
        );

The API-client can also easily be addressed using the ajax-endpoint "audienceplayer_api_call" provided by the plugin. It takes raw GraphQL operations.

        var operation = 'query { ArticleList (category_id:123) { id name metas{key value} } }';

        $.post('/wp-admin/admin-ajax.php', {
            action: 'audienceplayer_api_call',
            operation: operation
            variables: []
        }).done(function (response) {
            console.log('success', response);
        }).fail(function (response) {
            console.log('fail', response);

        });

### Plugin helper methods

A batch of convenient helper methods are available to interact with the data more easily:

- ->isAuthenticated()
  Check if the remote AudiencePlayer user is authenticated
- ->fetchApiBaseUrl()
  Fetch the configured AudiencePlayer base url
- ->fetchProjectId()
  Fetch the configured AudiencePlayer project id
- ->fetchPaymentProviderId()
  Fetch the configured AudiencePlayer payment provider id
- ->fetchUserBearerToken()
  Fetch the configured AudiencePlayer user OAuth2 bearer token
- ->fetchCurrentAudiencePlayerUser()
  Fetch the AudiencePlayer user synchronised with the current wp user
- ->fetchEmbedPlayerLibraryBaseUrl()
  Fetch the base url of the Embed Player JavaScript library
- ->fetchMetaValueForKey(array $metas, string $key, $fallbackValue = null)
  Helper to quickly fetch a value for a given meta-field from the structure "metas {key value}"
- ->fetchImageWithAspectRatio(array $images, string $aspectRatioProfile = '16x9', int $fallbackIndex = 0)
  Helper to quickly fetch an image with preferred aspect ratio from the structure "images {url aspect_ratio_profile}"
- ->fetchTranslations(mixed $key = null)
  Helper to quickly fetch a translation (as set in template "audienceplayer-core-translations.php").
- ->setTranslations($key, $value = null)
  Helper to set a translation
- ->isOrderValidated(int $orderId)
  Check if a certain order was validated during the current request
- ->fetchValidatedOrder(int $orderId)
  Fetch a certain validated order to obtain all the details (e.g. useful when implementing your own commercial tracking events like GTM).

### Modal player

You can open the modal player by using the instantiated global javascript helper window.AudiencePlayerCore:

        window.AudiencePlayerCore.openModalPlayer(
            event,
            articleId,
            assetId,
            callbackAuthenticationError,
            callbackAuthorisationError,
            callbackGeneralError
        );

### Subscription/Product entitlements via Wordpress

If you cannot or do not want to use the AudiencePlayer payment/entitlement flow facilitated by this plugin, you need to set up purchases via Wordpress. In the Wordpress ecosystem there are many e-Commerce plugins available (e.g. WooCommerce, Magento, etc).
→ N.B. We have introduced a bèta feature which automatically applies the logic described below, to the WooCommerce plugin.
After a User has purchased a product via your e-Commerce plugin which should entitle the User to the playback of one or more video Articles, you need to reflect this entitlement in AudiencePlayer as well. This ensures that the User can play given video Articles on all platforms (i.e. besides Wordpress there might be other AudiencePlayer platforms you use like native mobile apps, Smart TV etc):

1. First set up the necessary Subscription(s) and or Product(s) in AudiencePlayer CMS.
2. In Wordpress, ensure that you can label your Wordpress e-Commerce products with the relevant AudiencePlayer Product/Subscription ID (e.g. through an "SKU" or "external_id" meta field provided by your e-Commerce plugin).
3. Set up a callback in a Wordpress action or filter made available by your e-Commerce plugin upon completion or refund of a purchase. In this callback, you can use the two helper methods below, to simpy fulfil or revoke the entitlment in AudiencePlayer.

        ### Sync entitlement for a User to an AudiencePlayer Subscription
        $result = $AudiencePlayerWordpressPlugin->syncWordpressUserSubscriptionEntitlementToAudiencePlayer(
            \get_current_user_id(),                 # ID of the currently logged-in Wordpress User
            123,                                    # ID if the AudiencePlayer Subscription
            'fulfil',                               # Either 'fulfil' or 'revoke' the entitlement
            new \DateTime('2022-12-12T20:00:00Z')   # In case of 'fulfil', specify the expiry date of the entitlement

        );

        ### Sync entitlement for a User to an AudiencePlayer Product
        $result = $AudiencePlayerWordpressPlugin->syncWordpressUserProductEntitlementToAudiencePlayer(
            \get_current_user_id(),                 # ID of the currently logged-in Wordpress User
            456,                                    # ID if the AudiencePlayer Product
            'fulfil'                                # Either 'fulfil' or 'revoke' the entitlement
        );