예제 #1
0
    void Start()
    {
        instance = this;
        DontDestroyOnLoad(gameObject);
        if (UnityEngine.Resources.Load("unibillInventory.json") == null)
        {
            Debug.LogError("You must define your purchasable inventory within the inventory editor!");
            this.gameObject.SetActive(false);
            return;
        }

        // We must first hook up listeners to Unibill's events.
        Unibiller.onBillerReady           += onBillerReady;
        Unibiller.onTransactionsRestored  += onTransactionsRestored;
        Unibiller.onPurchaseFailed        += onFailed;
        Unibiller.onPurchaseCompleteEvent += onPurchased;
        Unibiller.onPurchaseDeferred      += onDeferred;

        // Now we're ready to initialise Unibill.
        Unibiller.Initialise();

        items = Unibiller.AllPurchasableItems;

        // iOS includes additional functionality around App receipts.
                #if UNITY_IOS
        var appleExtensions = Unibiller.getAppleExtensions();
        appleExtensions.onAppReceiptRefreshed += x => {
            Debug.Log(x);
            Debug.Log("Refreshed app receipt!");
        };
        appleExtensions.onAppReceiptRefreshFailed += () => {
            Debug.Log("Failed to refresh app receipt.");
        };
                #endif
    }
예제 #2
0
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
    {
        if (String.Equals(args.purchasedProduct.definition.id, IDNonConsumableNoAds, StringComparison.Ordinal))
        {
            InApp.NoAds();
        }
        else if (String.Equals(args.purchasedProduct.definition.id, IDConsumableCoins1000, StringComparison.Ordinal))
        {
            InApp.BuyCoins(1000);
        }
        else if (String.Equals(args.purchasedProduct.definition.id, IDConsumableCoins2000, StringComparison.Ordinal))
        {
            InApp.BuyCoins(2000);
        }
        else if (String.Equals(args.purchasedProduct.definition.id, IDConsumableCoins4000noads, StringComparison.Ordinal))
        {
            InApp.BuyCoins(4000);
            InApp.NoAds();
        }
        //else if (String.Equals(args.purchasedProduct.definition.id, IDConsumableCoins1000, StringComparison.Ordinal))
        //{
        //    InApp.BuyCoins(1000);
        //}
        //else if (String.Equals(args.purchasedProduct.definition.id, IDConsumableCoins10000, StringComparison.Ordinal))
        //{
        //    InApp.BuyCoins(10000);
        //}
        else
        {
            Debug.Log(string.Format("ProcessPurchase: FAIL. Unrecognized product: '{0}'", args.purchasedProduct.definition.id));
        }

        return(PurchaseProcessingResult.Complete);
    }
