Advertisement
Guest User

Untitled

a guest
Nov 22nd, 2019
449
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 13.94 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,
  7. // one of the existing Survival Shooter scripts.
  8. namespace CompleteProject
  9. {
  10.     // Deriving the Purchaser class from IStoreListener enables it to receive messages from Unity Purchasing.
  11.     public class Purchaser : MonoBehaviour, IStoreListener
  12.     {
  13.         private static IStoreController m_StoreController;          // The Unity Purchasing system.
  14.         private static IExtensionProvider m_StoreExtensionProvider; // The store-specific Purchasing subsystems.
  15.  
  16.         // Product identifiers for all products capable of being purchased:
  17.         // "convenience" general identifiers for use with Purchasing, and their store-specific identifier
  18.         // counterparts for use with and outside of Unity Purchasing. Define store-specific identifiers
  19.         // also on each platform's publisher dashboard (iTunes Connect, Google Play Developer Console, etc.)
  20.  
  21.         // General product identifiers for the consumable, non-consumable, and subscription products.
  22.         // Use these handles in the code to reference which product to purchase. Also use these values
  23.         // when defining the Product Identifiers on the store. Except, for illustration purposes, the
  24.         // kProductIDSubscription - it has custom Apple and Google identifiers. We declare their store-
  25.         // specific mapping to Unity Purchasing's AddProduct, below.
  26.         public static string kProductIDConsumable = "consumable";
  27.         public static string NO_ADS = "nonconsumable";
  28.         public static string kProductIDSubscription = "subscription";
  29.         public GameObject Restore;
  30.         public GameObject NoAdsButton;
  31.         public GameObject Premium;
  32.         public GameObject ShopButton;
  33.  
  34.         // Apple App Store-specific product identifier for the subscription product.
  35.         private static string kProductNameAppleSubscription = "com.unity3d.subscription.new";
  36.  
  37.         // Google Play Store-specific product identifier subscription product.
  38.         private static string kProductNameGooglePlaySubscription = "com.unity3d.subscription.original";
  39.  
  40.         void Start()
  41.         {
  42.             if (Application.platform != RuntimePlatform.IPhonePlayer)
  43.             {
  44.                 Restore.SetActive(false);
  45.             }
  46.            
  47.            
  48.             if (PlayerPrefs.GetInt("NoAds") == 1)
  49.             {
  50.                 NoAdsButton.SetActive(false);
  51.             }
  52.             if (PlayerPrefs.GetInt("ProVersion") == 1)
  53.             {
  54.                 Premium.SetActive(false);
  55.             }
  56.             // If we haven't set up the Unity Purchasing reference
  57.             if (m_StoreController == null)
  58.             {
  59.                 // Begin to configure our connection to Purchasing
  60.                 InitializePurchasing();
  61.             }
  62.             if (!Restore.activeSelf && !NoAdsButton.activeSelf && !Premium.activeSelf)
  63.             {
  64.                 ShopButton.SetActive(false);
  65.             }
  66.         }
  67.         public void InitializePurchasing()
  68.         {
  69.             // If we have already connected to Purchasing ...
  70.             if (IsInitialized())
  71.             {
  72.                 // ... we are done here.
  73.                 return;
  74.             }
  75.  
  76.             // Create a builder, first passing in a suite of Unity provided stores.
  77.             var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
  78.  
  79.             // Add a product to sell / restore by way of its identifier, associating the general identifier
  80.             // with its store-specific identifiers.
  81.             builder.AddProduct(kProductIDConsumable, ProductType.Consumable);
  82.             // Continue adding the non-consumable product.
  83.             builder.AddProduct(NO_ADS, ProductType.NonConsumable);
  84.             // And finish adding the subscription product. Notice this uses store-specific IDs, illustrating
  85.             // if the Product ID was configured differently between Apple and Google stores. Also note that
  86.             // one uses the general kProductIDSubscription handle inside the game - the store-specific IDs
  87.             // must only be referenced here.
  88.             builder.AddProduct(kProductIDSubscription, ProductType.Subscription, new IDs(){
  89.                 { kProductNameAppleSubscription, AppleAppStore.Name },
  90.                 { kProductNameGooglePlaySubscription, GooglePlay.Name },
  91.             });
  92.  
  93.             // Kick off the remainder of the set-up with an asynchrounous call, passing the configuration
  94.             // and this class' instance. Expect a response either in OnInitialized or OnInitializeFailed.
  95.             UnityPurchasing.Initialize(this, builder);
  96.         }
  97.  
  98.  
  99.         private bool IsInitialized()
  100.         {
  101.             // Only say we are initialized if both the Purchasing references are set.
  102.             return m_StoreController != null && m_StoreExtensionProvider != null;
  103.         }
  104.  
  105.  
  106.         public void BuyConsumable()
  107.         {
  108.             // Buy the consumable product using its general identifier. Expect a response either
  109.             // through ProcessPurchase or OnPurchaseFailed asynchronously.
  110.             BuyProductID(kProductIDConsumable);
  111.         }
  112.  
  113.  
  114.         public void BuyNonConsumable()
  115.         {
  116.             // Buy the non-consumable product using its general identifier. Expect a response either
  117.             // through ProcessPurchase or OnPurchaseFailed asynchronously.
  118.             BuyProductID(NO_ADS);
  119.         }
  120.  
  121.  
  122.         public void BuySubscription()
  123.         {
  124.             // Buy the subscription product using its the general identifier. Expect a response either
  125.             // through ProcessPurchase or OnPurchaseFailed asynchronously.
  126.             // Notice how we use the general product identifier in spite of this ID being mapped to
  127.             // custom store-specific identifiers above.
  128.             BuyProductID(kProductIDSubscription);
  129.         }
  130.  
  131.  
  132.         void BuyProductID(string productId)
  133.         {
  134.             // If Purchasing has been initialized ...
  135.             if (IsInitialized())
  136.             {
  137.                 // ... look up the Product reference with the general product identifier and the Purchasing
  138.                 // system's products collection.
  139.                 Product product = m_StoreController.products.WithID(productId);
  140.  
  141.                 // If the look up found a product for this device's store and that product is ready to be sold ...
  142.                 if (product != null && product.availableToPurchase)
  143.                 {
  144.                     Debug.Log(string.Format("Purchasing product asychronously: '{0}'", product.definition.id));
  145.                     // ... buy the product. Expect a response either through ProcessPurchase or OnPurchaseFailed
  146.                     // asynchronously.
  147.                     m_StoreController.InitiatePurchase(product);
  148.                 }
  149.                 // Otherwise ...
  150.                 else
  151.                 {
  152.                     // ... report the product look-up failure situation  
  153.                     Debug.Log("BuyProductID: FAIL. Not purchasing product, either is not found or is not available for purchase");
  154.                 }
  155.             }
  156.             // Otherwise ...
  157.             else
  158.             {
  159.                 // ... report the fact Purchasing has not succeeded initializing yet. Consider waiting longer or
  160.                 // retrying initiailization.
  161.                 Debug.Log("BuyProductID FAIL. Not initialized.");
  162.             }
  163.         }
  164.  
  165.  
  166.         // Restore purchases previously made by this customer. Some platforms automatically restore purchases, like Google.
  167.         // Apple currently requires explicit purchase restoration for IAP, conditionally displaying a password prompt.
  168.         public void RestorePurchases()
  169.         {
  170.             // If Purchasing has not yet been set up ...
  171.             if (!IsInitialized())
  172.             {
  173.                 // ... report the situation and stop restoring. Consider either waiting longer, or retrying initialization.
  174.                 Debug.Log("RestorePurchases FAIL. Not initialized.");
  175.                 return;
  176.             }
  177.  
  178.             // If we are running on an Apple device ...
  179.             if (Application.platform == RuntimePlatform.IPhonePlayer ||
  180.                 Application.platform == RuntimePlatform.OSXPlayer)
  181.             {
  182.                 // ... begin restoring purchases
  183.                 Debug.Log("RestorePurchases started ...");
  184.  
  185.                 // Fetch the Apple store-specific subsystem.
  186.                 var apple = m_StoreExtensionProvider.GetExtension<IAppleExtensions>();
  187.                 // Begin the asynchronous process of restoring purchases. Expect a confirmation response in
  188.                 // the Action<bool> below, and ProcessPurchase if there are previously purchased products to restore.
  189.                 apple.RestoreTransactions((result) => {
  190.                     // The first phase of restoration. If no more responses are received on ProcessPurchase then
  191.                     // no purchases are available to be restored.
  192.                     Debug.Log("RestorePurchases continuing: " + result + ". If no further messages, no purchases available to restore.");
  193.                 });
  194.             }
  195.             // Otherwise ...
  196.             else
  197.             {
  198.                 // We are not running on an Apple device. No work is necessary to restore purchases.
  199.                 Debug.Log("RestorePurchases FAIL. Not supported on this platform. Current = " + Application.platform);
  200.             }
  201.         }
  202.  
  203.  
  204.         //  
  205.         // --- IStoreListener
  206.         //
  207.  
  208.         public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
  209.         {
  210.             // Purchasing has succeeded initializing. Collect our Purchasing references.
  211.             Debug.Log("OnInitialized: PASS");
  212.  
  213.             // Overall Purchasing system, configured with products for this application.
  214.             m_StoreController = controller;
  215.             // Store specific subsystem, for accessing device-specific store features.
  216.             m_StoreExtensionProvider = extensions;
  217.         }
  218.  
  219.  
  220.         public void OnInitializeFailed(InitializationFailureReason error)
  221.         {
  222.             // Purchasing set-up has not succeeded. Check error for reason. Consider sharing this reason with the user.
  223.             Debug.Log("OnInitializeFailed InitializationFailureReason:" + error);
  224.         }
  225.  
  226.  
  227.         public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
  228.         {
  229.             // A consumable product has been purchased by this user.
  230.             if (String.Equals(args.purchasedProduct.definition.id, kProductIDConsumable, StringComparison.Ordinal))
  231.             {
  232.                 Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));
  233.                 // The consumable item has been successfully purchased, add 100 coins to the player's in-game score.
  234.                // ScoreManager.score += 100;
  235.             }
  236.             // Or ... a non-consumable product has been purchased by this user.
  237.             else if (String.Equals(args.purchasedProduct.definition.id, NO_ADS, StringComparison.Ordinal))
  238.             {
  239.                 NoAdsButton.SetActive(false);
  240.                 PlayerPrefs.SetInt("NoAds", 1);
  241.                 if (!Restore.activeSelf && !NoAdsButton.activeSelf && !Premium.activeSelf)
  242.                 {
  243.                     ShopButton.SetActive(false);
  244.                 }
  245.                 Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));
  246.                 // TODO: The non-consumable item has been successfully purchased, grant this item to the player.
  247.             }
  248.             // Or ... a subscription product has been purchased by this user.
  249.             else if (String.Equals(args.purchasedProduct.definition.id, kProductIDSubscription, StringComparison.Ordinal))
  250.             {
  251.                 PlayerPrefs.SetInt("UnlockEyes", 65534);
  252.                 PlayerPrefs.SetInt("UnlockHat", 510);
  253.                 NoAdsButton.SetActive(false);
  254.                 Premium.SetActive(false);
  255.                 PlayerPrefs.SetInt("NoAds", 1);
  256.                 PlayerPrefs.SetInt("ProVersion", 1);
  257.                 if (!Restore.activeSelf && !NoAdsButton.activeSelf && !Premium.activeSelf)
  258.                 {
  259.                     ShopButton.SetActive(false);
  260.                 }
  261.                 Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));
  262.                 // TODO: The subscription item has been successfully purchased, grant this to the player.
  263.             }
  264.             // Or ... an unknown product has been purchased by this user. Fill in additional products here....
  265.             else
  266.             {
  267.                 //NoAdsButton.SetActive(true);
  268.                 //PlayerPrefs.SetInt("NoAds", 0);
  269.                 Debug.Log(string.Format("ProcessPurchase: FAIL. Unrecognized product: '{0}'", args.purchasedProduct.definition.id));
  270.             }
  271.  
  272.             // Return a flag indicating whether this product has completely been received, or if the application needs
  273.             // to be reminded of this purchase at next app launch. Use PurchaseProcessingResult.Pending when still
  274.             // saving purchased products to the cloud, and when that save is delayed.
  275.             return PurchaseProcessingResult.Complete;
  276.         }
  277.  
  278.  
  279.         public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
  280.         {
  281.             // A product purchase attempt did not succeed. Check failureReason for more detail. Consider sharing
  282.             // this reason with the user to guide their troubleshooting actions.
  283.             Debug.Log(string.Format("OnPurchaseFailed: FAIL. Product: '{0}', PurchaseFailureReason: {1}", product.definition.storeSpecificId, failureReason));
  284.         }
  285.     }
  286. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement