Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

In-App Purchase Service Problem

Discussion in 'Scripting' started by Alzan, Dec 16, 2015.

  1. Alzan

    Alzan

    Joined:
    Sep 2, 2012
    Posts:
    81
    Hey, I'm working on an Android application that uses Unity's new IAP system. After implementing some code based off of their demo script I get the following error message when calling the buy function:
    I've checked that my kGooglePlayPuzzles variable matches the item id setup in the Play Store. I'm also saving the items we have purchased in the PlayerPrefs during the PurchaseProcessingResult function, which doesn't seem to be secure, is there any way to improve on the security?

    Thanks!

    Code (CSharp):
    1. using System;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.Purchasing;
    5.    
    6.     // Deriving the Purchaser class from IStoreListener enables it to receive messages from Unity Purchasing.
    7.     public class IAP : MonoBehaviour, IStoreListener
    8.     {
    9.         private static IStoreController m_StoreController; // Reference to the Purchasing system.
    10.         private static IExtensionProvider m_StoreExtensionProvider; // Reference to store-specific Purchasing
    11.  
    12.         private static string kPuzzles = "puzzles_all"; // General handle for the consumable product.
    13.  
    14.         private static string kGooglePlayPuzzles = "com.------------myInfo----------------"; // Google Play Store identifier for the consumable product.
    15.        
    16.         void Start()
    17.         {
    18.             // If we haven't set up the Unity Purchasing reference
    19.             if (m_StoreController == null)
    20.             {
    21.                 // Begin to configure our connection to Purchasing
    22.                 InitializePurchasing();
    23.             }
    24.         }
    25.        
    26.         public void InitializePurchasing()
    27.         {
    28.             // If we have already connected to Purchasing ...
    29.             if (IsInitialized())
    30.             {
    31.                 // ... we are done here.
    32.                 return;
    33.             }
    34.            
    35.             // Create a builder, first passing in a suite of Unity provided stores.
    36.             var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
    37.            
    38.             // Add a product to sell / restore by way of its identifier, associating the general identifier with its store-specific identifiers.
    39.             builder.AddProduct(kPuzzles, ProductType.NonConsumable, new IDs(){ kGooglePlayPuzzles,  GooglePlay.Name });// Continue adding the non-consumable product.
    40.            
    41.             UnityPurchasing.Initialize(this, builder);
    42.         }
    43.        
    44.        
    45.         private bool IsInitialized()
    46.         {
    47.             // Only say we are initialized if both the Purchasing references are set.
    48.             return m_StoreController != null && m_StoreExtensionProvider != null;
    49.         }
    50.        
    51.         public void BuyNonConsumable()
    52.         {
    53.             // Buy the non-consumable product using its general identifier. Expect a response either through ProcessPurchase or OnPurchaseFailed asynchronously.
    54.             BuyProductID(kPuzzles);
    55.         }
    56.        
    57.        
    58.         void BuyProductID(string productId)
    59.         {
    60.             // If the stores throw an unexpected exception, use try..catch to protect my logic here.
    61.             try
    62.             {
    63.                 // If Purchasing has been initialized ...
    64.                 if (IsInitialized())
    65.                 {
    66.                     // ... look up the Product reference with the general product identifier and the Purchasing system's products collection.
    67.                     Product product = m_StoreController.products.WithID(productId);
    68.                    
    69.                     // If the look up found a product for this device's store and that product is ready to be sold ...
    70.                     if (product != null && product.availableToPurchase)
    71.                     {
    72.                         Debug.Log (string.Format("Purchasing product asychronously: '{0}'", product.definition.id));// ... buy the product. Expect a response either through ProcessPurchase or OnPurchaseFailed asynchronously.
    73.                         m_StoreController.InitiatePurchase(product);
    74.                     }
    75.                     // Otherwise ...
    76.                     else
    77.                     {
    78.                         // ... report the product look-up failure situation
    79.                         Debug.Log ("BuyProductID: FAIL. Not purchasing product, either is not found or is not available for purchase");
    80.                     }
    81.                 }
    82.                 // Otherwise ...
    83.                 else
    84.                 {
    85.                     // ... report the fact Purchasing has not succeeded initializing yet. Consider waiting longer or retrying initiailization.
    86.                     Debug.Log("BuyProductID FAIL. Not initialized.");
    87.                 }
    88.             }
    89.             // Complete the unexpected exception handling ...
    90.             catch (Exception e)
    91.             {
    92.                 // ... by reporting any unexpected exception for later diagnosis.
    93.                 Debug.Log ("BuyProductID: FAIL. Exception during purchase. " + e);
    94.             }
    95.         }
    96.        
    97.        
    98.         // Restore purchases previously made by this customer. Some platforms automatically restore purchases. Apple currently requires explicit purchase restoration for IAP.
    99.         public void RestorePurchases()
    100.         {
    101.             // If Purchasing has not yet been set up ...
    102.             if (!IsInitialized())
    103.             {
    104.                 // ... report the situation and stop restoring. Consider either waiting longer, or retrying initialization.
    105.                 Debug.Log("RestorePurchases FAIL. Not initialized.");
    106.                 return;
    107.             }
    108.            
    109.             // If we are running on an Apple device ...
    110.             if (Application.platform == RuntimePlatform.IPhonePlayer ||
    111.                 Application.platform == RuntimePlatform.OSXPlayer)
    112.             {
    113.                 // ... begin restoring purchases
    114.                 Debug.Log("RestorePurchases started ...");
    115.                
    116.                 // Fetch the Apple store-specific subsystem.
    117.                 var apple = m_StoreExtensionProvider.GetExtension<IAppleExtensions>();
    118.                 // Begin the asynchronous process of restoring purchases. Expect a confirmation response in the Action<bool> below, and ProcessPurchase if there are previously purchased products to restore.
    119.                 apple.RestoreTransactions((result) => {
    120.                     // The first phase of restoration. If no more responses are received on ProcessPurchase then no purchases are available to be restored.
    121.                     Debug.Log("RestorePurchases continuing: " + result + ". If no further messages, no purchases available to restore.");
    122.                 });
    123.             }
    124.             // Otherwise ...
    125.             else
    126.             {
    127.                 // We are not running on an Apple device. No work is necessary to restore purchases.
    128.                 Debug.Log("RestorePurchases FAIL. Not supported on this platform. Current = " + Application.platform);
    129.             }
    130.         }
    131.        
    132.        
    133.         //
    134.         // --- IStoreListener
    135.         //
    136.        
    137.         public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
    138.         {
    139.             // Purchasing has succeeded initializing. Collect our Purchasing references.
    140.             Debug.Log("OnInitialized: PASS");
    141.            
    142.             // Overall Purchasing system, configured with products for this application.
    143.             m_StoreController = controller;
    144.             // Store specific subsystem, for accessing device-specific store features.
    145.             m_StoreExtensionProvider = extensions;
    146.         }
    147.        
    148.        
    149.         public void OnInitializeFailed(InitializationFailureReason error)
    150.         {
    151.             // Purchasing set-up has not succeeded. Check error for reason. Consider sharing this reason with the user.
    152.             Debug.Log("OnInitializeFailed InitializationFailureReason:" + error);
    153.         }
    154.        
    155.        
    156.         public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
    157.         {
    158.             // A consumable product has been purchased by this user.
    159.             if (String.Equals(args.purchasedProduct.definition.id, kPuzzles, StringComparison.Ordinal))
    160.             {
    161.                 Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));
    162.                 //If the consumable item has been successfully purchased, add 100 coins to the player's in-game score.
    163.                 PlayerPrefs.SetInt("Puzzles_All", 1);
    164.             }
    165.             else
    166.             {
    167.                 Debug.Log(string.Format("ProcessPurchase: FAIL. Unrecognized product: '{0}'", args.purchasedProduct.definition.id));
    168.                 PlayerPrefs.SetInt("Puzzles_All", 0);
    169.             }
    170.             // Return a flag indicating wither this product has completely been received, or if the application needs to be reminded of this purchase at next app launch. Is useful when saving purchased products to the cloud, and when that save is delayed.
    171.             return PurchaseProcessingResult.Complete;
    172.         }
    173.        
    174.        
    175.         public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
    176.         {
    177.             // A product purchase attempt did not succeed. Check failureReason for more detail. Consider sharing this reason with the user.
    178.             Debug.Log(string.Format("OnPurchaseFailed: FAIL. Product: '{0}', PurchaseFailureReason: {1}",product.definition.storeSpecificId, failureReason));}
    179.     }
    180.  
     
  2. Alzan

    Alzan

    Joined:
    Sep 2, 2012
    Posts:
    81
    After a few days of reading, and this post a few minutes ago, I found my silly mistake to be this line here:
    which should be written like so
    I figure this fixed it, as now I get a "Publisher can not buy own goods" error. Is there any way around this for testing purposes? The PlayerPrefs logic is still being used. There must be a better way out there.
     
  3. basavaraj_guled

    basavaraj_guled

    Joined:
    Nov 1, 2014
    Posts:
    4
    u just create another google account and then add it in the google play developers console as tester account then the same