Payments SDK Plugin for Unity

With the now.gg Payments SDK plugin for Unity, you can implement in-app purchases within your game on Unity.

To implement in-app purchases using the now.gg IAP plugin:

  1. Download and Import the now.gg Payments SDK Unity plugin.
  2. Add required dependencies.
  3. Implement now.gg Payments SDK to your project.

Download and Import the Plugin

The now.gg Payments SDK Unity plugin is included as a Unity package file NowGGSdk-1.2.3.1003.unitypackage.

To add the plugin within your Unity project:

  1. Download the package containing the latest version of now.gg Payments SDK Plugin for Unity.
  2. After you have downloaded the plugin, import it into your Unity project. To do this:
    • Click on Assets > Import Package > Custom Package, as shown below:
    • Select NowGGSdk-1.2.3.1003.unitypackage that you previously downloaded.
    • Select all the listed files and click on Import.

Once all the plugin files have been imported, a folder named ‘NowGGSdk‘ will be added to your project. You can find this folder within the root of the Assets folder.

Note: Please do not modify the NowGGSdk folder, as that contains all the assets related to now.gg Payments SDK.

Add Required Dependencies

This operation will download and add all the required dependencies to the Assets/Plugins/Android directory of your project using the Unity External Dependency Manager.

To add the required dependencies follow the steps below:

  • Click on Assets > External Dependency Manager > Android Resolver > Resolve.

Implement now.gg Payments SDK

Once the now.gg Payments SDK Plugin has been imported and the dependencies have been added, you should now implement the code to integrate your app/game with now.gg Payments SDK.

Add Platform check to your Unity IAP implementation

To run the now.gg IAP service, the now.gg platform is required. The Unity IAP (or any other IAP services) should only be initialized when you are not running on the now.gg platform.

In order to check the platform, you should add the following code to your implementation so that Unity IAP is not activated when your app is running on the now.gg platform:

public void Start()
 {
 	 if (NowGG.Sdk.NowGGSdkManager.IsNowGGIapAvailable())
            return;

	 // Your Unity IAP code here...
 }

Implement now.gg IAP in Unity

The following sections illustrate the implementation of the now.gg IAP functions which you can call from your app/game in Unity.

Start by creating a class that contains the now.gg IAP implementation and attach it to a game object that you can use to initialize the in-app purchases.

1. Add Products and Initialize SDK

This step will allow you to add the in-app purchase products in your app/game and initialize the SDK.

For example, we have added two IAP consumable products with product id ‘coin1’ and ‘coin2’ and a non-consumable product with product id  ‘gunSkin’ in the following code.

Similarly, you can add other products with the corresponding product id that you have added within the developer portal.

public void Start()
 {
	 // Only initialize Now.gg IAP if running on Now.gg platform
	 if (!NowGG.Sdk.NowGGSdkManager.IsNowGGIapAvailable())
		 return;

	 NowGGProductBuilder.Instance.AddProduct("coin1", ProductType.Consumable);
	 NowGGProductBuilder.Instance.AddProduct("coin2", ProductType.Consumable);
	 NowGGProductBuilder.Instance.AddProduct("gunSkin", ProductType.NonConsumable);

	 NowGGSdkManager.Instance.OnInitSuccess += OnInitSuccess;
	 NowGGSdkManager.Instance.OnInitFailed += OnInitFailed;
	 NowGGSdkManager.Instance.OnPurchaseCompleted += OnPurchaseProduct;
     NowGGSdkManager.Instance.OnPurchaseFailed += OnPurchaseFailed;

	 NowGGSdkManager.Instance.InitializeIap(NOWGG_APP_ID);
 }

Explanation:

  • An initial check is performed to ensure that you are initializing the now.gg Payments service on the now.gg platform.
  • The in-app products are added to the ProductBuilder class.
  • InitializeIap function of the NowGGSdkManager Class is called to init the Payments SDK using the NOWGG_APP_ID.
  • The SDK responses are recorded using the three callback functions, as illustrated above.

Note:

  • NowGG_APP_ID is a unique identifier for your app.
  • Each app that you add on the now.gg developer portal generates a unique App ID, which you can find under your app details within now.gg Developer Portal.
2. Get Product Details

After successful initialization, you can get the product details in your app using the product id.

To get product details, refer to the following implementation:

private void OnInitSuccess()
 {
    Debug.Log($"IAP init success");

    // now you can get product details using product id
   string price = NowGGSdkManager.Instance.GetProductWithID("coin1").price;
   string currencyCode = NowGGSdkManager.Instance.GetProductWithID("coin1").priceCurrencyCode;
 }

 private void OnInitFailed(string reason)
 {
   Debug.Log($"IAP init failed {reason}");
 }
3. Initiate purchase

After you have the product details, you can initiate a product purchase. To do so, you have to call the PurchaseProduct() function as illustrated below:

public void PurchaseProduct(string productId)
 {
     NowGGSdkManager.Instance.PurchaseProduct(productId);
 }

Note:

  • ProductId is a unique identifier for the in-app product(s) that you have defined within now.gg developer portal for your specific App (App Id).
  • Prices for the products are fetched from the price template that you created within the developer portal.
4. Assigning the purchased products to a User

After a successful purchase, you can assign the in-app purchased product to the user. To do so, you can refer to the implementation below:

private PurchaseProcessingResult OnPurchaseProduct(PurchasedProduct purchasedProduct)
 {
     // A consumable product has been purchased by this user.
     if (String.Equals(purchasedProduct.productId, "coin1", StringComparison.Ordinal))
     {
         Debug.Log(string.Format("OnPurchaseProduct: PASS. Product: '{0}'", purchasedProduct.productId));
         // The consumable item has been successfully purchased, add 100 coins to the player's in-game currency.
         // coin += 100;
     }
     else if (String.Equals(purchasedProduct.productId, "coin2", StringComparison.Ordinal))
     {
         Debug.Log(string.Format("OnPurchaseProduct: PASS. Product: '{0}'", purchasedProduct.productId));
         // The consumable item has been successfully purchased, add 200 coins to the player's in-game currency.
         // coin += 200;
     }
     else
     {
         Debug.Log(string.Format("OnPurchaseProduct: FAIL. Unrecognized product: '{0}'", purchasedProduct.productId));
     }

     // Return a flag indicating whether this product has been received, or if the application needs to be reminded of this purchase at the next app launch.
     // Return PurchaseProcessingResult.Pending if you want to be reminded of this purchase on the next launch of your app/game.
     // Return PurchaseProcessingResult.Complete to specify that this is a one time purchase and you have allotted the purchased in-game item to the user.

     return PurchaseProcessingResult.Complete;
 }
5. Confirm Pending Purchase

If you wish to process the purchase on your backend server, or you need to complete the purchase using some other method based on your implementation, your app should return PurchaseProcessingResult.Pending from OnPurchaseProduct.

To complete the purchase flow, you can use the ConfirmPendingPurchase method to inform the now.gg IAP service that the app has made a record of the purchase.

void ConfirmPendingPurchase(PurchasedProduct purchasedProduct)
 {
   NowGGSdkManager.Instance.ConfirmPendingPurchase(purchasedProduct);
 }

Note: Once the pending purchase is confirmed, the now.gg IAP service will not notify about the said purchase to the app.

6. Query Pending Purchases

If you need to query for pending purchases you can call the QueryPendingPurchases function of the NowGGSdkManager class. This function will query all the pending purchases and call the OnPurchaseProduct callback along with the pending purchases.

7. Fetch Additional Products

If you wish to fetch additional products for purchase or to refresh the details/metadata associated with the existing products, you can use the FetchAdditionalProducts function as illustrated below.

