Exemplo n.º 1
0
        private static async Task GetPayPalTransactionsAsync(HttpClient httpClient, PayPalAccessToken accessToken, DateTime from, DateTime to, List <PayPalTransaction> payPalTransactions)
        {
            string startDate = string.Format("{0:yyyy-MM-ddTHH\\:mm\\:ssZ}", from);
            string endDate   = string.Format("{0:yyyy-MM-ddTHH\\:mm\\:ssZ}", to);
            string url       = $"https://api.paypal.com/v1/reporting/transactions?fields=all&page_size=100&page=1&start_date={startDate}&end_date={endDate}";

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.access_token);
            HttpResponseMessage response = await httpClient.SendAsync(request);

            string jsonString = await response.Content.ReadAsStringAsync();

            dynamic jsonD = JsonConvert.DeserializeObject(jsonString);

            // parse json
            string   accountNumber = jsonD.account_number;
            int      total_pages   = jsonD.total_pages;
            DateTime dateStart     = jsonD.start_date;
            DateTime dateEnd       = jsonD.end_date;
            int      page          = jsonD.page;
            int      totalItems    = jsonD.total_items;

            foreach (var transaction in jsonD.transaction_details)
            {
                var      transactionInfo               = transaction.transaction_info;
                var      transactionId                 = transactionInfo.transaction_id;
                string   transactionEventCode          = transactionInfo.transaction_event_code;
                DateTime transactionInitiationDate     = transactionInfo.transaction_initiation_date;
                DateTime transactionUpdatedDate        = transactionInfo.transaction_updated_date;
                var      transactionAmountObject       = transactionInfo.transaction_amount;
                string   transactionAmountCurrencyCode = transactionAmountObject.currency_code;
                decimal  transactionAmountValue        = transactionAmountObject.value;
                string   transactionStatus             = transactionInfo.transaction_status;
                string   bankReferenceId               = transactionInfo.bank_reference_id;
                var      endingBalanceObject           = transactionInfo.ending_balance;
                string   endingBalanceCurrencyCode     = endingBalanceObject.currency_code;
                decimal  endingBalanceValue            = endingBalanceObject.value;
                var      availableBalanceObject        = transactionInfo.available_balance;
                string   availableBalanceCurrencyCode  = availableBalanceObject.currency_code;
                decimal  availableBalanceValue         = availableBalanceObject.value;
                string   protectionEligibility         = transactionInfo.protection_eligibility;

                PayPalTransaction payPalTransaction = new PayPalTransaction();
                payPalTransaction.TransactionID = transactionId;
                payPalTransaction.Timestamp     = transactionInitiationDate;
                payPalTransaction.Status        = transactionStatus;
                payPalTransaction.Type          = transactionEventCode;
                payPalTransaction.GrossAmount   = transactionAmountValue;
                payPalTransaction.NetAmount     = 0;
                payPalTransaction.FeeAmount     = 0;

                // payPalTransaction.Payer = transaction.Payer;
                // payPalTransaction.PayerDisplayName = transaction.PayerDisplayName;

                payPalTransactions.Add(payPalTransaction);
            }
        }
