Example #1
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");
        }
Example #3
0
        public async Task <string> GetTunnelAddressFromAPI()
        {
            if (!IsNgrokActive())
            {
                throw new Exception($"Not able to get Ngrok tunnel address from API because Ngrok is not started (or exited prematurely)! LastErrorCode: {NgrokLastErrorCode}");
            }

            if (_ngrokAPIAddress == null)
            {
                throw new Exception($"Not able to get Ngrok tunnel address because Ngrok API address is not (yet) known!");
            }

            using (var client = new HttpClient())
            {
                var response = await client.GetAsync($"http://{_ngrokAPIAddress}/api/tunnels");

                if (response.IsSuccessStatusCode)
                {
                    var body = await response.Content.ReadAsStringAsync();

                    var json = MiniJson.Deserialize(body) as Dictionary <string, object>;

                    var tunnels = json["tunnels"] as List <object>;

                    string publicUrl = null;
                    foreach (Dictionary <string, object> tunnel in tunnels)
                    {
                        if (tunnel["proto"] as string == "tcp" && (tunnel["config"] as Dictionary <string, object>)["addr"] as string == $"localhost:{_port}")
                        {
                            publicUrl = tunnel["public_url"] as string;
                            break;
                        }
                    }

                    if (publicUrl == null)
                    {
                        throw new Exception("Not able to get Ngrok tunnel address because no matching tunnel was found in API response");
                    }

                    return(publicUrl.Replace("tcp://", ""));
                }
                else
                {
                    throw new Exception("Could not access the ngrok API");
                }
            }
        }
Example #4
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);
    }
        public string Export(ProductCatalog catalog)
        {
            List <object> catalogList = new List <object>();

            foreach (var item in catalog.allProducts)
            {
                Dictionary <string, object> itemDict = new Dictionary <string, object>();

                itemDict[kIDKey]   = item.id;
                itemDict[kTypeKey] = item.type.ToString();
                itemDict[kNameKey] = item.defaultDescription.Title;

                Dictionary <string, string> storeIDsDict = new Dictionary <string, string>();
                foreach (var storeID in item.allStoreIDs)
                {
                    storeIDsDict[storeID.store] = storeID.id;
                }
                itemDict[kStoreIDsKey] = storeIDsDict;

                Dictionary <string, object> priceDict = new Dictionary <string, object> ();
                priceDict [kApplePriceKey]  = ApplePriceTiers.ActualDollarsForAppleTier(item.applePriceTier);
                priceDict [kGooglePriceKey] = Convert.ToDouble(item.googlePrice.value);
                itemDict [kPriceKey]        = priceDict;

                var payouts = new List <Dictionary <string, object> > ();
                foreach (var p in item.Payouts)
                {
                    var payout = new Dictionary <string, object> ();
                    payout [kPayoutTypeKey]     = p.typeString;
                    payout [kPayoutSubtypeKey]  = p.subtype;
                    payout [kPayoutQuantityKey] = p.quantity;
                    payout [kPayoutDataKey]     = p.data;
                    payouts.Add(payout);
                }
                itemDict [kPayoutsKey] = payouts.ToArray();

                catalogList.Add(itemDict);
            }

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

            dict[kCatalogKey] = catalogList;
            return(MiniJson.JsonEncode(dict));
        }
Example #7
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));
    }
Example #8
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";
            }
        }
Example #10
0
        // Mastro: This saves a JSON config file to a Olproxy application data folder (needed if no external Olproxy.exe is found).
        public bool SaveConfig(Dictionary <string, object> saveConfig, string alternateFileName = null)
        {
            string configPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Olproxy");

            if (Directory.Exists(configPath) == false)
            {
                Directory.CreateDirectory(configPath);
            }

            string configFileName = Path.Combine(configPath, "appsettings.json");
            string jsonString     = MiniJson.ToString(saveConfig);

            try { File.WriteAllText(configFileName, jsonString); } catch { return(false); }

            // Optionall update the appsettings.json placed in the same directory as Olproxy.exe.
            if (!String.IsNullOrEmpty(alternateFileName))
            {
                try { File.WriteAllText(alternateFileName, jsonString); } catch { return(false); }
            }

            return(true);
        }
Example #11
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);
    }
Example #12
0
        public MatchInfo(string matchMessage)
        {
            var msg  = MiniJson.Parse(matchMessage);
            var attr = (msg as MJDict)["attr"] as MJDict;

            if (!attr.TryGetValue("mm_players", out object plVal) && !attr.TryGetValue("mm_mmPlayers", out plVal))
            {
                return;
            }
            var players = MiniJson.Parse((plVal as MJDict)["S"] as string) as MJList;

            PlayerCount = players.Count;
            foreach (var pl in players)
            {
                if (((pl as MJDict)["PlayerAttributes"] as MJDict).TryGetValue("private_match_data", out object data))
                {
                    PrivateMatchData = new PrivateMatchData(System.Convert.FromBase64String((data as MJDict)["valueAttribute"] as string));
                    HasMatchData     = true;
                    Creator          = PrivateMatchData.Creator;
                    Level            = PrivateMatchData.LevelName;
                    IsTeams          = PrivateMatchData.Mode == 1;
                }
            }
        }
