Advertisement
Guest User

Purchaser Script

a guest
Aug 5th, 2017
440
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 10.30 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Purchasing;
  5.  
  6.  
  7. // Placing the Purchaser class in the CompleteProject namespace allows it to interact with ScoreManager,
  8. // one of the existing Survival Shooter scripts.
  9. namespace CompleteProject
  10. {
  11.     // Deriving the Purchaser class from IStoreListener enables it to receive messages from Unity Purchasing.
  12.     public class Purchaser : MonoBehaviour, IStoreListener
  13.     {
  14.         private static IStoreController m_StoreController;          // The Unity Purchasing system.
  15.         private static IExtensionProvider m_StoreExtensionProvider; // The store-specific Purchasing subsystems.
  16.  
  17.         // Product identifiers for all products capable of being purchased:
  18.         // "convenience" general identifiers for use with Purchasing, and their store-specific identifier
  19.         // counterparts for use with and outside of Unity Purchasing. Define store-specific identifiers
  20.         // also on each platform's publisher dashboard (iTunes Connect, Google Play Developer Console, etc.)
  21.  
  22.         // General product identifiers for the consumable, non-consumable, and subscription products.
  23.         // Use these handles in the code to reference which product to purchase. Also use these values
  24.         // when defining the Product Identifiers on the store. Except, for illustration purposes, the
  25.         // kProductIDSubscription - it has custom Apple and Google identifiers. We declare their store-
  26.         // specific mapping to Unity Purchasing's AddProduct, below.
  27.         string rocket50 = "rocket.50";
  28.         string rocket51 = "rocket.51";
  29.         string rocket52 = "rocket.52";
  30.  
  31.         GameObject cameraScript;
  32.         void Start()
  33.         {
  34.             cameraScript = Camera.main.gameObject;
  35.             // If we haven't set up the Unity Purchasing reference
  36.             if (m_StoreController == null)
  37.             {
  38.                 // Begin to configure our connection to Purchasing
  39.                 InitializePurchasing();
  40.             }
  41.         }
  42.  
  43.         public void InitializePurchasing()
  44.         {
  45.             // If we have already connected to Purchasing ...
  46.             if (IsInitialized())
  47.             {
  48.                 // ... we are done here.
  49.                 return;
  50.             }
  51.  
  52.             // Create a builder, first passing in a suite of Unity provided stores.
  53.             var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
  54.  
  55.            
  56.             builder.AddProduct(rocket50, ProductType.NonConsumable);
  57.             builder.AddProduct(rocket51, ProductType.NonConsumable);
  58.             builder.AddProduct(rocket52, ProductType.NonConsumable);
  59.  
  60.             // Kick off the remainder of the set-up with an asynchrounous call, passing the configuration
  61.             // and this class' instance. Expect a response either in OnInitialized or OnInitializeFailed.
  62.             UnityPurchasing.Initialize(this, builder);
  63.         }
  64.  
  65.  
  66.         private bool IsInitialized()
  67.         {
  68.             // Only say we are initialized if both the Purchasing references are set.
  69.             return m_StoreController != null && m_StoreExtensionProvider != null;
  70.         }
  71.  
  72.  
  73.  
  74.  
  75.  
  76.         public void BuyProductID(string productId)
  77.         {
  78.             // If Purchasing has been initialized ...
  79.             if (IsInitialized())
  80.             {
  81.                 // ... look up the Product reference with the general product identifier and the Purchasing
  82.                 // system's products collection.
  83.                 Product product = m_StoreController.products.WithID(productId);
  84.  
  85.                 // If the look up found a product for this device's store and that product is ready to be sold ...
  86.                 if (product != null && product.availableToPurchase)
  87.                 {
  88.                     Debug.Log(string.Format("Purchasing product asychronously: '{0}'", product.definition.id));
  89.                     // ... buy the product. Expect a response either through ProcessPurchase or OnPurchaseFailed
  90.                     // asynchronously.
  91.                     m_StoreController.InitiatePurchase(product);
  92.                 }
  93.                 // Otherwise ...
  94.                 else
  95.                 {
  96.                     // ... report the product look-up failure situation  
  97.                     Debug.Log("BuyProductID: FAIL. Not purchasing product, either is not found or is not available for purchase");
  98.                 }
  99.             }
  100.             // Otherwise ...
  101.             else
  102.             {
  103.                 // ... report the fact Purchasing has not succeeded initializing yet. Consider waiting longer or
  104.                 // retrying initiailization.
  105.                 Debug.Log("BuyProductID FAIL. Not initialized.");
  106.             }
  107.         }
  108.  
  109.  
  110.         // Restore purchases previously made by this customer. Some platforms automatically restore purchases, like Google.
  111.         // Apple currently requires explicit purchase restoration for IAP, conditionally displaying a password prompt.
  112.         public void RestorePurchases()
  113.         {
  114.             // If Purchasing has not yet been set up ...
  115.             if (!IsInitialized())
  116.             {
  117.                 // ... report the situation and stop restoring. Consider either waiting longer, or retrying initialization.
  118.                 Debug.Log("RestorePurchases FAIL. Not initialized.");
  119.                 return;
  120.             }
  121.  
  122.             // If we are running on an Apple device ...
  123.             if (Application.platform == RuntimePlatform.IPhonePlayer ||
  124.                 Application.platform == RuntimePlatform.OSXPlayer)
  125.             {
  126.                 // ... begin restoring purchases
  127.                 Debug.Log("RestorePurchases started ...");
  128.  
  129.                 // Fetch the Apple store-specific subsystem.
  130.                 var apple = m_StoreExtensionProvider.GetExtension<IAppleExtensions>();
  131.                 // Begin the asynchronous process of restoring purchases. Expect a confirmation response in
  132.                 // the Action<bool> below, and ProcessPurchase if there are previously purchased products to restore.
  133.                 apple.RestoreTransactions((result) => {
  134.                     // The first phase of restoration. If no more responses are received on ProcessPurchase then
  135.                     // no purchases are available to be restored.
  136.                     Debug.Log("RestorePurchases continuing: " + result + ". If no further messages, no purchases available to restore.");
  137.                 });
  138.             }
  139.             // Otherwise ...
  140.             else
  141.             {
  142.                 // We are not running on an Apple device. No work is necessary to restore purchases.
  143.                 Debug.Log("RestorePurchases FAIL. Not supported on this platform. Current = " + Application.platform);
  144.             }
  145.         }
  146.  
  147.  
  148.         //  
  149.         // --- IStoreListener
  150.         //
  151.  
  152.         public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
  153.         {
  154.             // Purchasing has succeeded initializing. Collect our Purchasing references.
  155.             Debug.Log("OnInitialized: PASS");
  156.  
  157.             // Overall Purchasing system, configured with products for this application.
  158.             m_StoreController = controller;
  159.             // Store specific subsystem, for accessing device-specific store features.
  160.             m_StoreExtensionProvider = extensions;
  161.         }
  162.  
  163.  
  164.         public void OnInitializeFailed(InitializationFailureReason error)
  165.         {
  166.             // Purchasing set-up has not succeeded. Check error for reason. Consider sharing this reason with the user.
  167.             Debug.Log("OnInitializeFailed InitializationFailureReason:" + error);
  168.         }
  169.  
  170.  
  171.         public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
  172.         {
  173.  
  174.             // Or ... a non-consumable product has been purchased by this user.
  175.             if (String.Equals(args.purchasedProduct.definition.id, rocket50, StringComparison.Ordinal))
  176.             {
  177.                 Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));
  178.                 // TODO: The non-consumable item has been successfully purchased, grant this item to the player.
  179.                 cameraScript.GetComponent<menu_camera>().purchaseRocket(50);
  180.             }
  181.             else if (String.Equals(args.purchasedProduct.definition.id, rocket51, StringComparison.Ordinal))
  182.             {
  183.                 Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));
  184.                 // TODO: The non-consumable item has been successfully purchased, grant this item to the player.
  185.                 cameraScript.GetComponent<menu_camera>().purchaseRocket(51);
  186.             }
  187.             else if (String.Equals(args.purchasedProduct.definition.id, rocket52, StringComparison.Ordinal))
  188.             {
  189.                 Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));
  190.                 // TODO: The non-consumable item has been successfully purchased, grant this item to the player.
  191.                 cameraScript.GetComponent<menu_camera>().purchaseRocket(52);
  192.             }
  193.             // Or ... an unknown product has been purchased by this user. Fill in additional products here....
  194.             else
  195.             {
  196.                 Debug.Log(string.Format("ProcessPurchase: FAIL. Unrecognized product: '{0}'", args.purchasedProduct.definition.id));
  197.             }
  198.  
  199.             // Return a flag indicating whether this product has completely been received, or if the application needs
  200.             // to be reminded of this purchase at next app launch. Use PurchaseProcessingResult.Pending when still
  201.             // saving purchased products to the cloud, and when that save is delayed.
  202.             return PurchaseProcessingResult.Complete;
  203.         }
  204.  
  205.  
  206.         public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
  207.         {
  208.             // A product purchase attempt did not succeed. Check failureReason for more detail. Consider sharing
  209.             // this reason with the user to guide their troubleshooting actions.
  210.             Debug.Log(string.Format("OnPurchaseFailed: FAIL. Product: '{0}', PurchaseFailureReason: {1}", product.definition.storeSpecificId, failureReason));
  211.         }
  212.     }
  213. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement