Advertisement
Guest User

Untitled

a guest
Mar 27th, 2016
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 12.77 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Purchasing;
  5.  
  6. // Placing the Purchaser class in the CompleteProject namespace allows it to interact with ScoreManager, one of the existing Survival Shooter scripts.
  7.  
  8.  
  9. // Deriving the Purchaser class from IStoreListener enables it to receive messages from Unity Purchasing.
  10. public class IAPUnity : MonoBehaviour, IStoreListener
  11. {
  12.     private static IStoreController m_StoreController;                                                                  // Reference to the Purchasing system.
  13.     private static IExtensionProvider m_StoreExtensionProvider;                                                         // Reference to store-specific Purchasing subsystems.
  14.  
  15.     // Product identifiers for all products capable of being purchased: "convenience" general identifiers for use with Purchasing, and their store-specific identifier counterparts
  16.     // for use with and outside of Unity Purchasing. Define store-specific identifiers also on each platform's publisher dashboard (iTunes Connect, Google Play Developer Console, etc.)
  17.  
  18.     private static string kProductIDConsumable = "consumable";                                                         // General handle for the consumable product.
  19.     private static string kProductIDNonConsumable = "nonconsumable";                                                  // General handle for the non-consumable product.
  20.     private static string kProductIDSubscription = "subscription";                                                   // General handle for the subscription product.
  21.     private static string coinsTenTousent = "10000 Coins";
  22.  
  23.     private static string kProductNameAppleConsumable = "com.unity3d.test.services.purchasing.consumable";             // Apple App Store identifier for the consumable product.
  24.     private static string kProductNameAppleNonConsumable = "com.unity3d.test.services.purchasing.nonconsumable";      // Apple App Store identifier for the non-consumable product.
  25.     private static string kProductNameAppleSubscription = "com.unity3d.test.services.purchasing.subscription";       // Apple App Store identifier for the subscription product.
  26.     private static string coinsTenTousentApple = "10000 Coins";
  27.  
  28.     private static string kProductNameGooglePlayConsumable = "com.unity3d.test.services.purchasing.consumable";        // Google Play Store identifier for the consumable product.
  29.     private static string kProductNameGooglePlayNonConsumable = "com.unity3d.test.services.purchasing.nonconsumable";     // Google Play Store identifier for the non-consumable product.
  30.     private static string kProductNameGooglePlaySubscription = "com.unity3d.test.services.purchasing.subscription";  // Google Play Store identifier for the subscription product.
  31.     private static string coinsTenTousentGooglePlay = "10000 Coins";
  32.  
  33.     private static string kProductNameWindowsConsumable = "args";
  34.     private static string coinsTenTousentWindows = "10000 Coins";
  35.  
  36.     void Start()
  37.     {
  38.         // If we haven't set up the Unity Purchasing reference
  39.         if (m_StoreController == null)
  40.         {
  41.             // Begin to configure our connection to Purchasing
  42.             InitializePurchasing();
  43.         }
  44.     }
  45.  
  46.     public void InitializePurchasing()
  47.     {
  48.         // If we have already connected to Purchasing ...
  49.         if (IsInitialized())
  50.         {
  51.             // ... we are done here.
  52.             return;
  53.         }
  54.  
  55.         // Create a builder, first passing in a suite of Unity provided stores.
  56.         var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
  57.  
  58.         // Add a product to sell / restore by way of its identifier, associating the general identifier with its store-specific identifiers.
  59.         builder.AddProduct(kProductIDConsumable, ProductType.Consumable, new IDs() { { kProductNameAppleConsumable, AppleAppStore.Name }, { kProductNameGooglePlayConsumable, GooglePlay.Name }, { kProductNameWindowsConsumable, WindowsPhone8.Name}, });// Continue adding the non-consumable product.
  60.         builder.AddProduct(kProductIDNonConsumable, ProductType.NonConsumable, new IDs() { { kProductNameAppleNonConsumable, AppleAppStore.Name }, { kProductNameGooglePlayNonConsumable, GooglePlay.Name }, });// And finish adding the subscription product.
  61.         builder.AddProduct(kProductIDSubscription, ProductType.Subscription, new IDs() { { kProductNameAppleSubscription, AppleAppStore.Name }, { kProductNameGooglePlaySubscription, GooglePlay.Name }, });// Kick off the remainder of the set-up with an asynchrounous call, passing the configuration and this class' instance. Expect a response either in OnInitialized or OnInitializeFailed.
  62.  
  63.         builder.AddProduct(coinsTenTousent, ProductType.Consumable, new IDs() { { coinsTenTousentApple, AppleAppStore.Name }, { coinsTenTousentGooglePlay, GooglePlay.Name }, { coinsTenTousentWindows, WindowsPhone8.Name }, });
  64.         UnityPurchasing.Initialize(this, builder);
  65.     }
  66.  
  67.  
  68.     private bool IsInitialized()
  69.     {
  70.         // Only say we are initialized if both the Purchasing references are set.
  71.         return m_StoreController != null && m_StoreExtensionProvider != null;
  72.     }
  73.  
  74.  
  75.     public void BuyConsumable()
  76.     {
  77.         // Buy the consumable product using its general identifier. Expect a response either through ProcessPurchase or OnPurchaseFailed asynchronously.
  78.         BuyProductID(kProductIDConsumable);
  79.     }
  80.  
  81.     public void BuyTenThousentCoins()
  82.     {
  83.         BuyProductID(coinsTenTousent);
  84.     }
  85.  
  86.  
  87.     public void BuyNonConsumable()
  88.     {
  89.         // Buy the non-consumable product using its general identifier. Expect a response either through ProcessPurchase or OnPurchaseFailed asynchronously.
  90.         BuyProductID(kProductIDNonConsumable);
  91.     }
  92.  
  93.  
  94.     public void BuySubscription()
  95.     {
  96.         // Buy the subscription product using its the general identifier. Expect a response either through ProcessPurchase or OnPurchaseFailed asynchronously.
  97.         BuyProductID(kProductIDSubscription);
  98.     }
  99.  
  100.  
  101.     void BuyProductID(string productId)
  102.     {
  103.         // If the stores throw an unexpected exception, use try..catch to protect my logic here.
  104.         try
  105.         {
  106.             // If Purchasing has been initialized ...
  107.             if (IsInitialized())
  108.             {
  109.                 // ... look up the Product reference with the general product identifier and the Purchasing system's products collection.
  110.                 Product product = m_StoreController.products.WithID(productId);
  111.  
  112.                 // If the look up found a product for this device's store and that product is ready to be sold ...
  113.                 if (product != null && product.availableToPurchase)
  114.                 {
  115.                     Debug.print(string.Format("Purchasing product asychronously: '{0}'", product.definition.id));// ... buy the product. Expect a response either through ProcessPurchase or OnPurchaseFailed asynchronously.
  116.                     m_StoreController.InitiatePurchase(product);
  117.                 }
  118.                 // Otherwise ...
  119.                 else
  120.                 {
  121.                     // ... report the product look-up failure situation  
  122.                     Debug.print("BuyProductID: FAIL. Not purchasing product, either is not found or is not available for purchase");
  123.                 }
  124.             }
  125.             // Otherwise ...
  126.             else
  127.             {
  128.                 // ... report the fact Purchasing has not succeeded initializing yet. Consider waiting longer or retrying initiailization.
  129.                 Debug.print("BuyProductID FAIL. Not initialized.");
  130.             }
  131.         }
  132.         // Complete the unexpected exception handling ...
  133.         catch (Exception e)
  134.         {
  135.             // ... by reporting any unexpected exception for later diagnosis.
  136.             Debug.print("BuyProductID: FAIL. Exception during purchase. " + e);
  137.         }
  138.     }
  139.  
  140.  
  141.     // Restore purchases previously made by this customer. Some platforms automatically restore purchases. Apple currently requires explicit purchase restoration for IAP.
  142.     public void RestorePurchases()
  143.     {
  144.         // If Purchasing has not yet been set up ...
  145.         if (!IsInitialized())
  146.         {
  147.             // ... report the situation and stop restoring. Consider either waiting longer, or retrying initialization.
  148.             Debug.print("RestorePurchases FAIL. Not initialized.");
  149.             return;
  150.         }
  151.  
  152.         // If we are running on an Apple device ...
  153.         if (Application.platform == RuntimePlatform.IPhonePlayer ||
  154.             Application.platform == RuntimePlatform.OSXPlayer)
  155.         {
  156.             // ... begin restoring purchases
  157.             Debug.print("RestorePurchases started ...");
  158.  
  159.             // Fetch the Apple store-specific subsystem.
  160.             var apple = m_StoreExtensionProvider.GetExtension<IAppleExtensions>();
  161.             // 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.
  162.             apple.RestoreTransactions((result) =>
  163.             {
  164.                 // The first phase of restoration. If no more responses are received on ProcessPurchase then no purchases are available to be restored.
  165.                 Debug.print("RestorePurchases continuing: " + result + ". If no further messages, no purchases available to restore.");
  166.             });
  167.         }
  168.         // Otherwise ...
  169.         else
  170.         {
  171.             // We are not running on an Apple device. No work is necessary to restore purchases.
  172.             Debug.print("RestorePurchases FAIL. Not supported on this platform. Current = " + Application.platform);
  173.         }
  174.     }
  175.  
  176.  
  177.     //  
  178.     // --- IStoreListener
  179.     //
  180.  
  181.     public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
  182.     {
  183.         // Purchasing has succeeded initializing. Collect our Purchasing references.
  184.         Debug.print("OnInitialized: PASS");
  185.  
  186.         // Overall Purchasing system, configured with products for this application.
  187.         m_StoreController = controller;
  188.         // Store specific subsystem, for accessing device-specific store features.
  189.         m_StoreExtensionProvider = extensions;
  190.     }
  191.  
  192.  
  193.     public void OnInitializeFailed(InitializationFailureReason error)
  194.     {
  195.         // Purchasing set-up has not succeeded. Check error for reason. Consider sharing this reason with the user.
  196.         Debug.print("OnInitializeFailed InitializationFailureReason:" + error);
  197.     }
  198.  
  199.  
  200.     public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
  201.     {
  202.         // A consumable product has been purchased by this user.
  203.         if (String.Equals(args.purchasedProduct.definition.id, kProductIDConsumable, StringComparison.Ordinal))
  204.         {
  205.             Debug.print(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));//If the consumable item has been successfully purchased, add 100 coins to the player's in-game score.
  206.         }
  207.         else if (String.Equals(args.purchasedProduct.definition.id, coinsTenTousent, StringComparison.Ordinal))
  208.         {
  209.             Debug.print("yay coins");
  210.         }
  211.  
  212.         // Or ... a non-consumable product has been purchased by this user.
  213.         else if (String.Equals(args.purchasedProduct.definition.id, kProductIDNonConsumable, StringComparison.Ordinal))
  214.         {
  215.             Debug.print(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));
  216.         }// Or ... a subscription product has been purchased by this user.
  217.         else if (String.Equals(args.purchasedProduct.definition.id, kProductIDSubscription, StringComparison.Ordinal))
  218.         {
  219.             Debug.print(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));
  220.         }// Or ... an unknown product has been purchased by this user. Fill in additional products here.
  221.         else
  222.         {
  223.             Debug.print(string.Format("ProcessPurchase: FAIL. Unrecognized product: '{0}'", args.purchasedProduct.definition.id));
  224.         }// 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.
  225.         return PurchaseProcessingResult.Complete;
  226.     }
  227.  
  228.  
  229.     public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
  230.     {
  231.         // A product purchase attempt did not succeed. Check failureReason for more detail. Consider sharing this reason with the user.
  232.         Debug.print(string.Format("OnPurchaseFailed: FAIL. Product: '{0}', PurchaseFailureReason: {1}", product.definition.storeSpecificId, failureReason));
  233.     }
  234. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement