Example #1
0
    /// <summary>
    /// Gets the access token with a previously received code.
    /// </summary>
    /// <param name="client">Client.</param>
    /// <param name="user">User.</param>
    /// <param name="accessCode">Access code.</param>
    public void GetAccessTokenWithCode(ThirdPartyClient client, Coflnet.CoflnetUser user, string accessCode)
    {
        var request    = new RestRequest(client.service.TokenPath);
        var restClient = new RestClient(client.service.GetUrl());

        request.AddHeader("grant_type", "authorization_code");
        request.AddHeader("client_id", client.id);
        request.AddHeader("client_secret", client.secret);
        request.AddHeader("code", accessCode);

        var response = restClient.Execute(request);

        if (response.StatusCode != System.Net.HttpStatusCode.OK)
        {
            throw new CoflnetException("oauth_failed", $"Oauth handshake failed, {client.service.Slug} responded with: `{response.Content}`");
        }


        var binary  = MessagePack.MessagePackSerializer.ConvertFromJson(response.Content);
        var content = MessagePack.MessagePackSerializer.Deserialize <OAuthResponse>(binary);



        Oauth2Token token = new Oauth2Token(user, content.access_token,
                                            client.service,
                                            System.DateTime.Now.AddSeconds(content.expires_in),
                                            content.refresh_token);

        user.ThirdPartyTokens[client.service.Slug] = token;
    }
