Example #1
0
 public void TestApi()
 {
     var authorizeState = new HaravanAuthorizationState()
     {
         ShopName = "mrshop", AccessToken = "LNniFLi1NXES-h9W2BSO0G_OS-WADl1eoKISLj4TehkeqYHRDU77rOAPVA4S90N_fT4qmJGjOT_8Kc4bF0xzr7EvIX-vpfJJFZv5ZXnsXfx2f9n3uTmA1yu4ck1yqy7c6AVLW9mp8OWNgL2q9uWHSe02XnPsDGfjNJDBM_bdbe6u2lTwwTZsIOR9uZxHpxBQli1JgzYz9HhTz6dxGPLpMRGBwAUVw2FbgVYMjRgkL3mtdk9RobtrHS1td1ibMeXtjR2UR3fT2JQyxTMSmCG8ynjVztGWn6kZJiYThZm2C6NYk1dXlK70pW4R1_esBSY6Y02DhuPUPMKc9Ss6fnfZ_AXhqfrPkDYVdR6MHfAfmSgCX9jQc3txaPEONY0uL1j55buStpGE_2VuxGYeikujwNHNaKxFt5bWBbTgNnMMKgB7HVmhUZXCPfWSkweJXCr5XsBGqaR2hYhdZ3dsZXNSdZgTBSHL1bxrSsILclutxxc9vADW"
     };
     var client = new HaravanAPIClient(authorizeState);
     var obj    = client.Get("/admin/products.json");
 }
Example #2
0
        public async Task <Tuple <string, string> > GetAccessToken(string code)
        {
            HaravanAPIAuthorizer      authorizer = GetAuthorizer();
            HaravanAuthorizationState authState  = authorizer.AuthorizeClient(code);

            if (authState != null && authState.AccessToken != null)
            {
                return(new Tuple <string, string>(authState.AccessToken, authState.ShopName));
            }
            return(new Tuple <string, string>("", ""));
        }
Example #3
0
        public async Task <ApiResponse> Delete()
        {
            ApiResponse res = new ApiResponse();

            try
            {
                var authorizeState = new HaravanAuthorizationState()
                {
                    AccessToken = _accessToken
                };
                var client = new HaravanAPIClient(authorizeState);
                var objs   = client.Delete("/web/oauth/revoke");
                res.Data = objs;
                res.Code = HttpStatusCode.OK;
            }
            catch (Exception ex)
            {
                res.Message = "Kết nối đến Haravan thất bại, vui lòng thử lại";
            }
            return(res);
        }
Example #4
0
        public async Task <ApiResponse> CountPage()
        {
            ApiResponse res = new ApiResponse();

            try
            {
                var authorizeState = new HaravanAuthorizationState()
                {
                    AccessToken = _accessToken
                };
                var client = new HaravanAPIClient(authorizeState);
                var objs   = client.Get("/web/themes.json").ToString();
                if (objs.Count() >= 1)
                {
                    res.Data = objs;
                    res.Code = HttpStatusCode.OK;
                }
            }
            catch (Exception ex)
            {
                res.Message = "Kết nối đến Haravan thất bại, vui lòng thử lại";
            }
            return(res);
        }
Example #5
0
        public async Task <ApiResponse> CreateOrUpdatePage(string html, string title, string url, string id, string referPageId = null)
        {
            ApiResponse res = new ApiResponse();

            try
            {
                var authorizeState = new HaravanAuthorizationState()
                {
                    AccessToken = _accessToken
                };
                var client = new HaravanAPIClient(authorizeState);
                var thh    = client.Get("/web/themes.json").ToString();

                var themes = JsonConvert.DeserializeObject <Themes>(thh);
                _log.Warn(thh);
                var theme = themes.themes.FirstOrDefault(x => x.role == "main");
                if (theme == null)
                {
                    return(res);
                }

                string name      = $"punnel-{id}";
                string asset_key = $"templates/page.{name}.liquid";
                var    asset     = new AssetPut()
                {
                    key   = asset_key,
                    value = @"{% layout none %} " + html
                };
                var assets = new ObjPost();
                assets.asset = asset;

                client.Put($"/web/themes/{theme.id}/assets.json", assets);

                _log.Warn("tao page haravan trên theme" + theme.id);
                //page
                Page page    = null;
                long?referId = null;
                if (string.IsNullOrEmpty(referPageId) == false)
                {
                    referId = long.Parse(referPageId);
                }
                if (referId != null)
                {
                    var sp = client.Get($"/web/pages/{referId}.json");
                    if (sp != null)
                    {
                        page = JsonConvert.DeserializeObject <ObjWrap>(sp.ToString()).page;
                    }
                }

                ObjPost objPage = new ObjPost();
                if (page == null)
                {
                    objPage.page = new PagePost()
                    {
                        title           = title,
                        body_html       = $"Landing page {title}. Click nút [Xem thử] để xem trang",
                        published       = true,
                        template_suffix = name,
                        handle          = url
                    };
                    var obj = client.Post("/web/pages.json", objPage);
                    page = JsonConvert.DeserializeObject <ObjWrap>(obj.ToString()).page;
                }
                else
                {
                    objPage.page = new PagePost()
                    {
                        id              = page.id,
                        title           = title,
                        body_html       = $"Landing page {title}. Click nút [Xem thử] để xem trang",
                        published       = true,
                        template_suffix = name,
                        handle          = url
                    };
                    var obj = client.Put($"/web/pages/{page.id}.json", objPage);
                    page = JsonConvert.DeserializeObject <ObjWrap>(obj.ToString()).page;
                }

                res.Data = page.id;
                res.Code = HttpStatusCode.OK;
            }
            catch (Exception ex)
            {
                _log.Error(ex);
                res.Message = "Quyền truy cập đến haravan không hợp lệ hoặc đã hết hạn, bạn vui lòng vào phần ứng dụng để kiểm tra lại kết nối!";
            }
            return(res);
        }
Example #6
0
        public static List <QT.Entities.Product> GetProductFromHaravan(string shopname, string accesstoken, QT.Entities.Company company)
        {
            List <QT.Entities.Product> ListProducts = new List <QT.Entities.Product>();
            var authorizeState = new HaravanAuthorizationState()
            {
                ShopName = shopname, AccessToken = accesstoken
            };
            var client = new HaravanAPIClient(authorizeState);

            ProductHaravanInfo listproductHaravan = new ProductHaravanInfo()
            {
                products = new List <Product>()
            };
            bool check = true;
            int  page  = 1;

            while (check)
            {
                Object obj = null;
                try
                {
                    //Mỗi lần lấy về 50 product của haravan
                    string querry = "/admin/products.json?page=" + page.ToString();
                    obj = client.Get(querry);
                }
                catch (Exception ex)
                {
                    check = false;
                    Log.ErrorFormat("HARAVAN : Get/admin/products.json FAILS. ERROR : {0}", ex);
                }
                if (obj != null)
                {
                    ProductHaravanInfo listproduct = JsonConvert.DeserializeObject <ProductHaravanInfo>(obj.ToString());
                    if (listproduct.products.Count > 0)
                    {
                        listproductHaravan.products.AddRange(listproduct.products);
                        page++;
                    }
                    else
                    {
                        check = false;
                    }
                }
                else
                {
                    check = false;
                }
            }


            if (listproductHaravan.products.Count > 0)
            {
                #region Chuyển từ ListProducts of Haravan sang ListProductWebsosanh
                for (int i = 0; i < listproductHaravan.products.Count; i++)
                {
                    if (string.IsNullOrEmpty(listproductHaravan.products[i].published_at) || Common.ObjectToDataTime(listproductHaravan.products[i].published_at) > DateTime.Now)
                    {
                        continue;
                    }
                    //Check số lượng phiên bản variant
                    int variant = listproductHaravan.products[i].variants.Count;
                    //TH variant = 1 (1 phiên bản)
                    if (variant == 1)
                    {
                        #region Product
                        var tmpProduct = new QT.Entities.Product();
                        tmpProduct.Domain = company.Domain;
                        var originalurl = string.Empty;
                        originalurl = company.Website + "products/" + listproductHaravan.products[i].handle;
                        if (company.ID == 7605281528637856297)
                        {
                            tmpProduct.DetailUrl = originalurl + "?ref=10066";
                        }
                        else
                        {
                            tmpProduct.DetailUrl = originalurl + "?utm=websosanh";
                        }

                        tmpProduct.ID = Common.GetIDProduct(originalurl);

                        if (listproductHaravan.products[i].variants[0].sku != null)
                        {
                            tmpProduct.MerchantSku = listproductHaravan.products[i].variants[0].sku;
                        }

                        if (listproductHaravan.products[i].variants[0].inventory_policy == "deny")
                        {
                            //check số lượng hàng còn trong kho
                            if (listproductHaravan.products[i].variants[0].inventory_quantity <= 0)
                            {
                                //17.09.2015 trạng thái là deny thì để là liên hệ
                                tmpProduct.Status = Common.ProductStatus.LienHe;
                                //tmpProduct.Status = Common.ProductStatus.Clear;
                            }
                            else
                            {
                                tmpProduct.Status = Common.ProductStatus.Available;
                            }
                        }
                        else if (listproductHaravan.products[i].variants[0].inventory_policy == "continue")
                        {
                            int inventory_quantity = Common.Obj2Int(listproductHaravan.products[i].variants[0].inventory_quantity);
                            if (inventory_quantity > 0)
                            {
                                tmpProduct.Status = Common.ProductStatus.Available;
                            }
                            else
                            {
                                tmpProduct.Status = Common.ProductStatus.Clear;
                            }
                        }
                        else
                        {
                            tmpProduct.Status = Common.ProductStatus.LienHe;
                        }
                        tmpProduct.Instock     = QT.Entities.Common.GetProductInstockFormStatus(tmpProduct.Status);
                        tmpProduct.Manufacture = listproductHaravan.products[i].vendor;

                        tmpProduct.Name     = listproductHaravan.products[i].title;
                        tmpProduct.HashName = Common.GetHashNameProduct(company.Domain, tmpProduct.Name.Trim());

                        tmpProduct.ProductContent = listproductHaravan.products[i].body_html;

                        CultureInfo cultureInfo = CultureInfo.GetCultureInfo("vi-VN");
                        int         originPrice = 0;
                        int         price       = 0;
                        try
                        {
                            originPrice = (int)Decimal.Parse(listproductHaravan.products[i].variants[0].compare_at_price.ToString(), cultureInfo);
                        }
                        catch (FormatException)
                        {
                        }
                        try
                        {
                            price = (int)Decimal.Parse(listproductHaravan.products[i].variants[0].price.ToString(), cultureInfo);
                        }
                        catch (FormatException ex)
                        {
                            Log.Error("HARAVAN : Parse discounted_price Error. " + listproductHaravan.products[i].variants[0].price + "/r/n" + ex);
                            continue;
                        }
                        if (price <= 0)
                        {
                            Log.Error("HARAVAN : Product price equal = 0" + "Product: ID" + tmpProduct.ID + " - " + tmpProduct.Name);
                            continue;
                        }
                        if (originPrice > price)
                        {
                            tmpProduct.OriginPrice = originPrice;
                            tmpProduct.Price       = price;
                        }
                        else
                        {
                            tmpProduct.OriginPrice = tmpProduct.Price = price;
                        }
                        //Categories
                        tmpProduct.Categories = new List <string>();
                        tmpProduct.Categories.Add(company.Domain);
                        tmpProduct.Categories.Add(listproductHaravan.products[i].product_type);
                        tmpProduct.IDCategories = Common.GetIDClassification(Common.ConvertToString(tmpProduct.Categories, " -> "));

                        // list Url Images
                        if (listproductHaravan.products[i].images != null && listproductHaravan.products[i].images.Count != 0)
                        {
                            tmpProduct.ImageUrls = new List <string>()
                            {
                                listproductHaravan.products[i].images[0].src
                            };
                        }
                        else
                        {
                            tmpProduct.ImageUrls = new List <string>();
                        }
                        if (listproductHaravan.products[i].variants[0] != null)
                        {
                            tmpProduct.VATStatus = listproductHaravan.products[i].variants[0].taxable == false ? Common.VATStatus.NotVAT : Common.VATStatus.HaveVAT;
                        }
                        else
                        {
                            tmpProduct.VATStatus = Common.VATStatus.UndefinedVAT;
                        }
                        ListProducts.Add(tmpProduct);
                        #endregion
                    }
                    // TH có nhiều phiên bản
                    else if (variant > 1)
                    {
                        //check image nếu có ảnh thì = true, ko có = false
                        bool checkImage = false;
                        Dictionary <int, string> dicImage = new Dictionary <int, string>();
                        if (listproductHaravan.products[i].images != null && listproductHaravan.products[i].images.Count != 0)
                        {
                            checkImage = true;
                            for (int k = 0; k < listproductHaravan.products[i].images.Count; k++)
                            {
                                dicImage.Add(listproductHaravan.products[i].images[k].id, listproductHaravan.products[i].images[k].src);
                            }
                        }
                        else
                        {
                            checkImage = false;
                        }
                        for (int j = 0; j < variant; j++)
                        {
                            #region Product
                            var tmpProduct = new QT.Entities.Product();
                            tmpProduct.Domain = company.Domain;
                            string originalurl = string.Empty;
                            originalurl = company.Website + "products/" + listproductHaravan.products[i].handle + "?index=" + (j + 1).ToString();
                            //guphukien.com
                            if (company.ID == 7605281528637856297)
                            {
                                tmpProduct.DetailUrl = originalurl + "&ref=10066";
                            }
                            else
                            {
                                tmpProduct.DetailUrl = originalurl + "&utm=websosanh";
                            }
                            tmpProduct.ID = Common.GetIDProduct(originalurl);
                            if (listproductHaravan.products[i].variants[j].sku != null)
                            {
                                tmpProduct.MerchantSku = listproductHaravan.products[i].variants[0].sku;
                            }
                            //check status inventory_policy
                            if (listproductHaravan.products[i].variants[j].inventory_policy == "deny")
                            {
                                //check số lượng hàng còn trong kho
                                if (listproductHaravan.products[i].variants[j].inventory_quantity <= 0)
                                {
                                    //17.09.2015 trạng thái là deny thì để là liên hệ
                                    tmpProduct.Status = Common.ProductStatus.LienHe;
                                    //tmpProduct.Status = Common.ProductStatus.Clear;
                                }
                                else
                                {
                                    tmpProduct.Status = Common.ProductStatus.Available;
                                }
                            }
                            else if (listproductHaravan.products[i].variants[j].inventory_policy == "continue")
                            {
                                if (listproductHaravan.products[i].variants[j].inventory_quantity <= 0)
                                {
                                    tmpProduct.Status = Common.ProductStatus.Clear;
                                }
                                else
                                {
                                    tmpProduct.Status = Common.ProductStatus.Available;
                                }
                            }
                            else
                            {
                                tmpProduct.Status = Common.ProductStatus.LienHe;
                            }
                            tmpProduct.Instock     = QT.Entities.Common.GetProductInstockFormStatus(tmpProduct.Status);
                            tmpProduct.Manufacture = listproductHaravan.products[i].vendor;
                            string nameproduct = listproductHaravan.products[i].title;
                            if (listproductHaravan.products[i].variants[j].option1 != null)
                            {
                                nameproduct += " " + listproductHaravan.products[i].options[0].name + " " + listproductHaravan.products[i].variants[j].option1;
                            }
                            if (listproductHaravan.products[i].variants[j].option2 != null)
                            {
                                nameproduct += " " + listproductHaravan.products[i].options[1].name + " " + listproductHaravan.products[i].variants[j].option2;
                            }
                            if (listproductHaravan.products[i].variants[j].option3 != null)
                            {
                                nameproduct += " " + listproductHaravan.products[i].options[2].name + " " + listproductHaravan.products[i].variants[j].option3;
                            }
                            tmpProduct.Name     = nameproduct;
                            tmpProduct.HashName = Common.GetHashNameProduct(company.Domain, tmpProduct.Name.Trim());

                            tmpProduct.ProductContent = listproductHaravan.products[i].body_html;

                            CultureInfo cultureInfo = CultureInfo.GetCultureInfo("vi-VN");
                            int         originPrice = 0;
                            int         price       = 0;
                            try
                            {
                                originPrice = (int)Decimal.Parse(listproductHaravan.products[i].variants[j].compare_at_price.ToString(), cultureInfo);
                            }
                            catch (FormatException)
                            {
                            }
                            try
                            {
                                price = (int)Decimal.Parse(listproductHaravan.products[i].variants[j].price.ToString(), cultureInfo);
                            }
                            catch (FormatException ex)
                            {
                                Log.Error("HARAVAN : Parse discounted_price Error. " + listproductHaravan.products[i].variants[0].price + "/r/n" + ex);
                                continue;
                            }
                            if (price <= 0)
                            {
                                Log.Error("HARAVAN : Product price equal = 0" + "Product: ID " + tmpProduct.ID + " - " + tmpProduct.Name);
                                continue;
                            }
                            if (originPrice > price)
                            {
                                tmpProduct.OriginPrice = originPrice;
                                tmpProduct.Price       = price;
                            }
                            else
                            {
                                tmpProduct.OriginPrice = tmpProduct.Price = price;
                            }

                            //Categories
                            tmpProduct.Categories = new List <string>();
                            tmpProduct.Categories.Add(company.Domain);
                            tmpProduct.Categories.Add(listproductHaravan.products[i].product_type);
                            tmpProduct.IDCategories = Common.GetIDClassification(Common.ConvertToString(tmpProduct.Categories, " -> "));

                            // list Url Images
                            if (checkImage)
                            {
                                //check image_id của variant

                                int image_id = Common.Obj2Int(listproductHaravan.products[i].variants[j].image_id);
                                //nếu != 0 thì tìm values trong dicImage tương ứng
                                if (image_id != 0)
                                {
                                    string imageurl = dicImage.Where(kvp => kvp.Key == image_id).Select(kvp => kvp.Value).FirstOrDefault();
                                    if (!string.IsNullOrEmpty(imageurl))
                                    {
                                        tmpProduct.ImageUrls = new List <string>()
                                        {
                                            imageurl
                                        }
                                    }
                                    ;
                                    else
                                    {
                                        tmpProduct.ImageUrls = new List <string>()
                                        {
                                            listproductHaravan.products[i].images[0].src
                                        }
                                    };
                                }
                                // nếu = 0 (null) thì lấy ảnh mặc định images[0].src
                                else
                                {
                                    tmpProduct.ImageUrls = new List <string>()
                                    {
                                        listproductHaravan.products[i].images[0].src
                                    }
                                };
                            }
                            else
                            {
                                tmpProduct.ImageUrls = new List <string>();
                            }
                            if (listproductHaravan.products[i].variants[0] != null)
                            {
                                tmpProduct.VATStatus = listproductHaravan.products[i].variants[0].taxable == false
                                    ? Common.VATStatus.NotVAT
                                    : Common.VATStatus.HaveVAT;
                            }
                            else
                            {
                                tmpProduct.VATStatus = Common.VATStatus.UndefinedVAT;
                            }

                            ListProducts.Add(tmpProduct);
                            #endregion
                        }
                    }
                    else if (variant < 1)
                    {
                        Log.ErrorFormat("HARAVAN : Error : Variant of {0}  = 0", listproductHaravan.products[i].title);
                    }
                }
                #endregion
            }
            return(ListProducts);
        }