var newProducts = new System.Collections.Generic.Dictionary<string, ProductType>();
 newProducts.Add("coin2", ProductType.Consumable);
 newProducts.Add("coin3", ProductType.Consumable);

 NowGGSdkManager.Instance.FetchAdditionalProducts(newProducts,
       () =>
       {
           //Additional products fetched, they can now be purchased.
           Debug.Log($"Successfully fetched additional products");
           string price = NowGGSdkManager.Instance.GetProductWithID("coin1").price;
           string currencyCode = NowGGSdkManager.Instance.GetProductWithID("coin1").priceCurrencyCode;
       },
      reason =>
      {
          Debug.Log($"Fetching additional products failed: {reason}");
      });
8. Handling Failed Purchases

Purchases may fail due to any number of reasons including network/connectivity issues, payment failure or configuration issues. You may investigate the reasons for failed purchases and implement any necessary actions.

You can handle failed purchases and write your desired implementation by referring to the following code:

public void OnPurchaseFailed(int errorCode, string errorMessage)
 {
    Debug.Log($"OnPurchaseFailed: errorCode: {errorCode} and msg: {errorMessage}");
 }

Purchase Verification

now.gg Payments SDK utilizes a public key to verify in-app purchases, which enables you to establish the authenticity of a purchase. It is recommended to authenticate every purchase prior to assigning the product to the user.

Verify the purchases with your Public Key

You can either verify purchase(s) locally or use a backend server. However, we recommend using your backend server to verify a purchase.

The following code segment is an illustration to verify purchase(s) locally and using a backend server. You can refer to the SDK Demo project for more details.

private PurchaseProcessingResult OnPurchaseProduct(PurchasedProduct purchasedProduct) {
    // If you want to do local verification, use this sample code
    bool isValidPurchase = PurchaseVerification.Instance.VerifyPurchaseLocally(
        BASE_64_ENCODED_PUBLIC_KEY,
        purchasedProduct.originalJson,
        purchasedProduct.signature); 

    // We recommend you to verify purchases on your backend server.
    // You need to send signature and original data to your backend server for verification.
    PurchaseVerification.Instance.VerifyValidSignatureOnBackend(
        purchasedProduct.originalJson,
        purchasedProduct.signature);

    // A consumable product has been purchased by this user.
    if (String.Equals(purchasedProduct.productId, "coin1", StringComparison.Ordinal))
    {
        Debug.Log(string.Format("OnPurchaseProduct: PASS. Product: '{0}'", purchasedProduct.productId));
        // The consumable item has been successfully purchased, add 100 coins to the player's in-game currency.
        // coin += 100;
    } 
    else if (String.Equals(purchasedProduct.productId, "coin2", StringComparison.Ordinal)) 
    {
        Debug.Log(string.Format("OnPurchaseProduct: PASS. Product: '{0}'", purchasedProduct.productId));
        // The consumable item has been successfully purchased, add 200 coins to the player's in-game currency.
        // coin += 200;
    } 
    else 
    {
        Debug.Log(string.Format("OnPurchaseProduct: FAIL. Unrecognized product: '{0}'", purchasedProduct.productId));
    }

    return PurchaseProcessingResult.Complete;
}

Server Verification

The SDK download package contains a sample implementation to verify a purchase using a backend server which you can use to write your own implementation. You may use it to write your own implementation.

The sample implementation includes-

  • PurchaseVerification class: Located in the SDK Demo Project, it contains Unity-specific code to send purchase data and signature to the backend server.
  • Server.py: Located separately within the download package, it includes sample python code to run a local server and perform backend verification.

Local Verification

We have provided a sample implementation within the SDK download package for local verification of purchase. You can use the provided sample to write your own implementation.

In the sample implementation-

  • You can refer to the VerifyPurchaseLocally function of the PurchaseVerification class.

SDK Demo Project

We have also included an SDK Demo project in the download package. You can refer to this project to understand the IAP payments flow using ‘now.gg Payments SDK’.

To understand the payments flow:

  • Open this project in Unity.
  • Open the scene SdkSample.unity from the Assets\Scenes directory in your Project panel.
×
Text copied to clipboard
Questions? Please reach out to us at dev-support@now.gg