Example #2
0
        private string CreateJwt(ThirdPartyClient client, Order order, OrderItem[] orderItems, decimal cornOrderSum, int txId)
        {
            var          tokenHandler = new JwtSecurityTokenHandler();
            var          creds        = new SigningCredentials(new SymmetricSecurityKey(Encoding.Default.GetBytes(client.ValidationKey)), SecurityAlgorithms.HmacSha256Signature);
            List <Claim> claims       = new List <Claim>();

            claims.Add(new Claim($"items", JsonConvert.SerializeObject(orderItems.Select(x => new {
                cornAmount = x.CornAmount,
                name       = x.Name,
                usdAmount  = x.UsdAmount,
                itemId     = x.ClientItemId
            }).ToArray()
                                                                       )));

            claims.Add(new Claim("txInfo", JsonConvert.SerializeObject(new
            {
                orderId       = order.OrderId,
                clientOrderId = order.ClientOrderId,
                totalAmount   = cornOrderSum,
                txId          = txId
            })));

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(claims.ToArray()),
                Issuer  = "https://bitcornfarms.com",

                SigningCredentials = creds
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
Example #3
0
        public DeleteApiKeyResponse DeleteApiKey(DeleteApiKeyRequest request)
        {
            DeleteApiKeyResponse response        = new DeleteApiKeyResponse();
            ThirdPartyClient     thirpartyClient = Mapper.Map <ThirdPartyClientViewModel, ThirdPartyClient>(request.ThirdPartyClientViewModel);

            thirdPartyClientRepository.DeleteThirdPartyClient(thirpartyClient);
            return(response);
        }
Example #4
0
        public UpdateApiKeyResponse UpdateApiKey(UpdateApiKeyRequest request)
        {
            UpdateApiKeyResponse response         = new UpdateApiKeyResponse();
            ThirdPartyClient     thirdPartyClient = Mapper.Map <ThirdPartyClientViewModel, ThirdPartyClient>(request.ThirdPartyClientViewModel);

            thirdPartyClientRepository.UpdateThirdPartyClient(thirdPartyClient);
            return(response);
        }
Example #5
0
        public InsertThirdPartyClientResponse  AddThirdPartyClient(InsertThirdPartyClientRequest request)
        {
            InsertThirdPartyClientResponse response = new InsertThirdPartyClientResponse();
            ThirdPartyClient thirdPartyClient       = Mapper.Map <ThirdPartyClientViewModel, ThirdPartyClient>(request.ThirdPartyClientViewModel);

            thirdPartyClientRepository.AddThirdPartyClient(thirdPartyClient);
            return(response);
        }
        public async Task <string> QueryAzureSearch()
        {
            using var client = new ThirdPartyClient(_baseAddress);//this client is 3rd party and has some logic hardcoded

            var result = await client.GetAsync("/");

            return(await result.Content.ReadAsStringAsync());
        }
Example #7
0
        public GetApiKeyByIDResponse GetApiKeyByID(GetApiKeyByIDRequest request)
        {
            GetApiKeyByIDResponse response          = new GetApiKeyByIDResponse();
            ThirdPartyClient      thirdPartyClients = thirdPartyClientRepository.GetApiKeyByID(request.ID);

            ThirdPartyClientViewModel thirdPartyClientsList = Mapper.Map <ThirdPartyClient, ThirdPartyClientViewModel>(thirdPartyClients);

            response.ThirdPartyClientViewModel = thirdPartyClientsList;
            return(response);
        }
Example #8
0
        public JsonResult RefreshCache()
        {
            bool result = false;

            using (var client = new ThirdPartyClient())
            {
                result = client.RefreshThirdPartyCache().Result;
            }
            return(Json(new { msg = result }));
        }
Example #9
0
 public OrderOutput(Order order, ThirdPartyClient client, OrderItem[] items)
 {
     ClientId   = client.ClientId;
     ClientName = client.ClientName;
     OrderId    = order.OrderId;
     Domain     = client.Domain;
     this.Items = items.Select(e => new {
         cornAmount = e.CornAmount,
         usdAmount  = e.UsdAmount,
         name       = e.Name,
         id         = e.ClientItemId,
         quantity   = e.Quantity
     }).ToArray();
 }
        public JsonResult SyncMiaoShaItems(string shopCode)
        {
            var flag = true;

            using (var client = new ThirdPartyClient())
            {
                var response = client.SyncMiaoShaItems(shopCode);
                if (response != null)
                {
                    flag = response.Result;
                }
            }
            return(Json(new
            {
                result = flag
            }));
        }
        public HttpResponseMessage MobileLogin(LoginAPIViewModel loginInfo)
        {
            LoginAPIViewModel loginViewModel = new LoginAPIViewModel();

            try
            {
                Validate("Username", loginInfo.Email);
                Validate("Password", loginInfo.Password);
                Validate("AccountName", loginInfo.AccountName);

                ThirdPartyClient thirdPartyClient = new ThirdPartyClient();
                var domainName = loginInfo.AccountName + ConfigurationManager.AppSettings["STDOMAIN"].ToString();
                thirdPartyClient = thirdPartyClientService.GetCLientSecretKeyByDomainName(domainName);
                if (thirdPartyClient != null)
                {
                    var tokens = GetAccessTokenRespnse(loginInfo.Email, loginInfo.Password, thirdPartyClient.ID);
                    if (!string.IsNullOrEmpty(tokens.AccessToken))
                    {
                        UserViewModel userViewModel = userService.GetUserDetailsByEmailAndAccountId(new GetUserRequest(1)
                        {
                            AccountId = thirdPartyClient.AccountID,
                            UserName  = loginInfo.Email
                        }).User;
                        loginViewModel.AccessToken = tokens.AccessToken;
                        loginViewModel.AccountId   = thirdPartyClient.AccountID;
                        loginViewModel.UserModel   = userViewModel;
                    }
                    else
                    {
                        return(Request.CreateResponse(tokens.Json)); //loginViewModel.ErrorMessage = tokens.Error;
                    }
                }
                else
                {
                    LoginError error = new LoginError();
                    error.error = "Invalid Account";
                    return(Request.CreateResponse(error));
                }
            }
            catch (Exception ex)
            {
                loginViewModel.ErrorMessage = ex.Message.Replace("[|", "").Replace("|]", "");
            }
            return(Request.CreateResponse(loginViewModel));
        }
Example #12
0
        public async Task <string> ProcessAndroidAdInfo(AdInfo adInfo)
        {
            string result = string.Empty;

            try
            {
                var    eventType     = GetEventType(adInfo.Type.ToString());
                var    androidId     = adInfo.AndroidID;
                var    appversion    = adInfo.AppVersion;
                var    osversion     = adInfo.OSVersion.Trim().Replace("Android", "").Trim();
                var    unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                string url           = string.Format(@"http://www.googleadservices.com/pagead/conversion/app/1.0?dev_token=NldQwKEyu5kkEqIKQxz65A&link_id=392487AFBBAC7BD1A3D53D4CF6166499&app_event_type={0}&pdid={1}&id_type=ssaid&lat=0&app_version={2}&os_version={3}&sdk_version={2}&timestamp={4}", eventType, androidId, appversion, osversion, unixTimestamp);
                result = await Get(url);

                JObject obj = JsonConvert.DeserializeObject(result) as JObject;
                // var flag = obj["errors"].Where(p=>!string.IsNullOrWhiteSpace(p));
                var jarray = JArray.Parse(obj["errors"].ToString());
                var flag   = jarray.Count <= 0;
                using (var client = new ThirdPartyClient())
                {
                    if (flag)
                    {
                        client.UpdateAdInfo(adInfo.PKID, StatusType.SuccessTransfer, "");
                    }
                    else
                    {
                        var errormsg = string.Empty;
                        foreach (var arrayitem in jarray)
                        {
                            errormsg += arrayitem;
                            errormsg += "_";
                        }
                        errormsg = errormsg.TrimEnd(new char[] { '_' });
                        client.UpdateAdInfo(adInfo.PKID, StatusType.FailTransfer, errormsg);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error($"Process Android AdInfo error occur in pkid:{adInfo.PKID}", ex);
            }
            return(result);
        }
Example #13
0
        public async void PushAdInfoToGoogle()
        {
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();
            long topPKid = 0;
            long pkid    = 0;

            using (var client = new ThirdPartyClient())
            {
                var response = client.GetTopPKID();
                if (response != null && response.Result > 0)
                {
                    topPKid = response.Result;
                }
                while (pkid <= topPKid)
                {
                    var listAdInforesponse = client.FetchAdInfosByPKID(pkid, 5000);
                    if (listAdInforesponse != null && listAdInforesponse.Result != null)
                    {
                        var andriodList = listAdInforesponse.Result.Where(p => p.TerminalType == Service.ThirdParty.Models.OSType.Android && !string.IsNullOrWhiteSpace(p.AndroidID)).ToList();

                        foreach (var andriodItem in andriodList)
                        {
                            string result = await ProcessAndroidAdInfo(andriodItem);
                        }
                        pkid = listAdInforesponse.Result.LastOrDefault().PKID;
                        //下一次遍历的初始Pkid
                        pkid += 1;
                    }
                }
            }
            stopWatch.Stop();
            TimeSpan ts = stopWatch.Elapsed;

            Logger.Info(string.Format("耗时:{0}s", ts.TotalSeconds));
            //return true;
        }