# Make Purchases through Google Play Store

In order to use IAP with Google Play Store, you must have an active Google Session, to do this read our [Google Sign in Guide](https://lootlocker.com/guides/google-signin-unity-unreal) or take a look at our in-house feature [UPA](https://docs.lootlocker.com/players/unified-player-accounts) where you can start a Remote Login Session for Google!

{% hint style="warning" %}
It is presumed that you have at least made an Application in Google Play Console!
{% endhint %}

## Create In App Purchases on Google

To utilize IAP you must make the In App Purchases in [Google Play Console](https://play.google.com/console).

Some important information to find is your application name; it generally follows this style "com.company.app\_name", this name can be found under the overview of all your applications, or inside the application page beneath the title.

<figure><img src="https://534367586-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MVu1MPzezO-NgvC98xh%2Fuploads%2Fgit-blob-5fbbe0055982270100a1ccbef01666e73118b9ac%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>

Underneath the `Monetization` page in the left menu list, you will see `Products` which contains In-app products. This is where you set up your products to use IAP with.

Create new in-app product, supply all the required fields.

## Creating Purchases In Engine

{% tabs %}
{% tab title="Unity" %}
To create Purchases in Unity, you must inherit from `IDetailedStoreListener` and import the required methods that follows.

This is how you add products to your IAPManager:

```csharp
        builder.AddProduct("<replace_with_product_id>", ProductType.Consumable);
```

Here is how you'd initiate a Purchase:

```csharp
    public void Purchase()
    {
        var product = controller.products.WithID("<replace_with_product_id>");

        if (product is { availableToPurchase: true })
        {
            controller.InitiatePurchase(product);
        }
    }
```

This snippet shows you how you'll connect LootLocker IAP to the flow:

In this example LootLockerIAPManager.cs has a `RedeemPurchase(Product product)` method which will be described underneath [#redeem-purchase-for-player](#redeem-purchase-for-player "mention") and [#redeem-purchase-for-class](#redeem-purchase-for-class "mention")

```csharp
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
    {
        LootLockerIAPManager.RedeemPurchase(e.purchasedProduct);
        return PurchaseProcessingResult.Complete;
    }
```

This is the complete script:

```csharp
using Unity.Services.Core;
using Unity.Services.Core.Environments;
using UnityEngine;
using UnityEngine.Purchasing;
using UnityEngine.Purchasing.Extension;

public class IAPManager : MonoBehaviour, IDetailedStoreListener
{

    public IStoreController controller;
    private IExtensionProvider extensions;

    public async void Awake()
    {
        try
        {
            var options = new InitializationOptions()
                .SetEnvironmentName("production");

            await UnityServices.InitializeAsync(options);
        }
        catch (Exception exception)
        {
            Debug.Log(exception);
        }
        //Specifically creates IAP for Google Play Store, using ifdefs to determine which platform is being run is preferable.
        var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance(AppStore.GooglePlay));

        builder.AddProduct("<replace_with_product_id>", ProductType.Consumable);

        StandardPurchasingModule.Instance().useFakeStoreAlways = true;

        UnityPurchasing.Initialize(this, builder);
    }

    public void OnPurchaseClicked(string productId)
    {
        controller.InitiatePurchase(productId);
    }

    public void Purchase()
    {
        var product = controller.products.WithID("<replace_with_product_id>");

        if (product is { availableToPurchase: true })
        {
            controller.InitiatePurchase(product);
        }
    }

    /// <summary>
    /// Called when Unity IAP is ready to make purchases.
    /// </summary>
    public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
    {
        this.controller = controller;
        this.extensions = extensions;
    }

    /// <summary>
    /// Called when Unity IAP encounters an unrecoverable initialization error.
    ///
    /// Note that this will not be called if Internet is unavailable; Unity IAP
    /// will attempt initialization until it becomes available.
    /// </summary>
    public void OnInitializeFailed(InitializationFailureReason error)
    {
    }

    /// <summary>
    /// Called when a purchase completes.
    ///
    /// May be called at any time after OnInitialized().
    /// </summary>
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
    {
        LootLockerIAPManager.RedeemPurchase(e.purchasedProduct);
        return PurchaseProcessingResult.Complete;
    }

    /// <summary>
    /// Called when a purchase fails.
    /// </summary>
    public void OnPurchaseFailed(Product i, PurchaseFailureReason p)
    {
    }

    public void OnPurchaseFailed(Product product, PurchaseFailureDescription failureDescription)
    {

    }

    public void OnInitializeFailed(InitializationFailureReason error, string message)
    {
        Debug.Log("Error: " + message);
    }
}
```

{% endtab %}

{% tab title="Unreal" %}
{% hint style="danger" %}
A guide is currently in the making as this requires a lot of set up! Once the guide is up, it will be linked here.
{% endhint %}
{% endtab %}
{% endtabs %}

## Redeem Purchase For Player

{% tabs %}
{% tab title="Unity" %}
`Product` is from using UnityEngine.Purchasing;

Which is a Package called "In-App Purchasing", read more [here](https://docs.unity3d.com/Packages/com.unity.purchasing@4.1/manual/UnityIAPGoogleConfiguration.html).

```csharp
public void RedeemPurchase(Product product)
{
    string productID = product.definition.id;
    string purchaseToken = product.transactionID;
    LootLockerSDKManager.RedeemGooglePlayStorePurchaseForPlayer(productID, purchaseToken, (result) =>
    {
        if (!result.success)
        {
            Debug.Log("Redeem Purchase unsuccessful!");
            return;
        }

    });
}
```

{% endtab %}

{% tab title="Unreal" %}

<figure><img src="https://534367586-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MVu1MPzezO-NgvC98xh%2Fuploads%2Fgit-blob-834c2738ea3e45e70147ef1ac8912907b149e902%2Fimage.png?alt=media" alt=""><figcaption><p><a href="https://blueprintue.com/blueprint/zqd9d_1_/">Blueprint example of redeeming purchase for player</a></p></figcaption></figure>

To be able to redeem a Google purchase you've made, you need to grab the product id (the same you used to make the purchase) and the purchase token from a successful purchase as input for the redeem.

On a successful redemption, the player will have been rewarded with whatever catalog item that this product id has been set up to reward.
{% endtab %}

{% tab title="REST" %}

```bash
curl --location --request POST 'https://api.lootlocker.io//game/redeem/store/google' \
--header 'x-session-token: {{session_token}}' \
--header 'User-Agent: Apidog/1.0.0 (https://apidog.com)' \
--header 'Content-Type: application/json' \
--data-raw '{
    "sandboxed": true,
    "transaction_id": "2000000316432479"
}'
```

On a successful Purchase, a 204 will be returned with no body.
{% endtab %}
{% endtabs %}

## Redeem Purchase For Class

{% tabs %}
{% tab title="Unity" %}
`Product` is from using UnityEngine.Purchasing;

Which is a package called "In-App Purchasing", read more [here](https://docs.unity3d.com/Packages/com.unity.purchasing@4.1/manual/UnityIAPGoogleConfiguration.html).

```csharp
public void RedeemPurchase(Product product)
{
    string productID = product.definition.id;
    string purchaseToken = product.transactionID;
    int classID = 123;
    LootLockerSDKManager.RedeemGooglePlayStorePurchaseForClass(productID, purchaseToken, classID, (result) =>
    {
        if (!result.success)
        {
            Debug.Log("Redeem Purchase unsuccessful!");
            return;
        }

    });
}
```

{% endtab %}

{% tab title="Unreal" %}

<figure><img src="https://534367586-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MVu1MPzezO-NgvC98xh%2Fuploads%2Fgit-blob-967a7b103c6112ef9d2d9bd354f3ef95f15e5773%2Fimage.png?alt=media" alt=""><figcaption><p><a href="https://blueprintue.com/blueprint/pl549sul/">Blueprint example of redeeming purchase for class</a></p></figcaption></figure>

To be able to redeem a Google purchase you've made, you need to grab the product id (the same you used to make the purchase) and the purchase token from a successful purchase as input for the redeem.

On a successful redemption, the player will have been rewarded with whatever catalog item that this product id has been set up to reward.
{% endtab %}

{% tab title="REST" %}

```bash
curl --location --request POST 'https://api.lootlocker.io/game/redeem/store/google' \
--header 'x-session-token: {{session_token}}' \
--header 'User-Agent: Apidog/1.0.0 (https://apidog.com)' \
--header 'Content-Type: application/json' \
--data-raw '{
    "sandboxed": true,
    "transaction_id": "2000000316432499",
    "character_id": 123
}'
```

On a successful Purchase, a 204 will be returned with no body.
{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.lootlocker.com/commerce/real-money-purchases/how-to/google-play-store-purchasing.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