Example #7
0
        private void CheckCompanyButton_Click(object sender, EventArgs e)
        {
            Wait.Show("Đang kiểm tra công ty!");
            //idcomnay này có thể là idharavan hoặc id mới đc sinh ra theo domain chính xác
            long idcompany = Common.Obj2Int64(companyIdWSSSpinEdit.Text);

            //QT.Entities.Company company = new QT.Entities.Company(idcompany);
            #region CheckCompany
            try
            {
                DBWebPartnerTableAdapters.CompanyTableAdapter companyAdapter = new DBWebPartnerTableAdapters.CompanyTableAdapter();
                companyAdapter.Connection.ConnectionString = Server.ConnectionString;
                DBWebPartner.CompanyDataTable _companyTable = new DBWebPartner.CompanyDataTable();
                companyAdapter.FillBy_ID(_companyTable, idcompany);
                //Trường hợp cài app thành công nhưng lúc tạo ra company xảy ra lỗi (api.websosanh.vn).
                // Lấy dữ liệu company từ haravan và thêm mới vào database.
                if (_companyTable.Rows.Count == 0)
                {
                    string shopname    = shopNameTextEdit.Text;
                    string accesstoken = accessTokenTextEdit.Text;
                    HaravanAuthorizationState authorizeState = new HaravanAuthorizationState();
                    authorizeState.ShopName    = shopname;
                    authorizeState.AccessToken = accesstoken;
                    var    client = new HaravanAPIClient(authorizeState);
                    object obj    = client.Get("/admin/shop.json");
                    if (obj != null)
                    {
                        ShopHaravanInfo shopharavanInfo = JsonConvert.DeserializeObject <ShopHaravanInfo>(obj.ToString());
                        //domain và website lấy theo domain chính xác được config (hoặc mặc định là shopname.myharavan.com)
                        string website = string.Format("http://{0}/", domainChinhXacTextEdit.Text);
                        Uri    uri     = new Uri(website);
                        String domain  = uri.Host.ToLower();
                        domain = domain.Replace("www.", "");
                        TimeSpan timestartup = new TimeSpan(0, 1, 1, 0);
                        TimeSpan timeSleep   = new TimeSpan(0, 1, 1, 0);
                        Alexa    a           = new Alexa();
                        a = Common.GetRankAlexa(uri.Host);
                        #region Insert
                        try
                        {
                            companyAdapter.Insert(
                                Common.GetIDCompany(domain),
                                authorizeState.ShopName,
                                "Shop in Haravan install App",
                                website,
                                domain,
                                DateTime.Now,
                                shopharavanInfo.shop.phone,
                                shopharavanInfo.shop.email,
                                shopharavanInfo.shop.customer_email,
                                shopharavanInfo.shop.address1,
                                Common.CompanyStatus.WEB_HARAVAN,
                                "",
                                a.AlexaRankContries,
                                a.AlexaRank,
                                timestartup,
                                timeSleep,
                                0,
                                0,
                                DateTime.Now,
                                DateTime.Now,
                                30,
                                0,
                                0,
                                0,
                                "",
                                DateTime.Now,
                                0);
                            Log.InfoFormat("HARAVAN : Insert Company Success With ShopName = {0}", authorizeState.ShopName);
                            MessageBox.Show("Thêm mới công ty thành công!");
                        }
                        catch (Exception ex)
                        {
                            Log.ErrorFormat("HARAVAN : Error Insert Company {0}", ex);
                        }
                        #endregion
                    }
                }
                else
                {
                    MessageBox.Show("Có công ty này!");
                }
            }
            catch (Exception exx)
            {
                Log.ErrorFormat("HARAVAN : CheckCompany {0}", exx);
            }
            #endregion
            Wait.Close();
        }