public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
    {
        // A consumable product has been purchased by this user.
        if (String.Equals(args.purchasedProduct.definition.id, kProductIDConsumable, StringComparison.Ordinal))
        {
            //Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));
            statusText = "ProcessPurchase: PASS. Product: " + args.purchasedProduct.definition.id;
        }
        else
        {
            //Debug.Log(string.Format("ProcessPurchase: FAIL. Unrecognized product: '{0}'", args.purchasedProduct.definition.id));
            statusText = "ProcessPurchase: FAIL. Unrecognized product: " + args.purchasedProduct.definition.id;
        }

        wrapper   = (Dictionary <string, object>)MiniJson.JsonDecode(args.purchasedProduct.receipt);
        store     = (string)wrapper["Store"];
        payload   = (string)wrapper["Payload"];
        gpDetails = (Dictionary <string, object>)MiniJson.JsonDecode(payload);
        gpJson    = (string)gpDetails["json"];
        gpSig     = (string)gpDetails["signature"];

        // Return a flag indicating whether this product has completely been received, or if the application needs
        // to be reminded of this purchase at next app launch. Use PurchaseProcessingResult.Pending when still
        // saving purchased products to the cloud, and when that save is delayed.
        return(PurchaseProcessingResult.Complete);
    }
Пример #2
0
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
    {
        string prodID   = args.purchasedProduct.definition.id;
        string price    = args.purchasedProduct.metadata.localizedPriceString;
        string regPrice = Regex.Replace(price, "[^0-9 /.]", "");
        string currency = args.purchasedProduct.metadata.isoCurrencyCode;

        Dictionary <string, string> myDict = new Dictionary <string, string>();

        string receipt       = args.purchasedProduct.receipt;
        var    recptToJSON   = (Dictionary <string, object>)MiniJson.JsonDecode(args.purchasedProduct.receipt);
        var    transactionID = (string)recptToJSON["TransactionID"];

        if (String.Equals(args.purchasedProduct.definition.id, kProductIDConsumable, StringComparison.Ordinal))
        {
            Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));

            afiosValidate(prodID, regPrice, currency, transactionID, myDict);
        }
        else
        {
            Debug.Log(string.Format("ProcessPurchase: FAIL. Unrecognized product: '{0}'", args.purchasedProduct.definition.id));
        }


        return(PurchaseProcessingResult.Complete);
    }
        public GooglePlayReceipt Validate(string receipt, string signature)
        {
            var rawReceipt   = System.Text.Encoding.UTF8.GetBytes(receipt);           // "{\"orderId\":\"G...
            var rawSignature = System.Convert.FromBase64String(signature);

            if (!key.Verify(rawReceipt, rawSignature))
            {
                throw new InvalidSignatureException();
            }

            var    dic = (Dictionary <string, object>)MiniJson.JsonDecode(receipt);
            object orderID, packageName, productId, purchaseToken, purchaseTime, purchaseState;

            dic.TryGetValue("orderId", out orderID);
            dic.TryGetValue("packageName", out packageName);
            dic.TryGetValue("productId", out productId);
            dic.TryGetValue("purchaseToken", out purchaseToken);
            dic.TryGetValue("purchaseTime", out purchaseTime);
            dic.TryGetValue("purchaseState", out purchaseState);

            // Google specifies times in milliseconds since 1970.
            var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            // NOTE: to safely handle null values for these fields, using Convert.ToDouble & ToInt32 in place of casts
            var time  = epoch.AddMilliseconds(Convert.ToDouble(purchaseTime));
            var state = (GooglePurchaseState)Convert.ToInt32(purchaseState);

            return(new GooglePlayReceipt((string)productId, (string)orderID, (string)orderID, (string)packageName,
                                         (string)purchaseToken, time, state));
        }
Пример #4
0
 protected virtual void Refresh()
 {
     Debug.Log($"StencilProductState: Refresh {productId}");
     productId = product.definition.id;
     CheckNotNull(productId, "Product ID");
     price        = decimal.ToDouble(product.metadata.localizedPrice);
     currencyCode = product.metadata?.isoCurrencyCode;
     if (currencyCode == null)
     {
         currencyCode = "USD";
         var price = product.metadata?.localizedPriceString ?? "UNKNOWN";
         Tracking.Instance
         .Track("null_currency_code", "product", productId, "price", price)
         .SetUserProperty("null_currency_code", true);
         Tracking.LogException(new Exception($"Null Currency: {productId} - {price}"));
     }
     if (product.receipt == null)
     {
         Debug.Log($"StencilProductState: No Receipt {productId}");
         wrapper      = null;
         payload      = null;
         subscription = null;
         return;
     }
     wrapper = (Dictionary <string, object>)MiniJson.JsonDecode(product.receipt);
     payload = (string)wrapper["Payload"];
     if (product.definition.type == ProductType.Subscription)
     {
         subscription = new StencilSubscriptionState(product);
     }
 }
Пример #5
0
        //购买成功后的回调,包括restore的商品
        public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
        {
            string productID = args.purchasedProduct.definition.id;
            //onBuyProductCallBcak.Call(true, args.purchasedProduct.transactionID, args.purchasedProduct.receipt);
            //Debug.Log("IAP:" + args.purchasedProduct.receipt);
            //这里要取出receipt的数据给PHP做二次验证
            Dictionary <string, object> wrapper = (Dictionary <string, object>)MiniJson.JsonDecode(args.purchasedProduct.receipt);

            string store   = (string)wrapper["Store"];
            string payload = (string)wrapper["Payload"];

#if UNITY_EDITOR
            Debug.Log("IAP:" + args.purchasedProduct.receipt);
#elif UNITY_ANDROID
            Debug.Log("IAP receipt:" + args.purchasedProduct.receipt);

            Dictionary <string, object> gpDetails = (Dictionary <string, object>)MiniJson.JsonDecode(payload);

            string gpJson = (string)gpDetails["json"];
            string gpSig  = (string)gpDetails["signature"];
            string id     = args.purchasedProduct.definition.id;

            Debug.Log("IAP gpJson:" + gpJson);
            Debug.Log("IAP gpSig:" + gpSig);
            Debug.Log("IAP id:" + id);

            onBuyProductCallBcak.Call(true, gpJson, gpSig);
#elif UNITY_IPHONE
            onBuyProductCallBcak.Call();
#endif
            return(PurchaseProcessingResult.Complete);
        }
Пример #6
0
    /// <summary>
    /// 支付结果
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
    {
        //获取并解析你需要上传的数据。解析成string类型
        var wrapper = (Dictionary <string, object>)MiniJson.JsonDecode(e.purchasedProduct.receipt);

        if (null == wrapper)
        {
            return(PurchaseProcessingResult.Complete);
        }

        string store         = (string)wrapper["Store"];
        string transactionID = (string)wrapper["TransactionID"];
        string payload       = (string)wrapper["Payload"];

        mPayCallback(true, transactionID, payload);
        //VerifyTransactionResult(transactionID, payload);

        //For GooglePlay payload contains more JSON
        //if (Application.platform == RuntimePlatform.Android)
        //{
        //	var gpDetails = (Dictionary<string, object>)MiniJson.JsonDecode(payload);
        //	var gpJson = (string)gpDetails["json"];
        //	var gpSig = (string)gpDetails["signature"];

        //	//Google验证商品信息的数据包含在gpJson里面还需要在服务端进行解析一下,对应的键是"purchaseToken"。
        //	StartCoroutine(PostRepict("http://www.xxxxxxxxxxxxx/purchase/Andverifytrade", e.purchasedProduct.definition.id, gpJson));
        //}

        string logStr = "支付成功:" + JsonMapper.ToJson(e);

        Manager.log(logStr);
        return(PurchaseProcessingResult.Complete);
    }
Пример #7
0
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
    {
        //获取并解析你需要上传的数据。解析成string类型
        var wrapper = (Dictionary <string, object>)MiniJson.JsonDecode(e.purchasedProduct.receipt);

        if (null == wrapper)
        {
            return(PurchaseProcessingResult.Complete);
        }
        var store = (string)wrapper ["Store"];
        //下面的payload 即为IOS的验证商品信息的数据。即我们需要上传的部分。
        var payload       = (string)wrapper ["Payload"];   // For Apple this will be the base64 encoded ASN.1 receipt
        var pid           = e.purchasedProduct.definition.id;
        var transactionID = e.purchasedProduct.transactionID;

        int    purchaseType = 0;
        string receipt      = "";
        string udid         = OSUtility.GetOpenUDID();
        string signature    = "";

#if UNITY_IOS || UNITY_IPHONE
        purchaseType = 1;   //Apple Store  EPlatformType.EPlatformType_AppStore
        receipt      = payload;

        Debug.Log(string.Format("PID = {0} Payload = {1}", pid, receipt));
#elif UNITY_ANDROID
        purchaseType = 2;   //Google Play  EPlatformType.EPlatformType_GooglePlay

        var gpDetails = (Dictionary <string, object>)MiniJson.JsonDecode(payload);
        receipt   = (string)gpDetails["signature"];     // 服务器待验证 签名数据
        signature = (string)gpDetails["json"];          // 服务器待验证 订单信息
#endif

        //Write cache
        FileBilling.Instance.ReadFile();
        FileBilling.CReceiptInfo entry = new FileBilling.CReceiptInfo();
        entry.RoleId        = _roleId;
        entry.ProductId     = pid;
        entry.IsSucceed     = true;
        entry.BillingType   = purchaseType;
        entry.Receipt       = payload;
        entry.TransactionId = transactionID;
        FileBilling.Instance.Update(purchaseType, entry);
        FileBilling.Instance.WriteFile();

        // Post receipt for verify
        bool bPostSucceed = PostVerifyData(_roleId, _roleId, purchaseType, pid, transactionID, udid, receipt, signature, false, true);

        PURCHASE_INFO info = new PURCHASE_INFO();
        info.iBillingType     = purchaseType;
        info.strTransactionId = transactionID;
        info.strProductId     = pid;
        info.strReceipt       = receipt;
        _fnPurchaseCallback(true, info);

        return(PurchaseProcessingResult.Complete);
    }
        internal static string GetValueFromJsonDictionary(string rawJson, string key)
        {
            var container = (Dictionary <string, object>)MiniJson.JsonDecode(rawJson);

            object value;

            container.TryGetValue(key, out value);
            return(value as string);
        }
Пример #9
0
    private bool checkIfProductIsAvailableForSubscriptionManager(string receipt)
    {
        var receipt_wrapper = (Dictionary <string, object>)MiniJson.JsonDecode(receipt);

        if (!receipt_wrapper.ContainsKey("Store") || !receipt_wrapper.ContainsKey("Payload"))
        {
            Debug.Log("The product receipt does not contain enough information");
            return(false);
        }
        var store   = (string)receipt_wrapper ["Store"];
        var payload = (string)receipt_wrapper ["Payload"];

        if (payload != null)
        {
            switch (store)
            {
            case GooglePlay.Name:
            {
                var payload_wrapper = (Dictionary <string, object>)MiniJson.JsonDecode(payload);
                if (!payload_wrapper.ContainsKey("json"))
                {
                    Debug.Log("The product receipt does not contain enough information, the 'json' field is missing");
                    return(false);
                }
                var original_json_payload_wrapper =
                    (Dictionary <string, object>)MiniJson.JsonDecode((string)payload_wrapper["json"]);
                if (original_json_payload_wrapper == null || !original_json_payload_wrapper.ContainsKey("developerPayload"))
                {
                    Debug.Log("The product receipt does not contain enough information, the 'developerPayload' field is missing");
                    return(false);
                }
                var developerPayloadJSON     = (string)original_json_payload_wrapper["developerPayload"];
                var developerPayload_wrapper =
                    (Dictionary <string, object>)MiniJson.JsonDecode(developerPayloadJSON);
                if (developerPayload_wrapper == null || !developerPayload_wrapper.ContainsKey("is_free_trial") || !developerPayload_wrapper.ContainsKey("has_introductory_price_trial"))
                {
                    Debug.Log("The product receipt does not contain enough information, the product is not purchased using 1.19 or later");
                    return(false);
                }
                return(true);
            }

            case AppleAppStore.Name:
            case AmazonApps.Name:
            case MacAppStore.Name:
            {
                return(true);
            }

            default:
            {
                return(false);
            }
            }
        }
        return(false);
    }
Пример #10
0
    private bool IsSubscriptionAvailable(string receipt)
    {
        if (string.IsNullOrEmpty(receipt))
        {
            UnityEngine.Debug.Log("Subscription receipt is null");
            return(false);
        }
        Dictionary <string, object> dictionary = (Dictionary <string, object>)MiniJson.JsonDecode(receipt);

        if (!dictionary.ContainsKey("Store") || !dictionary.ContainsKey("Payload"))
        {
            UnityEngine.Debug.Log("The product receipt does not contain enough information");
            return(false);
        }
        string a    = (string)dictionary["Store"];
        string text = (string)dictionary["Payload"];

        if (text != null)
        {
            if (!(a == "GooglePlay"))
            {
                if (a == "AppleAppStore" || a == "AmazonApps" || a == "MacAppStore")
                {
                    return(true);
                }
                return(false);
            }
            Dictionary <string, object> dictionary2 = (Dictionary <string, object>)MiniJson.JsonDecode(text);
            if (!dictionary2.ContainsKey("json"))
            {
                UnityEngine.Debug.Log("The product receipt does not contain enough information, the 'json' field is missing");
                return(false);
            }
            Dictionary <string, object> dictionary3 = (Dictionary <string, object>)MiniJson.JsonDecode((string)dictionary2["json"]);
            if (dictionary3 == null || !dictionary3.ContainsKey("developerPayload"))
            {
                UnityEngine.Debug.Log("The product receipt does not contain enough information, the 'developerPayload' field is missing");
                return(false);
            }
            Dictionary <string, object> dictionary4 = (Dictionary <string, object>)MiniJson.JsonDecode((string)dictionary3["developerPayload"]);
            if (dictionary4 == null || !dictionary4.ContainsKey("is_free_trial") || !dictionary4.ContainsKey("has_introductory_price_trial"))
            {
                UnityEngine.Debug.Log("The product receipt does not contain enough information, the product is not purchased using 1.19 or later");
                return(false);
            }
            return(true);
        }
        return(false);
    }
        protected override void Refresh()
        {
            base.Refresh();
            if (payload == null)
            {
                return;
            }
            var gpDetails = (Dictionary <string, object>)MiniJson.JsonDecode(payload);

            CheckNotNull(gpDetails, "gpDetails");
            receipt = (string)gpDetails["json"];
            CheckNotNull(receipt, "gpJson");
            signature = (string)gpDetails["signature"];
            CheckNotNull(signature, "gpSig");
        }
Пример #12
0
    // Check if the obfuscated account id on the receipt is same as the one on the device.
    private static void ObfuscatedAccountIdValidation(string unityIapReceipt)
    {
        Dictionary <string, object> unityIapReceiptDictionary =
            (Dictionary <string, object>)MiniJson.JsonDecode(unityIapReceipt);
        string payload = (string)unityIapReceiptDictionary["Payload"];
        Dictionary <string, object> payLoadDictionary = (Dictionary <string, object>)MiniJson.JsonDecode(payload);
        string receipt = (string)payLoadDictionary["json"];

        Dictionary <string, object> receiptDictionary = (Dictionary <string, object>)MiniJson.JsonDecode(receipt);

        if (!receiptDictionary.ContainsKey("obfuscatedAccountId") ||
            !receiptDictionary["obfuscatedAccountId"].Equals(TrivialKartClientUtil.GetObfuscatedAccountId()))
        {
            Debug.Log("Obfuscated account id is invalid");
            throw new IAPSecurityException();
        }
    }
    public void OnVerifyPurchase()
    {
        gpJsonDict = (Dictionary <string, object>)MiniJson.JsonDecode(gpJson);

        Dictionary <string, object> receiptData = new Dictionary <string, object>();

        receiptData.Add("productId", gpJsonDict["productId"]);
        receiptData.Add("orderId", gpJsonDict["orderId"]);
        receiptData.Add("token", gpJsonDict["purchaseToken"]);
        //Developer payload is not supported
        //Google Play deprecated developer payload and is replacing it with alternatives that are more meaningful and contextual.
        receiptData.Add("developerPayload", ""); //So pass in empty string for developer payload.

        string receiptDataString = JsonWriter.Serialize(receiptData);

        BCConfig._bc.AppStoreService.VerifyPurchase("googlePlay", receiptDataString, OnSuccess_VerifyPurchase, OnError_VerifyPurchase);
    }
Пример #14
0
    public void OnPurchaseComplete(Product Purchased_product)
    {
        print("Successfully Purchased =>" + Purchased_product.definition.id.ToString());
        var decoded_receipt = (Dictionary <string, object>)MiniJson.JsonDecode(Purchased_product.receipt);

        if (null != decoded_receipt)
        {
            var store   = (string)decoded_receipt["Store"];
            var payload = (string)decoded_receipt["Payload"]; // For Apple this will be the base64 encoded ASN.1 receipt
            //print("Sandeep ka Payload =>" + payload.ToString());

            var decoded_payload = (Dictionary <string, object>)MiniJson.JsonDecode(payload);
            var decoded_Json    = (string)decoded_payload["json"];
            print("decoded Parload ka json =>" + decoded_Json.ToString());
            purchaseDetails = decoded_Json.ToString();
            mystatus.text   = purchaseDetails;
        }
        StartCoroutine(SendDatatoAppserver(purchaseDetails));
    }
Пример #15
0
        /**
         *  should return endPoints by parsing response from your endpoint info server.
         */
        private EndPoints OnEndPointsParseFromUpdateResponse(string responseStr)
        {
            /*
             *  e,g,
             *  {
             *      "main": [{
             *              "key0": "val0"
             *          },
             *          {
             *              "key1": "val1"
             *          }
             *      ],
             *      "sub": [{
             *          "key1": "val1"
             *      }]
             *  }
             */
            var endPoints = new List <EndPoint>();
            var classNamesAndValuesSource = MiniJson.JsonDecode(responseStr) as Dictionary <string, object>;

            foreach (var classNamesAndValueSrc in classNamesAndValuesSource)
            {
                var className        = classNamesAndValueSrc.Key;
                var rawParameterList = classNamesAndValueSrc.Value as List <object>;

                var parameterDict = new Dictionary <string, string>();
                foreach (var rawParameters in rawParameterList)
                {
                    var parameters = rawParameters as Dictionary <string, object>;
                    foreach (var parameter in parameters)
                    {
                        var key = parameter.Key;
                        var val = parameter.Value as string;
                        parameterDict[key] = val;
                    }
                }

                var endPoint = new EndPoint(className, parameterDict);
                endPoints.Add(endPoint);
            }

            return(new EndPoints(endPoints.ToArray()));
        }
        void UpdateUI()
        {
            var subscriptionProduct = m_StoreController.products.WithID(subscriptionProductId);

            try
            {
                var isSubscribed = IsSubscribedTo(subscriptionProduct);
                isSubscribedText.text = isSubscribed ? "You are subscribed" : "You are not subscribed";
            }
            catch (StoreSubscriptionInfoNotSupportedException)
            {
                var receipt = (Dictionary <string, object>)MiniJson.JsonDecode(subscriptionProduct.receipt);
                var store   = receipt["Store"];
                isSubscribedText.text =
                    "Couldn't retrieve subscription information because your current store is not supported.\n" +
                    $"Your store: \"{store}\"\n\n" +
                    "You must use the App Store, Google Play Store or Amazon Store to be able to retrieve subscription information.\n\n" +
                    "For more information, see README.md";
            }
        }
Пример #17
0
    public void ProcessPurchaseCache()
    {
        int purchaseType = 0;

#if UNITY_IOS || UNITY_IPHONE
        purchaseType = 1;   //Apple Store  EPlatformType.EPlatformType_AppStore
#elif UNITY_ANDROID
        purchaseType = 2;   //Google Play  EPlatformType.EPlatformType_GooglePlay
#endif
        FileBilling.Instance.ReadFile();
        var entry = FileBilling.Instance.Get(purchaseType);
        if (entry == null)
        {
            return;
        }

        Debug.Log("=================ProcessPurchaseCache==================");
        string udid          = OSUtility.GetOpenUDID();
        string signature     = "";
        string receipt       = entry.Receipt;
        bool   isSucceed     = entry.IsSucceed;
        string pid           = entry.ProductId;
        string transactionID = entry.TransactionId;
        int    roleIdCache   = entry.RoleId;
#if UNITY_IOS || UNITY_IPHONE
#elif UNITY_ANDROID
        if (isSucceed)
        {
            // 成功后解析需要的订单信息
            var gpDetails = (Dictionary <string, object>)MiniJson.JsonDecode(receipt);
            receipt   = (string)gpDetails["signature"];     // 服务器待验证 签名数据
            signature = (string)gpDetails["json"];          // 服务器待验证 订单信息
        }
#endif

        // Post receipt for verify
        PostVerifyData(_roleId, roleIdCache, purchaseType, pid, transactionID, udid, receipt, signature, true, isSucceed);
    }
        // If UnityIAP exists, check Assets/Plugins/UnityPurchasing/Resources/BillingMode.json
        // also, check the existence of UDP Setting.asset.
        public static bool TargetUDP()
        {
            bool res = File.Exists(AppStoreSettings.appStoreSettingsAssetPath);

            if (UnityIAPExists())
            {
                res = false; // set to false temporarily.

                // if billingMode is target to UDP, set it to true;
                if (File.Exists(UnityIAPBillingModeFile))
                {
                    string targetStoreJson = File.ReadAllText(UnityIAPBillingModeFile);
                    if (targetStoreJson != null)
                    {
                        Debug.Log(targetStoreJson);
                        var dic = MiniJson.JsonDecode(targetStoreJson);

                        res &= (string)dic["androidStore"] == "UDP";
                    }
                }
            }

            return(res);
        }
Пример #19
0
        public override void HandleRC(string data, RCType type)
        {
            base.HandleRC(data, type);

            var wrapper = (Dictionary <string, object>)MiniJson.JsonDecode(data);

            if (null == wrapper)
            {
                return;
            }

            string isFSOnString = wrapper["isFSOn"].ToString();

            bool.TryParse(isFSOnString, out App.GetData <AdsData>().isFSOn);

            string clicksPerAdString = wrapper["clicksPerFS"].ToString();

            int.TryParse(clicksPerAdString, out App.GetData <AdsData>().clicksPerAd);
            App.GetData <AdsData>().currentClicks = 0;



            base.RCSet();
        }
Пример #20
0
    public PurchaseProcessingResult ProcessPurchase(Product e, int skinID = -1)
    {
        bool validPurchase = true;         // Presume valid for platforms with no R.V.

        // Unity IAP's validation logic is only included on these platforms.
#if UNITY_ANDROID || UNITY_IOS || UNITY_STANDALONE_OSX || UNITY_TVOS
        // Prepare the validator with the secrets we prepared in the Editor
        // obfuscation window.
        var validator = new CrossPlatformValidator(GooglePlayTangle.Data(),
                                                   AppleTangle.Data(), Application.identifier);

        try
        {
            // On Google Play, result will have a single product Id.
            // On Apple stores receipts contain multiple products.
            var result = validator.Validate(e.receipt);
            Debug.Log("Receipt is valid. Contents:");
            foreach (IPurchaseReceipt productReceipt in result)
            {
                Debug.Log(productReceipt.productID);
                Debug.Log(productReceipt.purchaseDate);
                Debug.Log(productReceipt.transactionID);
            }
        }
        catch (IAPSecurityException)
        {
            Debug.Log("Invalid receipt, not unlocking content");
            validPurchase = false;
        }
#endif
        if (validPurchase)
        {
            // Unlock the appropriate content here.
#if UNITY_ANDROID
            //(string publicKey, string purchaseData, string signature, string price, string currency

            Dictionary <string, object> wrapper = (Dictionary <string, object>)MiniJson.JsonDecode(e.receipt);

            if (wrapper == null)
            {
                throw new InvalidReceiptDataException();
            }

            string payload   = (string)wrapper["Payload"];
            var    gpDetails = (Dictionary <string, object>)MiniJson.JsonDecode(payload);
            string gpJson    = (string)gpDetails["json"];
            string gpSig     = (string)gpDetails["signature"];

            AppsFlyer.validateReceipt(googlePublicKey, gpJson, gpSig, e.metadata.localizedPriceString, e.metadata.isoCurrencyCode, new Dictionary <string, string>());
#elif UNITY_IOS
            if (Debug.isDebugBuild)
            {
                AppsFlyer.setIsSandbox(true);
            }
            AppsFlyer.validateReceipt(e.definition.id, e.metadata.localizedPriceString, e.metadata.isoCurrencyCode, e.transactionID, new Dictionary <string, string>());
#endif

            if (skinID != -1)
            {
                GameObject.FindObjectOfType <SkinSceneManager>().AddSkinIDToPlayer(skinID);
                skinID = 0;
            }
            else
            {
                FindObjectOfType <TitleSceneManager>().AddNoAdsPurchase();
            }
        }

        return(PurchaseProcessingResult.Complete);
    }
Пример #21
0
    public IEnumerator ChangeEndPoint()
    {
        /*
         *  この機構は、起動時に通信を行い、特定のファイルの内容を更新することを前提としている。
         *  失敗した場合は起動しない、という選択肢も取る必要がある。
         */
        var retryCount = 3;

        var endPointSelector = new EndPointSelector(
            new IEndPoint[] {
            new main(),
            new sub(),
        }
            );

        var succeeded = false;

        var cor = endPointSelector.UpToDate(
            "https://raw.githubusercontent.com/sassembla/Autoya/master/Assets/AutoyaTests/RuntimeData/EndPoints/mainAndSub.json",
            new Dictionary <string, string>(),
            responseStr =>
        {
            var endPoints = new List <EndPoint>();
            var classNamesAndValuesSource = MiniJson.JsonDecode(responseStr) as Dictionary <string, object>;
            foreach (var classNamesAndValueSrc in classNamesAndValuesSource)
            {
                var className        = classNamesAndValueSrc.Key;
                var rawParameterList = classNamesAndValueSrc.Value as List <object>;

                var parameterDict = new Dictionary <string, string>();
                foreach (var rawParameters in rawParameterList)
                {
                    var parameters = rawParameters as Dictionary <string, object>;
                    foreach (var parameter in parameters)
                    {
                        var key            = parameter.Key;
                        var val            = parameter.Value as string;
                        parameterDict[key] = val;
                    }
                }

                var endPoint = new EndPoint(className, parameterDict);
                endPoints.Add(endPoint);
            }

            return(new EndPoints(endPoints.ToArray()));
        },
            namesAndErrors =>
        {
            if (namesAndErrors.Length == 0)
            {
                succeeded = true;
                return;
            }
            Debug.LogError("fauled to parse, errors:" + namesAndErrors.Length);
        },
            failReason =>
        {
            Debug.LogError("failed to get endPoints.");
        },
            10.0,
            retryCount
            );

        while (cor.MoveNext())
        {
            yield return(null);
        }

        Assert.True(succeeded);

        var ep = endPointSelector.GetEndPoint <main>();

        Assert.True(ep.key0 == "val0");
        Assert.True(ep.key1 == "default_val1");
    }
Пример #22
0
    /// <summary> 구매에 대한 처리 부분 </summary>
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
    {
        Debug.Log(args.purchasedProduct.receipt);
        string signedData = "";
        string signature  = "";
        Dictionary <string, object> jsonReceiptDic = (Dictionary <string, object>)MiniJson.JsonDecode(args.purchasedProduct.receipt);
        var payload = jsonReceiptDic["Payload"];
        Dictionary <string, object> jsonDic = (Dictionary <string, object>)MiniJson.JsonDecode(payload.ToString());


        foreach (KeyValuePair <string, object> pair in jsonDic)
        {
            if (pair.Key == "json")
            {
                signedData = pair.Value.ToString();
                Debug.Log(pair.Value);
            }
            else if (pair.Key == "signature")
            {
                signature = pair.Value.ToString();
                Debug.Log(pair.Value);
            }
        }
        bool validPurchase = true;

        string purchaseToken = "";
        string purchaseDate  = "";

        transactionID = null;

        //#if RECEIPT_VALIDATION
        if (isGooglePlayStoreSelected || isAppStoreSelected)
        {
            validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.identifier);
            try
            {
                var result = validator.Validate(args.purchasedProduct.receipt);
                Debug.Log("Receipt is valid. Contents:");

                foreach (IPurchaseReceipt productReceipt in result)
                {
                    Debug.Log(productReceipt.productID);
                    Debug.Log(productReceipt.purchaseDate);
                    Debug.Log(productReceipt.transactionID);

                    GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
                    if (null != google)
                    {
                        //Debug.Log(google.transactionID);
                        //Debug.Log(google.purchaseState);
                        //Debug.Log(google.purchaseToken);
                        Debug.Log(args.purchasedProduct.definition.id);
                        Debug.Log(productReceipt.productID);
                        if (args.purchasedProduct.transactionID != productReceipt.transactionID)
                        {
                            throw new IAPSecurityException("not matched transactionID");
                        }

                        if (args.purchasedProduct.definition.id != productReceipt.productID)
                        {
                            throw new IAPSecurityException("not matched productID");
                        }



                        transactionID = google.transactionID;
                        purchaseToken = google.purchaseToken;
                        purchaseDate  = google.purchaseDate.ToString();
                    }

                    AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
                    if (null != apple)
                    {
                        Debug.Log(apple.originalTransactionIdentifier);
                        Debug.Log(apple.subscriptionExpirationDate);
                        Debug.Log(apple.cancellationDate);
                        Debug.Log(apple.quantity);
                    }

                    // For improved security, consider comparing the signed
                    // IPurchaseReceipt.productId, IPurchaseReceipt.transactionID, and other data
                    // embedded in the signed receipt objects to the data which the game is using
                    // to make this purchase.
                }
            }
            catch (IAPSecurityException ex)
            {
                isFailed = true;
                Debug.Log("Invalid receipt, not unlocking content. " + ex);
                validPurchase = false;
            }
        }
        //#endif


        if (validPurchase)
        {
#if UNITY_EDITOR
            isSuccess = true;
            if (AdController.Instance != null)
            {
                AdController.Instance.DeleteBanner();
            }
#endif
#if !UNITY_EDITOR
            if (isGooglePlayStoreSelected)
            {
                //StartCoroutine(PurchaseGoogleReceiptSave(args.purchasedProduct.definition.id, args.purchasedProduct.receipt, transactionID, purchaseToken, purchaseDate, signedData, signature));
                //
                StartVerifyGoogleReceipt(args.purchasedProduct.definition.id, args.purchasedProduct.receipt, transactionID, purchaseToken, purchaseDate, signedData, signature);
            }
            else if (isAppStoreSelected)
            {
                //애플 검증
            }
#endif
        }
        return(PurchaseProcessingResult.Complete);
    }
Пример #23
0
        public IPurchaseReceipt[] Validate(string unityIAPReceipt)
        {
            try {
                var wrapper = (Dictionary <string, object>)MiniJson.JsonDecode(unityIAPReceipt);
                if (null == wrapper)
                {
                    throw new InvalidReceiptDataException();
                }

                var store   = (string)wrapper ["Store"];
                var payload = (string)wrapper ["Payload"];
                switch (store)
                {
                case "GooglePlay":
                {
                    if (null == google)
                    {
                        throw new MissingStoreSecretException(
                                  "Cannot validate a Google Play receipt without a Google Play public key.");
                    }
                    var details = (Dictionary <string, object>)MiniJson.JsonDecode(payload);
                    var json    = (string)details["json"];
                    var sig     = (string)details["signature"];
                    var result  = google.Validate(json, sig);

                    // [IAP-1696] Check googleBundleId if packageName is present inside the signed receipt.
                    // packageName can be missing when the GPB v1 getPurchaseHistory API is used to fetch.
                    if (!string.IsNullOrEmpty(result.packageName) &&
                        !googleBundleId.Equals(result.packageName))
                    {
                        throw new InvalidBundleIdException();
                    }

                    return(new IPurchaseReceipt[] { result });
                }

                case "AppleAppStore":
                case "MacAppStore":
                {
                    if (null == apple)
                    {
                        throw new MissingStoreSecretException(
                                  "Cannot validate an Apple receipt without supplying an Apple root certificate");
                    }
                    var r = apple.Validate(Convert.FromBase64String(payload));
                    if (!appleBundleId.Equals(r.bundleID))
                    {
                        throw new InvalidBundleIdException();
                    }
                    return(r.inAppPurchaseReceipts.ToArray());
                }

                default:
                {
                    throw new StoreNotSupportedException("Store not supported: " + store);
                }
                }
            } catch (IAPSecurityException ex) {
                throw ex;
            } catch (Exception ex) {
                throw new GenericValidationException("Cannot validate due to unhandled exception. (" + ex + ")");
            }
        }
Пример #24
0
 /// <summary>
 /// Convert string JSON into List of Objects.
 /// </summary>
 /// <param name="json">String JSON to convert.</param>
 /// <returns>List of Objects converted from string json.</returns>
 public static List <object> ArrayListFromJson(this string json)
 {
     return(MiniJson.JsonDecode(json) as List <object>);
 }
Пример #25
0
 /// <summary>
 /// Convert string JSON into Dictionary.
 /// </summary>
 /// <param name="json">String JSON to convert.</param>
 /// <returns>Dictionary converted from string json.</returns>
 public static Dictionary <string, object> HashtableFromJson(this string json)
 {
     return(MiniJson.JsonDecode(json) as Dictionary <string, object>);
 }
    public void OnShowJSONStats()
    {
        gpJsonDict = (Dictionary <string, object>)MiniJson.JsonDecode(gpJson);

        statusText = "PRODUCTID: " + gpJsonDict["productId"] + "\n:ORDERID " + gpJsonDict["orderId"] + "\nTOKEN: " + gpJsonDict["purchaseToken"];
    }