Example #1
0
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            IsAuthenticated = false;
            ShopName        = string.Empty;
            base.OnActionExecuting(filterContext);
            RavenSession = MvcApplication.Store.OpenSession();

            var authState = ShopifyAuthorize.GetAuthorizationState(HttpContext);

            // ONLY DEV!!!!!!!!!
            if (authState == null)
            {
                authState = new ShopifyAuthorizationState
                {
                    AccessToken = "363fa17b9d1a23b2ebaa53f1ff374c01",
                    ShopName    = "jesse-9"
                };
                ShopifyAuthorize.SetAuthorization(HttpContext, authState);
            }

            if (authState != null)
            {
                ShopifyApi      = new ShopifyAPIClient(authState);
                IsAuthenticated = true;
                ShopName        = authState.ShopName;
            }
            ViewBag.IsAuthenticated = IsAuthenticated;
            ViewBag.ShopName        = ShopName;
        }
Example #2
0
 /// <summary>
 /// Initialize Shopify by creating a Shopify API Client object.
 /// </summary>
 public Shopify(int ID, string account, string token)
 {
     this.ID      = ID;
     this.account = account;
     this._token  = token;
     this._api    = GetAPIClient();
 }
Example #3
0
        public JsonResult OrderDelete(DraftOrder order)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    ShopifyAPIClient api = new ShopifyAPIClient(authState);

                    // Del from shopify store
                    api.Delete("/admin/orders/" + order.Id + ".json");

                    // Del from db
                    repositories.OrderRepository.RemoveById(order.Id);

                    // Find by id product for delete
                    var AllOrders = ((List <DraftOrder>)(CacheManager.List as ArrayList)[1]);
                    var ordcache  = AllOrders.Where(p => p.Id == order.Id).FirstOrDefault();

                    //Remove from cache
                    ((List <DraftOrder>)(CacheManager.List as ArrayList)[1]).Remove(ordcache);

                    return(Json(new { success = "removed" }, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    return(Json(new { error = "Model is not valid" }, JsonRequestBehavior.AllowGet));
                }
            }
            catch (System.Exception e)
            {
                return(Json(new { error = e.Message }, JsonRequestBehavior.AllowGet));
            }
        }
Example #4
0
        public JsonResult ProductDelete(Product product)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    ShopifyAPIClient api = new ShopifyAPIClient(authState);

                    // del from shopify store
                    api.Delete("/admin/products/" + product.Id + ".json");

                    // del from db
                    repositories.ProductRepository.RemoveById(product.Id);

                    // find by id product for delete
                    var AllProducts = ((List <Product>)(CacheManager.List as ArrayList)[0]);
                    var prodcache   = AllProducts.Where(p => p.Id == product.Id).FirstOrDefault();

                    // remove from cache
                    ((List <Product>)(CacheManager.List as ArrayList)[0]).Remove(prodcache);

                    return(Json(new { success = "removed" }, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    return(Json(new { error = "Model is not valid" }, JsonRequestBehavior.AllowGet));
                }
            }
            catch (System.Exception e)
            {
                return(Json(new { error = e.Message }, JsonRequestBehavior.AllowGet));
            }
        }
Example #5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            ShopifyAuthorizationState state = HttpContext.Current.Session["Shopify.AuthState"] as ShopifyAuthorizationState;
            ShopifyAPIClient          client
                = new ShopifyAPIClient(state);

            APIOutput.Text = (string)client.Get("/admin/products.json");
        }
Example #6
0
        public ActionResult Buy(Guid id, string pid)
        {
            ShopifyAuthorizationState authState = Truffle.Shopify.ShopifyAuthorize.GetAuthorizationState(this.HttpContext);
            var api = new ShopifyAPIClient(authState, new JsonDataTranslator());

            WishLuUser user = Graph.GetUserById(id);
            dynamic    prod = api.Get("/admin/products/" + pid + ".json");

            dynamic order = new
            {
                order = new {
                    line_items = new dynamic[1] {
                        new { @variant_id = prod.product.variants[0].id, @quantity = 1 }
                    },
                    customer        = new { first_name = "Tyler", last_name = "Harden", email = "*****@*****.**" },
                    billing_address = new
                    {
                        first_name = "Tyler",
                        last_name  = "Harden",
                        address1   = "1497 Butterfield Circle",
                        phone      = "330-766-0277",
                        city       = "Niles",
                        province   = "Ohio",
                        country    = "United States",
                        zip        = "44446"
                    },
                    shipping_address = new
                    {
                        first_name = user.FirstName,
                        last_name  = user.LastName,
                        address1   = user.ShipAddress1,
                        phone      = "N/A",
                        city       = user.ShipCity,
                        province   = user.ShipStateOrProvince,
                        country    = "United States",
                        zip        = user.ShipZipOrPostalCode
                    },
                    email = "*****@*****.**"
                }
            };

            object res = null;

            try
            {
                res = api.Post("/admin/orders.json", order);
            }
            catch (WebException ex)
            {
                StreamReader sr = new StreamReader(ex.Response.GetResponseStream());

                Logger.Log(sr.ReadToEnd());
            }

            return(View("Buy", res));
        }
Example #7
0
        private static void CollectEntities(ShopifyAPIClient api, JArray summary, string entity, int top, int page, string fieldQuery)
        {
            var entityObject   = (JObject)api.Get($"/admin/{entity}.json?{fieldQuery}limit={top}&page={page}");
            var entitiesObject = entityObject.GetValue($"{entity}");

            foreach (var entityObj in entitiesObject.Cast <JObject>())
            {
                summary.Add(entityObj);
            }
        }
Example #8
0
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            ShopifyAuthorizationState authState = ShopifyAuthorize.GetAuthorizationState(this.HttpContext);

            if (authState != null)
            {
                _shopify = new ShopifyAPIClient(authState, new JsonDataTranslator());
            }
        }
Example #9
0
        /// <summary>
        /// Get API Client object with connection to a Shopify store.
        /// </summary>
        /// <returns></returns>
        public ShopifyAPIClient GetAPIClient()
        {
            ShopifyAuthorizationState authState = new ShopifyAuthorizationState();

            authState.ShopName    = this.account;
            authState.AccessToken = this._token;

            ShopifyAPIClient api = new ShopifyAPIClient(authState);

            return(api);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            ShopifyAuthorizationState state = HttpContext.Current.Session["Shopify.AuthState"] as ShopifyAuthorizationState;
            ShopifyAPIClient          client
                = new ShopifyAPIClient(state);
            string shopData = (string)client.Get("/admin/products.json");
            JavascriptSerializer serializer = new JavascriptSerializer();
            // Here Product is a object class which contains all of the attribute that JSON has.
            List <Product> lstProduct = serializer(shopData);

            GridView1.DataSource = lstProduct;
            GridView1.DataBind();
        }
Example #11
0
        public object CreateEntity(string entity, string token, string shopName, object body)
        {
            var authState = new ShopifyAuthorizationState
            {
                AccessToken = token,
                ShopName    = shopName
            };

            var api = new ShopifyAPIClient(authState, new JsonDataTranslator());

            var res = api.Post($"/admin/{entity}.json", body);

            return(res);
        }
Example #12
0
        public object DeleteEntity(string entity, string token, string shopName, string id)
        {
            var authState = new ShopifyAuthorizationState
            {
                AccessToken = token,
                ShopName    = shopName
            };

            var api = new ShopifyAPIClient(authState, new JsonDataTranslator());

            var res = api.Delete($"/admin/{entity}/{id}.json");

            return(res);
        }
Example #13
0
        public dynamic GetEntities(string entity, string token, string shopName, string[] fields, int top, string collectionId)
        {
            var authState = new ShopifyAuthorizationState
            {
                AccessToken = token,
                ShopName    = shopName
            };
            var api = new ShopifyAPIClient(authState, new JsonDataTranslator());

            var fieldQuery = "";
            var summary    = new JArray();

            if (fields.Length != 0)
            {
                var commaSeparatedFields = string.Join(",", fields);
                fieldQuery = "fields=" + commaSeparatedFields + "&";
            }

            if (collectionId != null)
            {
                fieldQuery = fieldQuery + "collection_id=" + collectionId + "&";
            }

            if (top == 0 || top > 250)
            {
                dynamic count = api.Get($"/admin/{entity}/count.json");

                var    json      = count;
                double realCount = int.Parse(json.GetValue("count").ToString());
                realCount = realCount / 250;
                var loops = (int)Math.Ceiling(realCount);

                if (entity == "webhooks")
                {
                    loops = 1;
                }

                for (var i = 1; i <= loops; i++)
                {
                    CollectEntities(api, summary, entity, 250, i, fieldQuery);
                }
            }
            else
            {
                CollectEntities(api, summary, entity, top, 1, fieldQuery);
            }

            return(summary);
        }