예제 #3
0
    // Restore purchases previously made by this customer. Some platforms automatically restore purchases, like Google.
    // Apple currently requires explicit purchase restoration for IAP, conditionally displaying a password prompt.
    public void RestorePurchases()
    {
        if (!IsInitialized())
        {
            Debug.Log("RestorePurchases FAIL. Not initialized.");
            return;
        }

        if (Application.platform == RuntimePlatform.IPhonePlayer ||
            Application.platform == RuntimePlatform.OSXPlayer)
        {
            Debug.Log("RestorePurchases started ...");

            // Fetch the Apple store-specific subsystem.
            var apple = m_StoreExtensionProvider.GetExtension <UnityEngine.Purchasing.IAppleExtensions>();
            // 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.
            apple.RestoreTransactions((result) =>
            {
                if (result)
                {
                    InApp.NoAds();
                }
                Debug.Log("RestorePurchases continuing: " + result + ". If no further messages, no purchases available to restore.");
            });
        }
        // Otherwise ...
        else
        {
            // We are not running on an Apple device. No work is necessary to restore purchases.
            Debug.Log("RestorePurchases FAIL. Not supported on this platform. Current = " + Application.platform);
        }
    }
    private void Start()
    {
        //Создаем экземпляр, передавая в конструктор текущик язык. На этом этапе уже подтянутся все дефолтные или сохраненные продукты с последними параметрами
        //InApp inApp = new InApp(TranslationLocale.de_DE);
        //InApp inApp = new InApp(TranslationLocale.en_US);
        InApp inApp = new InApp(TranslationLocale.ru_RU);

        // Работать с продуктами можно до начала инициализации
        List <IProduct> products = inApp.Product;

        foreach (var product in products)
        {
            // Берем параметры до инициализации и заполняем обьекты в ui
            string      id          = product.Id;
            string      title       = product.Title;
            string      description = product.Description;
            string      price       = product.Price;
            Sprite      icon        = product.Icon;
            ProductType productType = product.ProductType;

            var uiProduct = GameObject.Instantiate <GameObject>(ExampleProductItem, GridLayot.transform);
            uiProduct.gameObject.SetActive(true);

            Text   textTitle       = uiProduct.GetComponentsInChildren <Text>()[0];
            Text   textDescription = uiProduct.GetComponentsInChildren <Text>()[1];
            Text   textPrice       = uiProduct.GetComponentsInChildren <Text>()[2];
            Button buttonBuy       = uiProduct.GetComponentInChildren <Button>();
            Image  imageIcon       = uiProduct.GetComponentInChildren <Image>();

            textTitle.text       = title;
            textDescription.text = description;
            textPrice.text       = price;
            buttonBuy.onClick.AddListener(() =>
            {
                Debug.Log($"Начата покупка товара {product.Id}");
                //При начале покупки получаем обьект, благодаря котором можем следить за процессом и результатом покупки.
                //Перед началом покупки желательно проверить интернет-соединение (здесь опущено)
                IInAppProcess buyProcess = inApp.Buy(product.Id);
                StartCoroutine(PurchasingObserveCoroutine(buyProcess, product));
            });
            buttonBuy.interactable = inApp.IsInit && product.IsBuy == false;
            imageIcon.sprite       = icon;

            _productItems.Add(product.Id, uiProduct);
        }

        // Начинаем инициализацию. Перед ней желательно проверить состояние интернет-соединения (здесь опущено)
        // Получаем обьект IInappProcess, благодаря которому можем следить за процессом и результатом инициализации
        var initProcess = inApp.Inizialization();

        // следим за ходом через коррутину (можно другим способом, как вам удобней)
        StartCoroutine(InitInAppObserveCoroutione(initProcess, inApp));
    }
    private IEnumerator InitInAppObserveCoroutione(IInAppProcess process, InApp inApp)
    {
        yield return(new WaitForSecondsRealtime(1f)); // имитация соединения

        bool initSucces     = false;
        var  currentProcess = process;

        while (initSucces != true)
        {
            yield return(new WaitUntil(() => currentProcess.IsDone == true));

            if (currentProcess.Result == Result.Succes)
            {
                initSucces = true;
                RefreshAllUiProductItems(inApp.Product);
                Debug.Log("Инициализация прошла удачно!");
            }
            else
            {
                currentProcess = inApp.Inizialization();
                Debug.Log("Инициализация не пройдена. Перезапуск.");
            }
        }
    }
예제 #6
0
 /// <summary>
 /// Send a Push request. This call can perform the following:
 /// <list type="bullet"><item><description>Broadcast to all devices</description></item><item><description>Broadcast to one device type</description></item><item><description>Send to a targeted device</description></item><item><description>Broadcast to all devices with a different alert for each
 /// type</description></item></list></summary>
 /// <param name="alert">The message to be pushed</param>
 /// <param name="deviceTypes">use null for broadcast</param>
 /// <param name="deviceId">use null for broadcast or deviceTypes must contain 1
 /// element that distinguishes this deviceId</param>
 /// <param name="deviceAlerts">per device alert messages and extras</param>
 /// <param name="customAudience">a more specific way to choose the audience for the
 /// push. If this is set, deviceId is ignored</param>
 /// <param name="inAppMessage">optional in-app message object to be pushed</param>
 /// <returns>
 /// Service Response
 /// </returns>
 public PushResponse Push(string alert, IList <DeviceType> deviceTypes = null, string deviceId = null, IList <BaseAlert> deviceAlerts = null, Audience customAudience = null, InApp inAppMessage = null)
 {
     return(SendRequest(new PushRequest(CreatePush(alert, deviceTypes, deviceId, deviceAlerts, customAudience, inAppMessage), serviceModelConfig)));
 }
예제 #7
0
        /// <summary>
        /// Create a Push Object
        /// </summary>
        /// <param name="alert">Alert Text</param>
        /// <param name="deviceTypes">Device Types</param>
        /// <param name="deviceId">Singular Device ID</param>
        /// <param name="deviceAlerts">Device/Platform Specific Alerts</param>
        /// <param name="customAudience">Audience</param>
        /// <returns>A push object capable of representing the options provided.</returns>
        /// TODO: Move to DTOs?
        /// <exception cref="InvalidOperationException">when deviceId is not null, deviceTypes must contain 1 element which identifies the deviceId type</exception>
        /// <exception cref="ArgumentNullException">Linq source or predicate is null.</exception>
        /// <exception cref="ArgumentOutOfRangeException">index is not a valid index in the <see cref="T:System.Collections.Generic.IList`1" />.</exception>
        /// <exception cref="NotSupportedException">The property is set and the <see cref="T:System.Collections.Generic.IList`1" /> is read-only.</exception>
        public static Push CreatePush(string alert, IList <DeviceType> deviceTypes = null, string deviceId = null, IList <BaseAlert> deviceAlerts = null, Audience customAudience = null, InApp inApp = null)
        {
            var push = new Push()
            {
                Notification =
                    string.IsNullOrEmpty(alert) ?
                    null :
                    new Notification()
                {
                    DefaultAlert = alert
                },

                InApp = inApp
            };

            if (customAudience != null)
            {
                deviceId = null;

                push.Audience = customAudience;
            }

            if (deviceTypes != null)
            {
                push.DeviceTypes = deviceTypes;

                if (deviceId != null)
                {
                    if (deviceTypes.Count != 1)
                    {
                        throw new InvalidOperationException("when deviceId is not null, deviceTypes must contain 1 element which identifies the deviceId type");
                    }

                    var deviceType = deviceTypes[0];

                    switch (deviceType)
                    {
                    case DeviceType.Android:
                        push.SetAudience(AudienceType.Android, deviceId);
                        break;

                    case DeviceType.Ios:
                        push.SetAudience(AudienceType.Ios, deviceId);
                        break;

                    case DeviceType.Wns:
                        push.SetAudience(AudienceType.Windows, deviceId);
                        break;

                    case DeviceType.Mpns:
                        push.SetAudience(AudienceType.WindowsPhone, deviceId);
                        break;

                    case DeviceType.Blackberry:
                        push.SetAudience(AudienceType.Blackberry, deviceId);
                        break;
                    }
                }
            }

            if (deviceAlerts == null || deviceAlerts.Count <= 0)
            {
                return(push);
            }

            push.Notification.AndroidAlert      = (AndroidAlert)deviceAlerts.FirstOrDefault(x => x is AndroidAlert);
            push.Notification.IosAlert          = (IosAlert)deviceAlerts.FirstOrDefault(x => x is IosAlert);
            push.Notification.WindowsAlert      = (WindowsAlert)deviceAlerts.FirstOrDefault(x => x is WindowsAlert);
            push.Notification.WindowsPhoneAlert = (WindowsPhoneAlert)deviceAlerts.FirstOrDefault(x => x is WindowsPhoneAlert);
            push.Notification.BlackberryAlert   = (BlackberryAlert)deviceAlerts.FirstOrDefault(x => x is BlackberryAlert);

            return(push);
        }
