Beispiel #1
0
        private void AddAccessToken2Request(AdvertAccount account, HttpClient client)
        {
            if (account.AccessToken.IsNullOrEmpty())
            {
                return;
            }

            client.DefaultRequestHeaders.Add("Access-Token", account.AccessToken);
        }
Beispiel #2
0
        private string GetRequestPara(AdvertAccount account)
        {
            if (account.AccessToken.IsNullOrEmpty())
            {
                return(string.Empty);
            }

            var nonStr    = CommonHelper.GenerateRandomDigitCode(6);
            var timeStamp = DateTime.UtcNow.ConvertDateTimeStampLong(milliseconds: false);

            return($"?access_token={account.AccessToken}&timestamp={timeStamp}&nonce={nonStr}");
        }
Beispiel #3
0
        public async Task <bool> RefreshAccessTokenAsync(AdvertAccount account)
        {
            if (DateTime.UtcNow > account.RefreshTokenExpiresIn)
            {
                return(false);
            }

            string reqURL = RefessAccessTokenAddress();

            List <KeyValuePair <String, String> > paramList = new List <KeyValuePair <String, String> >();

            paramList.Add(new KeyValuePair <string, string>("app_id", await GetAppId()));
            paramList.Add(new KeyValuePair <string, string>("secret", await GetAppSecret()));
            paramList.Add(new KeyValuePair <string, string>("grant_type", "refresh_token"));
            paramList.Add(new KeyValuePair <string, string>("refresh_token", account.RefreshToken));

            var httpClient = new HttpClient();

            try
            {
                var response = await httpClient.PostAsync(new Uri(reqURL), new FormUrlEncodedContent(paramList));

                var jsonResultString = await response.Content.ReadAsStringAsync();

                var result = JsonConvert.DeserializeObject <ToutiaoAdvertResponse <ToutiaoAccesstokenResponse> >(jsonResultString);

                if (result.Code != 0 || result.Data == null)
                {
                    return(false);
                }

                account.AccessToken           = result.Data.AccessToken;
                account.AccessTokenExpiresIn  = DateTime.UtcNow.AddSeconds(result.Data.AccessTokenExpiresIn);
                account.RefreshToken          = result.Data.RefreshToken;
                account.RefreshTokenExpiresIn = DateTime.UtcNow.AddSeconds(result.Data.RefreshTokenExpiresIn);

                await _advertAccountManager.UpdateAsync(account);
            }
            catch (Exception)
            {
                return(false);
            }
            finally
            {
                httpClient.Dispose();
            }

            return(true);
        }
Beispiel #4
0
        /// <summary>
        /// 查询账户资金情况
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public async Task <bool> QueryAccountFundsAsync(AdvertAccount account)
        {
            if (!account.IsAuth())
            {
                return(false);
            }

            if (account.IsAuthExpires())
            {
                await RefreshAccessTokenAsync(account);
            }

            string reqURL = FundAddress();

            List <KeyValuePair <String, String> > paramList = new List <KeyValuePair <String, String> >();

            paramList.Add(new KeyValuePair <string, string>("client_id", await GetAppId()));

            var httpClient = new HttpClient();

            AddAccessToken2Request(account, httpClient);
            try
            {
                var response = await httpClient.PostAsync(new Uri(reqURL), new FormUrlEncodedContent(paramList));

                var jsonResultString = await response.Content.ReadAsStringAsync();

                var result = JsonConvert.DeserializeObject <ToutiaoAdvertResponse <ToutiaoFundResponse> >(jsonResultString);

                if (result.Code == 0)
                {
                    account.Balance = result.Data.Balance;
                    await _advertAccountManager.UpdateAsync(account);
                }
            }
            catch (Exception)
            {
                return(false);
            }
            finally
            {
                httpClient.Dispose();
            }

            return(true);
        }
Beispiel #5
0
        /// <summary>
        /// 查询账户资金情况
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public async Task <bool> QueryAccountFundsAsync(AdvertAccount account)
        {
            if (!account.IsAuth())
            {
                return(false);
            }

            if (account.IsAuthExpires())
            {
                await RefreshAccessTokenAsync(account);
            }

            var reqURL = FundsAddress() + GetRequestPara(account);

            List <KeyValuePair <String, String> > paramList = new List <KeyValuePair <String, String> >();

            paramList.Add(new KeyValuePair <string, string>("account_id", account.ThirdpartyId));

            var httpClient = new HttpClient();

            try
            {
                var response = await httpClient.PostAsync(new Uri(reqURL), new FormUrlEncodedContent(paramList));

                var jsonResultString = await response.Content.ReadAsStringAsync();

                var result = JsonConvert.DeserializeObject <TenantAdvertRequestResult <TenantAccountFunds> >(jsonResultString);

                if (result.Code == 0)
                {
                    account.Balance = result.Data.Items.Sum(x => x.Balance) / 100;
                    await _advertAccountManager.UpdateAsync(account);
                }
            }
            catch (Exception)
            {
                return(false);
            }
            finally
            {
                httpClient.Dispose();
            }

            return(true);
        }
Beispiel #6
0
        /// <summary>
        /// 查询订单
        /// </summary>
        /// <param name="account"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task <TenantAdvertRequestResult <TenantOrder> > QueryOrderAsync(AdvertAccount account, DateTime startDate, DateTime endDate, int page, int pageSize = 100)
        {
            var dataParam = new DateRangePara()
            {
                StartDate = startDate.DateString(),
                EndDate   = endDate.DateString(),
            };


            string reqURL = OrderQueryAddress() + GetRequestPara(account);

            List <KeyValuePair <String, String> > paramList = new List <KeyValuePair <String, String> >();

            paramList.Add(new KeyValuePair <string, string>("account_id", account.ThirdpartyId));
            paramList.Add(new KeyValuePair <string, string>("date_range", JsonConvert.SerializeObject(dataParam)));
            paramList.Add(new KeyValuePair <string, string>("page", page.ToString()));
            paramList.Add(new KeyValuePair <string, string>("page_size", pageSize.ToString()));

            var httpClient = new HttpClient();

            try
            {
                var response = await httpClient.PostAsync(new Uri(reqURL), new FormUrlEncodedContent(paramList));

                var jsonResultString = (await response.Content.ReadAsStringAsync()).HtmlDecode();

                var result = JsonConvert.DeserializeObject <TenantAdvertRequestResult <TenantOrder> >(jsonResultString);

                return(result);
            }
            catch (Exception)
            {
                return(null);
            }
            finally
            {
                httpClient.Dispose();
            }
        }
Beispiel #7
0
        public async Task <bool> RefreshAccessTokenAsync(AdvertAccount account)
        {
            string reqURL = "https://api.e.qq.com/oauth/token";

            List <KeyValuePair <String, String> > paramList = new List <KeyValuePair <String, String> >();

            paramList.Add(new KeyValuePair <string, string>("client_id", await GetAppId()));
            paramList.Add(new KeyValuePair <string, string>("client_secret", await GetAppSecret()));
            paramList.Add(new KeyValuePair <string, string>("grant_type", "refresh_token"));
            paramList.Add(new KeyValuePair <string, string>("refresh_token", account.RefreshToken));

            var httpClient = new HttpClient();

            try
            {
                var response = await httpClient.PostAsync(new Uri(reqURL), new FormUrlEncodedContent(paramList));

                var jsonResultString = await response.Content.ReadAsStringAsync();

                var result = JsonConvert.DeserializeObject <TenantAdvertRequestResult <AccesstokenResult> >(jsonResultString);

                account.AccessToken           = result.Data.AccessToken;
                account.AccessTokenExpiresIn  = DateTime.UtcNow.AddSeconds(result.Data.AccessTokenExpiresIn);
                account.RefreshToken          = result.Data.RefreshToken;
                account.RefreshTokenExpiresIn = DateTime.UtcNow.AddSeconds(result.Data.RefreshTokenExpiresIn);
                await _advertAccountManager.UpdateAsync(account);

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
            finally
            {
                httpClient.Dispose();
            }
        }
Beispiel #8
0
        /// <summary>
        /// 查询每日消耗
        /// </summary>
        /// <param name="account"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public async Task <bool> QueryDailyReportsAsync(AdvertAccount account,
                                                        DateTime startDate,
                                                        DateTime endDate)
        {
            if (!account.IsAuth())
            {
                return(false);
            }

            if (account.IsAuthExpires())
            {
                await RefreshAccessTokenAsync(account);
            }

            var product = await _productManager.GetByIdAsync(account.ProductId);

            if (product == null)
            {
                return(false);
            }

            string reqURL = DailyReportAddress();

            List <KeyValuePair <String, String> > paramList = new List <KeyValuePair <String, String> >();

            paramList.Add(new KeyValuePair <string, string>("advertiser_id", account.ThirdpartyId));
            paramList.Add(new KeyValuePair <string, string>("start_date", startDate.DateString()));
            paramList.Add(new KeyValuePair <string, string>("end_date", endDate.DateString()));
            paramList.Add(new KeyValuePair <string, string>("time_granularity", "STAT_TIME_GRANULARITY_DAILY"));
            paramList.Add(new KeyValuePair <string, string>("page_size", "1000"));

            var httpClient = new HttpClient();

            AddAccessToken2Request(account, httpClient);
            try
            {
                var response = await httpClient.PostAsync(new Uri(reqURL), new FormUrlEncodedContent(paramList));

                var jsonResultString = await response.Content.ReadAsStringAsync();

                var result = JsonConvert.DeserializeObject <ToutiaoAdvertResponse <ToutiaoDailyReportListResponse> >(jsonResultString);
                var datas  = result.Data.List.OrderByDescending(l => l.StatDatetime).ToList();

                foreach (var item in datas)
                {
                    if (item.AdvertiserId.IsNullOrEmpty())
                    {
                        continue;
                    }

                    if (item.Cost == decimal.Zero)
                    {
                        continue;
                    }

                    var dataImport = new AdvertStatisticImport()
                    {
                        AdvertAccountId = account.Id,
                        ProductId       = account.ProductId,
                        ProductName     = product.Name,
                        StatisticOnUtc  = item.StatDatetime.GetStartTimeOfDate(),

                        ClickNum      = item.Click,
                        DisplayNum    = item.Show,
                        ClickPrice    = item.Click > 0 ? Math.Round(item.Cost / item.Click, 4) : 0,
                        ThDisplayCost = item.Show > 0 ? Math.Round(item.Cost / item.Show * 1000, 4) : 0,
                        TotalCost     = item.Cost,
                    };

                    await _advertDailyStatisticManager.InsertOrUpdateAdvertStatisticAsync(dataImport);
                }
            }
            catch (Exception)
            {
                return(false);
            }
            finally
            {
                httpClient.Dispose();
            }

            return(true);
        }
Beispiel #9
0
 /// <summary>
 /// 同步订单
 /// </summary>
 /// <param name="account"></param>
 /// <param name="startDate"></param>
 /// <param name="endDate"></param>
 /// <returns></returns>
 public async Task <bool> SyncOrders(AdvertAccount account, DateTime startDate, DateTime endDate)
 {
     return(await Task.FromResult(true));
 }
Beispiel #10
0
        /// <summary>
        /// 查询每日消耗
        /// </summary>
        /// <param name="account"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public async Task <bool> QueryDailyReportsAsync(AdvertAccount account,
                                                        DateTime startDate,
                                                        DateTime endDate)
        {
            if (!account.IsAuth())
            {
                return(false);
            }

            if (account.IsAuthExpires())
            {
                await RefreshAccessTokenAsync(account);
            }

            var product = await _productManager.GetByIdAsync(account.ProductId);

            var reqURL = DailyRepoersAddress() + GetRequestPara(account);

            var dataParam = new DateRangePara()
            {
                StartDate = startDate.DateString(),
                EndDate   = endDate.DateString(),
            };

            bool readEnd   = false;
            int  pageIndex = 1;
            int  pageSize  = 1000;

            var dateRange = JsonConvert.SerializeObject(dataParam).UrlDecode();

            var httpClient = new HttpClient();

            try
            {
                while (!readEnd)
                {
                    List <KeyValuePair <String, String> > paramList = new List <KeyValuePair <String, String> >();
                    paramList.Add(new KeyValuePair <string, string>("account_id", account.ThirdpartyId));
                    paramList.Add(new KeyValuePair <string, string>("level", "ADGROUP"));
                    paramList.Add(new KeyValuePair <string, string>("date_range", dateRange));
                    paramList.Add(new KeyValuePair <string, string>("group_by", "[\"date\"]"));
                    paramList.Add(new KeyValuePair <string, string>("page", pageIndex.ToString()));
                    paramList.Add(new KeyValuePair <string, string>("pageSize", pageSize.ToString()));

                    var response = await httpClient.PostAsync(new Uri(reqURL), new FormUrlEncodedContent(paramList));

                    var jsonResultString = await response.Content.ReadAsStringAsync();

                    var result = JsonConvert.DeserializeObject <TenantAdvertRequestResult <TenantDailyAdvert> >(jsonResultString);

                    foreach (var dailyStatistic in result.Data.Items)
                    {
                        //统计日期
                        var dataOnUtc = dailyStatistic.Date.LocalTimeConverUtcTime(_dateTimeHelper);

                        var dto = new AdvertStatisticImport()
                        {
                            AdvertAccountId = account.Id,
                            ProductId       = account.ProductId,
                            ProductName     = product.Name,
                            StatisticOnUtc  = dailyStatistic.Date,

                            ClickNum      = dailyStatistic.Click,
                            DisplayNum    = dailyStatistic.Impression,
                            ClickPrice    = Math.Round((dailyStatistic.Cost / 100) / dailyStatistic.Click, 4),
                            ThDisplayCost = Math.Round((dailyStatistic.Cost / 100) / dailyStatistic.Impression * 1000, 4),
                            TotalCost     = dailyStatistic.Cost / 100,
                        };

                        await _advertDailyStatisticManager.InsertOrUpdateAdvertStatisticAsync(dto);
                    }

                    readEnd = (pageIndex) * pageSize > result.Data.PageInfo.TotalNumber;
                }
            }
            catch (Exception)
            {
                return(false);
            }
            finally
            {
                httpClient.Dispose();
            }
            return(true);
        }
Beispiel #11
0
        /// <summary>
        /// 同步订单
        /// </summary>
        /// <param name="account"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public async Task <bool> SyncOrders(AdvertAccount account, DateTime startDate, DateTime endDate)
        {
            bool readEnd   = false;
            int  pageIndex = 1;
            int  pageSize  = 100;

            while (!readEnd)
            {
                var response = await QueryOrderAsync(account, startDate, endDate, pageIndex, pageSize);

                if (response.Code > 0)
                {
                    _logger.Error(string.Format("订单同步失败。{0}", response.Message));
                    break;
                }

                foreach (var orderData in response.Data.Orders)
                {
                    var orderDto = new OrderImport()
                    {
                        OrderSource     = OrderSource.Tenant,
                        StoreId         = account.StoreId,
                        AdvertAccountId = account.Id,
                        OrderNumber     = orderData.OrderId,
                        ProductSku      = GetSku(orderData.PackageInfo),
                        OrderStatus     = OrderStatus.WaitConfirm,
                        ShippingStatus  = ShippingStatus.NotYetShipped,
                        OrderTotal      = Convert.ToDecimal(orderData.TotalPrice) / 100,

                        PackageNum  = orderData.Quantity,
                        PackageName = orderData.PageName,

                        CustomerComment = GetSelectPackageInfo(orderData),

                        ReceiverName = orderData.UserName,
                        Telephone    = orderData.UserPhone,
                        FullAddress  = orderData.UserAddress,
                        Address      = orderData.UserAddress,
                        Province     = orderData.UserProvince,
                        City         = orderData.UserCity,
                        District     = orderData.UserArea,

                        PlaceOnUtc   = orderData.OrderTime.LocalTimeConverUtcTime(_dateTimeHelper),
                        CreatedOnUtc = orderData.OrderTime.LocalTimeConverUtcTime(_dateTimeHelper),
                    };

                    try
                    {
                        await _orderImportor.ImportOrderAsync(orderDto);
                    }
                    catch (Exception exc)
                    {
                        _logger.Error(string.Format("订单同步失败。{0}", exc.Message), exc);
                    }
                }

                readEnd = (pageIndex) * response.Data.PageInfo.PageSize > response.Data.PageInfo.TotalNumber;

                pageIndex += 1;
            }

            return(true);
        }