TransactionCurrencyConverter.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System;
  2. using System.Collections.Generic;
  3. using Newtonsoft.Json;
  4. using UnityEngine;
  5. namespace Unity.Services.Analytics
  6. {
  7. class TransactionCurrencyConverter
  8. {
  9. Dictionary<string, int> m_CurrencyCodeToMinorUnits;
  10. public long Convert(string currencyCode, double value)
  11. {
  12. if (m_CurrencyCodeToMinorUnits == null)
  13. {
  14. LoadCurrencyCodeDictionary();
  15. }
  16. var currencyCodeUppercased = currencyCode.ToUpperInvariant();
  17. if (!m_CurrencyCodeToMinorUnits.ContainsKey(currencyCodeUppercased))
  18. {
  19. Debug.LogWarning("Unknown currency provided to convert method, no conversion will be performed and returned value will be 0.");
  20. return 0;
  21. }
  22. var numberOfMinorUnits = m_CurrencyCodeToMinorUnits[currencyCode];
  23. return (long)(value * Math.Pow(10, numberOfMinorUnits));
  24. }
  25. public void LoadCurrencyCodeDictionary()
  26. {
  27. var text = (Resources.Load("iso4217", typeof(TextAsset)) as TextAsset)?.text;
  28. if (string.IsNullOrEmpty(text))
  29. {
  30. Debug.LogWarning("Error loading currency definitions, no conversions will be performed.");
  31. m_CurrencyCodeToMinorUnits = new Dictionary<string, int>();
  32. return;
  33. }
  34. try
  35. {
  36. m_CurrencyCodeToMinorUnits = JsonConvert.DeserializeObject<Dictionary<string, int>>(text);
  37. }
  38. catch (JsonException e)
  39. {
  40. Debug.LogWarning($"Failed to deserialize JSON for currency conversion, no conversions will be performed");
  41. Debug.LogWarning(e.Message);
  42. m_CurrencyCodeToMinorUnits = new Dictionary<string, int>();
  43. }
  44. }
  45. }
  46. }