Example #14
0
        public ActionResult Give(string id)
        {
            //string referrer = Request.UrlReferrer.ToString();
            string qs = Request.QueryString.ToString();

            // pass the supplied JSON Data Translator
            //var api = new ShopifyAPIClient((ShopifyAuthorizationState)Session["authState"], new JsonDataTranslator());

            ShopifyAuthorizationState authState = Truffle.Shopify.ShopifyAuthorize.GetAuthorizationState(this.HttpContext);
            var api = new ShopifyAPIClient(authState, new JsonDataTranslator());

            var model = api.Get("/admin/products/" + id + ".json");

            return(View("Give", model));
            //return View("Give", referrer);
            //return View("Give", new { product = new { @id = id }, qs = qs });
        }
Example #15
0
        public ProductDataSource()
        {
            // TODO: Of course it's a bad idea to hardcode this. In fact having this in your app is a bad idea period. This really should be exposed via
            // your own custom REST API that then connected to Shopify's.
            // This is just an example to show that it can be done, not how it *should* be done.
            ShopifyAuthorizationState authState = new ShopifyAuthorizationState
            {
                ShopName    = "buckridge-hyatt6895",
                AccessToken = "42d4917ed3507278c748046addb01f3d"
            };

            var api = new ShopifyAPIClient(authState, new JsonDataTranslator());

            // The JSON Data Translator will automatically decode the JSON for you
            var result = api.Get("/admin/products.json");

            result.Completed = delegate(IAsyncOperation <dynamic> asyncAction, AsyncStatus asyncStatus)
            {
                var data     = asyncAction.GetResults();
                var products = data.products;

                foreach (var product in products)
                {
                    var group = new ProductDataGroup(product.id.ToString(),
                                                     product.title.ToString(),
                                                     product.vendor.ToString(),
                                                     product.images.Count > 0 ? product.images[0].src.ToString() : "",
                                                     product.body_html.ToString());

                    var imgCount = 0;
                    foreach (var variant in product.variants)
                    {
                        group.Items.Add(new ProductDataItem(variant.id.ToString(),
                                                            variant.option1.ToString(),
                                                            variant.option2.ToString(),
                                                            imgCount < product.images.Count ? product.images[imgCount++].src.ToString() : "",
                                                            "",
                                                            group.Description,
                                                            group));
                    }
                    this.AllGroups.Add(group);
                }
            };
        }
Example #16
0
        /// <summary>
        /// This Action provides data from the Shopify store.
        /// Save the data to database
        /// Return Product List
        /// </summary>
        /// <returns></returns>
        public ActionResult DataList()
        {
            ShopifyAPIClient api = new ShopifyAPIClient(authState);

            JavaScriptSerializer js = new JavaScriptSerializer();

            // Get and Deserialize json products, customers and orders
            #region Deserialize Data form AliClient

            var root_products  = js.Deserialize <RootProductsList>((string)api.Get("/admin/products.json"));
            var root_customers = js.Deserialize <RootCustomersList>((string)api.Get("/admin/customers.json"));
            var root_orders    = js.Deserialize <RootOrdersList>((string)api.Get("/admin/draft_orders.json"));

            #endregion

            // Save to database if the db not exist
            if (!System.Data.Entity.Database.Exists("BuySharpsContext"))
            {
                repositories.ProductRepository.AddRange(root_products.products);
                repositories.CustomerRepository.AddRange(root_customers.Customers);
                repositories.OrderRepository.AddRange(root_orders.draft_orders);
            }

            // Data Caching
            #region Cache Manager

            if (!MemoryCache.Default.Contains("CacheKey"))
            {
                CacheManager.List = new ArrayList {
                    root_products.products,
                    root_orders.draft_orders,
                    root_customers.Customers
                };
            }

            #endregion


            return(Redirect("Product"));
        }
        //
        // GET: /Shopify/Test
        public ActionResult Test()
        {
            var appID = Request.Params["id"];

            using (ShopifyAppsContext context = new ShopifyAppsContext())
            {
                var app = context.ShopifyApps.Find(new Guid(appID));
                ViewData["App"] = app;

                ShopifyAuthorizationState authState = new ShopifyAuthorizationState
                {
                    ShopName    = app.ShopName,
                    AccessToken = app.AccessToken
                };

                var api = new ShopifyAPIClient(authState, new JsonDataTranslator());

                // The JSON Data Translator will automatically decode the JSON for you
                ViewData["ProductData"] = api.Get("/admin/products.json");
            }
            return(View());
        }
Example #18
0
        public dynamic GetEntity(string entity, string id, string token, string shopName, string[] fields, int top)
        {
            var authState = new ShopifyAuthorizationState
            {
                AccessToken = token,
                ShopName    = shopName
            };

            var api = new ShopifyAPIClient(authState, new JsonDataTranslator());

            var     queryString = "";
            dynamic entityObject;

            if (fields.Length != 0)
            {
                var commaSeparatedFields = string.Join(",", fields);
                queryString = "fields=" + commaSeparatedFields + "&";
            }

            if (entity.Equals("collections"))
            {
                entity       = "products";
                entityObject = GetEntities(entity, token, shopName, fields, top, id);
                return(entityObject);
            }
            if (entity.Equals("customer_saved_searches"))
            {
                id = id + "/customers";
                if (top != 0)
                {
                    queryString = queryString + "limit=" + top;
                }
            }
            var urlSuffix = $"/admin/{entity}/{id}.json?{queryString}";

            entityObject = (JObject)api.Get(urlSuffix);

            return(entityObject);
        }
Example #19
0
        public ActionResult ShopifyAuthCallback(string code, string shop, string error)
        {
            if (!string.IsNullOrEmpty(error))
            {
                this.TempData["Error"] = error;
                return(RedirectToAction("Login"));
            }
            if (string.IsNullOrWhiteSpace(code) || string.IsNullOrWhiteSpace(shop))
            {
                return(RedirectToAction("Index", "Home"));
            }

            var shopName   = shop.Replace(".myshopify.com", String.Empty);
            var authorizer = new ShopifyAPIAuthorizer(shopName, ConfigurationManager.AppSettings["Shopify.ConsumerKey"], ConfigurationManager.AppSettings["Shopify.ConsumerSecret"]);

            var authState = authorizer.AuthorizeClient(code);

            if (authState != null && authState.AccessToken != null)
            {
                ShopifyAuthorize.SetAuthorization(HttpContext, authState);

                var shopId     = Id.Shop(shopName);
                var shopInDb   = RavenSession.Load <Shop>(shopId);
                var shopifyApi = new ShopifyAPIClient(authState);

                if (shopInDb == null)
                {
                    RavenSession.Store(new Shop
                    {
                        Id   = shopId,
                        Name = shopName
                    });
                    RavenSession.SaveChanges();
                }

                var jsonResponse = shopifyApi.Get(string.Format("/admin/script_tags.json?src={0}", AppUrl.ShopScript(shopName))).ToString();

                if (Globals.IsLive() && !jsonResponse.Contains("created_at"))
                {
                    dynamic scriptTag = new ExpandoObject();
                    scriptTag.script_tag        = new ExpandoObject();
                    scriptTag.script_tag.@event = "onload";
                    scriptTag.script_tag.src    = "http://t.myvisitors.se/js/";//AppUrl.ShopScript(shopName);
                    var scriptTagJson = JsonConvert.SerializeObject(scriptTag);

                    try
                    {
                        var addScriptResponse = shopifyApi.Post("/admin/script_tags.json", scriptTagJson);
                        if (!addScriptResponse.ToString().Contains("created_at"))
                        {
                            // LOGGER ERROR
                        }
                    }
                    catch (Exception ex)
                    {
                        // LOGGER FATAL
                    }
                }
            }
            return(RedirectToAction("Index", "Home"));
        }