예제 #8
0
    void OnGUI()
    {
        if (IsInApp) {

            m_styleEmpty.alignment = TextAnchor.MiddleRight;
            m_styleEmpty.fontSize = Screen.width/25;
            Rect RLabel = Rectangle(1f,0.05f,0,0f);
            if(Enum_inApp == InApp.Life){
                GUI.Label(RLabel,"You have " +PlayerPrefs.GetInt("Lifes") + " Life.", m_styleEmpty);
            }
            else if(Enum_inApp == InApp.Point){
                GUI.Label(RLabel,"You have " +PlayerPrefs.GetInt("Points") + " Point.", m_styleEmpty);
            }
            else if(Enum_inApp == InApp.amour){
                GUI.Label(RLabel,"You have " +PlayerPrefs.GetInt("Armour") + " Armour.", m_styleEmpty);
            }
            else if(Enum_inApp == InApp.invisible){
                GUI.Label(RLabel,"You have " +PlayerPrefs.GetInt("Invisible") + " Invisible Power.", m_styleEmpty);
            }
            Rect Rgroup = Rectangle(0f,0,0, .75f);
            Rgroup.width = 1.42f * Rgroup.height;
            Rgroup.x = (Screen.width/2) -(Rgroup.width/2);
            Rgroup.y = (Screen.height/2) - (Rgroup.height/2);
            GUI.BeginGroup(Rgroup, m_texIAPBG, m_styleEmpty);

            Rect R1 = Rectangle(0,0.005f, 0, .15f);
            R1.width = 1.76f * R1.height;
            float x = Rgroup.width - ((R1.width * 4) + (Screen.width * 0.01f));
            x= x/3;
            if(GUI.Button(R1,"", m_styleEmpty)){
                Enum_inApp = InApp.Life;
            }
            Rect R2 = R1;
            R2.x = R1.width + x;

            if(GUI.Button(R2,"", m_styleEmpty)){
                Enum_inApp = InApp.Point;
            }
            Rect R3 = R1;
            R3.x = (R1.width * 2) + (x * 2);
            if(GUI.Button(R3, "", m_styleEmpty)){
                Enum_inApp = InApp.amour;
            }

            Rect R4 = R1;
            R4.x = (R1.width * 3) + (x* 3);
            if(GUI.Button(R4,"", m_styleEmpty)){
                Enum_inApp = InApp.invisible;
            }

            Rect Rapi = Rectangle(0,R1.height,0, .45f);
            Rapi.width = 1.75f * Rapi.height;
            Rapi.x = (Rgroup.width/2) -(Rapi.width/2);
            Rapi.y = (Rgroup.height/2) - ((Rapi.height/2) + (Screen.width * 0.005f) - R1.height/2);

            Rect Rbuy = Rectangle(0,0,0, 0.08f);
            Rbuy.width = 2f * Rbuy.height;
            Rbuy.x = Rapi.width * 0.9f;
                Rbuy.y = Rapi.height * 0.5f;

            if(Enum_inApp == InApp.Life){
                GUI.DrawTexture(R1,m_texLifePresed);
                GUI.DrawTexture(R2,m_texPoints);
                GUI.DrawTexture(R3,m_texAmour);
                GUI.DrawTexture(R4,m_texInvisible);

                GUI.Label(Rapi,m_texIAPLife, m_styleEmpty);
                if(GUI.Button(Rbuy,"", m_styleEmpty )){
                    BuyClick(0, 15, "Lifes", 2);
                }

                Rbuy.y = Rbuy.y + Rapi.height * 0.26f;
                if(GUI.Button(Rbuy,"", m_styleEmpty)){
                    BuyClick(1, 16, "Lifes", 5);
                }

                Rbuy.y = Rbuy.y + Rapi.height * 0.26f;
                if(GUI.Button(Rbuy,"", m_styleEmpty)){
                    BuyClick(2, 17, "Lifes", 11);
                }

                Rbuy.y = Rbuy.y + Rapi.height * 0.26f;
                if(GUI.Button(Rbuy,"", m_styleEmpty)){
                    BuyClick(3, 18, "Lifes", 22);
                }
        //				for(int i = 0; i < 4 ; i++){
        //					if(GUI.Button(Rbuy,"", m_styleEmpty)){
        //						print("HH");
        //					}
        //					Rbuy.y = Rbuy.y + Rapi.height * 0.25f;
        //
        //				}
        //				for(int i = 0; i < 3 ; i++){
        //					if(GUI.Button(Rbuy,"", m_styleEmpty)){
        //						print("HH");
        //					}
        //					Rbuy.y = Rbuy.y + Rapi.height * 0.33f;
        //				}
            }
            else if(Enum_inApp == InApp.Point){

                GUI.DrawTexture(R1,m_texLife);
                GUI.DrawTexture(R2,m_texPointsPresed);
                GUI.DrawTexture(R3,m_texAmour);
                GUI.DrawTexture(R4,m_texInvisible);

                GUI.Label(Rapi,m_texIAPPoints, m_styleEmpty);

                if(GUI.Button(Rbuy,"", m_styleEmpty)){
                    BuyClick(4, 19, "Points", 200);
                }

                Rbuy.y = Rbuy.y + Rapi.height * 0.25f;
                if(GUI.Button(Rbuy,"", m_styleEmpty)){
                    BuyClick(5, 20, "Points", 500);
                }

                Rbuy.y = Rbuy.y + Rapi.height * 0.25f;
                if(GUI.Button(Rbuy,"", m_styleEmpty)){
                    BuyClick(6, 21, "Points", 1100);
                }

                Rbuy.y = Rbuy.y + Rapi.height * 0.25f;
                if(GUI.Button(Rbuy,"", m_styleEmpty)){
                    BuyClick(7, 22, "Points", 2300);
                }
            }
            else if(Enum_inApp == InApp.amour){

                GUI.DrawTexture(R1,m_texLife);
                GUI.DrawTexture(R2,m_texPoints);
                GUI.DrawTexture(R3,m_texAmourPresed);
                GUI.DrawTexture(R4,m_texInvisible);

                GUI.Label(Rapi,m_texIAPAmour, m_styleEmpty);
                Rbuy.y = Rapi.height * 0.55f;
                if(GUI.Button(Rbuy,"", m_styleEmpty)){
                    BuyClick(8, 23, "Armour",2);
                }
                    Rbuy.y = Rbuy.y + Rapi.height * 0.33f;
                if(GUI.Button(Rbuy,"", m_styleEmpty)){
                    BuyClick(9, 24, "Armour",5);
                }
                Rbuy.y = Rbuy.y + Rapi.height * 0.33f;
                if(GUI.Button(Rbuy,"", m_styleEmpty)){
                    BuyClick(10, 25, "Armour",11);
                }
            }
            else if(Enum_inApp == InApp.invisible){

                GUI.DrawTexture(R1,m_texLife);
                GUI.DrawTexture(R2,m_texPoints);
                GUI.DrawTexture(R3,m_texAmour);
                GUI.DrawTexture(R4,m_texInvisiblePresed);

                GUI.Label(Rapi,m_texIAPinvisible, m_styleEmpty);
                if(GUI.Button(Rbuy,"", m_styleEmpty)){
                    BuyClick(11, 26, "Invisible",2);
                }
                Rbuy.y = Rbuy.y + Rapi.height * 0.33f;
                if(GUI.Button(Rbuy,"", m_styleEmpty)){
                    BuyClick(12, 27, "Invisible",5);
                }
                Rbuy.y = Rbuy.y + Rapi.height * 0.33f;
                if(GUI.Button(Rbuy,"", m_styleEmpty)){
                    BuyClick(13, 28, "Invisible",11);
                }
            }
            GUI.EndGroup();
        }
    }