Example #13
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();
        }
        // 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);
        }
Example #15
0
    public object[] Import(string path)
    {
        if (string.IsNullOrEmpty(path))
        {
            return(null);
        }
        if (!path.EndsWith(".json"))
        {
            path += ".json";
        }

        string txt = FileGameUtil.ReadText(path);

        if (string.IsNullOrEmpty(txt))
        {
            return(null);
        }

        List <object> instanceList = new List <object>();
        ArrayList     dataJson     = MiniJson.jsonDecode(txt) as ArrayList;

        foreach (object obj in dataJson)
        {
            Hashtable itemTab   = obj as Hashtable;
            Type      classType = Type.GetType(Convert.ToString(itemTab["type"]));

            Hashtable dataTab = itemTab["data"] as Hashtable;
            Dictionary <string, object> reflectDic = CopyTo(dataTab);
            object instance = InjectDataBinder.BindingData(classType, reflectDic);
            if (instance != null)
            {
                instanceList.Add(instance);
            }
        }
        return(instanceList.ToArray());
    }
Example #16
0
        // iapCreate && iapUpdate
        public static UnityWebRequest IapEvent(string eventName, string clientId, IapItem item, string failedReason)
        {
            var parameters = Common.GetCommonParams();

            parameters.Add(Common.k_ClientId, clientId);

            if (failedReason != null)
            {
                parameters.Add(Common.k_FailedReason, failedReason);
            }

            bool successful = failedReason == null;

            parameters.Add(Common.k_Successful, successful);

            if (successful)
            {
                parameters.Add(Common.k_Consumable, item.consumable);
                parameters.Add(Common.k_ItemId, item.id);
                parameters.Add(Common.k_ItemType, "inapp");
                var priceList = item.priceSets.PurchaseFee.priceMap.DEFAULT;
                parameters.Add(Common.k_PriceList, priceList);

                parameters.Add(Common.k_ProductId, item.slug);
                parameters.Add(Common.k_OwnerId, item.ownerId);
                parameters.Add(Common.k_OwnerType, item.ownerType);
            }

            EventRequest request = new EventRequest
            {
                type = eventName,
                msg  = MiniJson.JsonEncode(parameters),
            };

            return(AssembleAndSendWebRequest(request));
        }
Example #17
0
        // clientCreate or clientUpdate
        public static UnityWebRequest ClientEvent(string eventName, string clientId, string failedReason)
        {
            var parameters = Common.GetCommonParams();

            bool successful = failedReason == null;

            parameters.Add(Common.k_Successful, successful);
            if (successful)
            {
                parameters.Add(Common.k_ClientId, clientId);
            }
            else
            {
                parameters.Add(Common.k_FailedReason, failedReason);
            }

            EventRequest request = new EventRequest
            {
                type = eventName,
                msg  = MiniJson.JsonEncode(parameters),
            };

            return(AssembleAndSendWebRequest(request));
        }
Example #18
0
 /// <summary>
 /// Convert a Dictionary to JSON.
 /// </summary>
 /// <param name="obj">The dictionary to convert to JSON.</param>
 /// <returns>The converted dictionary in JSON string format.</returns>
 public static string toJson(this Dictionary <string, string> obj)
 {
     return(MiniJson.JsonEncode(obj));
 }
Example #19
0
 public static string ToJson(JsonArray _object)
 {
     return(MiniJson.Serialize(_object));
 }
Example #20
0
 public static JsonArray FromJson(string _jsonString)
 {
     return(MiniJson.Deserialize(_jsonString) as JsonArray);
 }
    public void OnShowJSONStats()
    {
        gpJsonDict = (Dictionary <string, object>)MiniJson.JsonDecode(gpJson);

        statusText = "PRODUCTID: " + gpJsonDict["productId"] + "\n:ORDERID " + gpJsonDict["orderId"] + "\nTOKEN: " + gpJsonDict["purchaseToken"];
    }
Example #22
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");
    }
Example #23
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);
    }
Example #24
0
 public static JsonObject FromJson(string _jsonString)
 {
     return(MiniJson.Deserialize(_jsonString) as JsonObject);
 }
Example #25
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 + ")");
            }
        }
Example #26
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>);
 }
Example #27
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);
    }
Example #28
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>);
 }