Exemplo n.º 2
0
        private static async Task <List <PayPalTransaction> > GetPayPalTransactionsListSoapAsync(IMyConfiguration configuration, TextWriter writer, DateTime from, DateTime to)
        {
            var payPalTransactions = new List <PayPalTransaction>();

            try
            {
                using (var httpClient = new HttpClient(new HttpClientHandler()
                {
                    AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip
                })
                {
                    Timeout = TimeSpan.FromSeconds(30)
                })
                {
                    string payPalApiUsername  = configuration.GetValue("PayPalApiUsername");
                    string payPalApiPassword  = configuration.GetValue("PayPalApiPassword");
                    string payPalApiSignature = configuration.GetValue("PayPalApiSignature");

                    var soapEnvelopeXml = ConstructSoapEnvelope();
                    var doc             = XDocument.Parse(soapEnvelopeXml);

                    var authHeader = doc.Descendants("{urn:ebay:apis:eBLBaseComponents}Credentials").FirstOrDefault();
                    if (authHeader != null)
                    {
                        authHeader.Element("{urn:ebay:apis:eBLBaseComponents}Username").Value  = payPalApiUsername;
                        authHeader.Element("{urn:ebay:apis:eBLBaseComponents}Password").Value  = payPalApiPassword;
                        authHeader.Element("{urn:ebay:apis:eBLBaseComponents}Signature").Value = payPalApiSignature;
                    }

                    var parameterHeader = doc.Descendants("{urn:ebay:api:PayPalAPI}TransactionSearchRequest").FirstOrDefault();
                    if (parameterHeader != null)
                    {
                        string startDate = string.Format("{0:yyyy-MM-ddTHH\\:mm\\:ssZ}", from);
                        string endDate   = string.Format("{0:yyyy-MM-ddTHH\\:mm\\:ssZ}", to.AddDays(1));

                        parameterHeader.Element("{urn:ebay:api:PayPalAPI}StartDate").Value = startDate;
                        parameterHeader.Element("{urn:ebay:api:PayPalAPI}EndDate").Value   = endDate;
                    }

                    string envelope = doc.ToString();

                    var request = CreateRequest(HttpMethod.Post, "https://api-3t.paypal.com/2.0/", "TransactionSearch", doc);
                    request.Content = new StringContent(envelope, Encoding.UTF8, "text/xml");

                    // request is now ready to be sent via HttpClient
                    //
                    HttpResponseMessage response = await httpClient.SendAsync(request);

                    if (!response.IsSuccessStatusCode)
                    {
                        throw new Exception();
                    }

                    var stream = await response.Content.ReadAsStreamAsync();

                    var sr           = new StreamReader(stream);
                    var soapResponse = XDocument.Load(sr);

                    // parse SOAP response
                    var xmlTransactions = soapResponse.Descendants("{urn:ebay:apis:eBLBaseComponents}PaymentTransactions").ToList();
                    foreach (var xmlTransaction in xmlTransactions)
                    {
                        // build new list
                        var payPalTransaction = new PayPalTransaction();

                        //xmlTransaction.RemoveAttributes(); // trick to ignore ebl types that cannot be deserialized
                        //var transaction = Utils.Deserialize<PaymentTransaction>(xmlTransaction.ToString());

                        payPalTransaction.TransactionID = xmlTransaction.Element("{urn:ebay:apis:eBLBaseComponents}TransactionID").Value;

                        // Converting from paypal date to date:
                        // 2017-08-30T21:13:37Z
                        // var date = DateTimeOffset.Parse(paypalTransaction.Timestamp).UtcDateTime;
                        payPalTransaction.Timestamp = DateTimeOffset.Parse(xmlTransaction.Element("{urn:ebay:apis:eBLBaseComponents}Timestamp").Value).UtcDateTime;

                        payPalTransaction.Status = xmlTransaction.Element("{urn:ebay:apis:eBLBaseComponents}Status").Value;
                        payPalTransaction.Type   = xmlTransaction.Element("{urn:ebay:apis:eBLBaseComponents}Type").Value;

                        payPalTransaction.GrossAmount           = decimal.Parse(xmlTransaction.Element("{urn:ebay:apis:eBLBaseComponents}GrossAmount").Value, CultureInfo.InvariantCulture);
                        payPalTransaction.GrossAmountCurrencyId = xmlTransaction.Element("{urn:ebay:apis:eBLBaseComponents}GrossAmount").Attribute("currencyID").Value;
                        payPalTransaction.NetAmount             = decimal.Parse(xmlTransaction.Element("{urn:ebay:apis:eBLBaseComponents}NetAmount").Value, CultureInfo.InvariantCulture);
                        payPalTransaction.NetAmountCurrencyId   = xmlTransaction.Element("{urn:ebay:apis:eBLBaseComponents}NetAmount").Attribute("currencyID").Value;
                        payPalTransaction.FeeAmount             = decimal.Parse(xmlTransaction.Element("{urn:ebay:apis:eBLBaseComponents}FeeAmount").Value, CultureInfo.InvariantCulture);
                        payPalTransaction.FeeAmountCurrencyId   = xmlTransaction.Element("{urn:ebay:apis:eBLBaseComponents}FeeAmount").Attribute("currencyID").Value;

                        if (null != xmlTransaction.Element("{urn:ebay:apis:eBLBaseComponents}Payer"))
                        {
                            payPalTransaction.Payer = xmlTransaction.Element("{urn:ebay:apis:eBLBaseComponents}Payer").Value;
                        }
                        payPalTransaction.PayerDisplayName = xmlTransaction.Element("{urn:ebay:apis:eBLBaseComponents}PayerDisplayName").Value;

                        payPalTransactions.Add(payPalTransaction);
                    }
                }
            }
            catch (System.Exception e)
            {
                await writer.WriteLineAsync(string.Format("ERROR: Could not get paypal transactions! '{0}'", e.Message));
            }

            return(payPalTransactions);
        }