如何在网站页面上(Shopify网站之外)显示Shopify购物车价值

时间:2012-04-27 07:02:08

标签: json api shopify

我正在尝试执行以下操作:我正在构建一个标准的HTML / PHP网站。我们将在网站上有产品。当有人点击“添加到购物车”时,用户将被引导到Shopify及其产品信息,该产品将被添加到购物车(到目前为止没问题......完成了这项工作)。当他们在浏览器中点击返回该站点(因此离开Shopify购物车)时,我需要能够在标题中显示该站点上的产品信息。像“5个产品| $ 168.00”这样的东西...基本上允许网站访问者(不是在shopify中,而是在我们构建的HTML网站中)查看购物车中的值,然后在他们想要的时候结帐或查看购物车。 / p>

我遇到了这个:http://api.shopify.com/cart.html#show

我是JSON的新手,正在寻找我正在尝试做的事情的例子,但没有看到它们。

任何建议或指向我正确方向的人都会很棒。

4 个答案:

答案 0 :(得分:8)

Shopify实际上提供了一个JSONP格式的文件,假设您来自同一个域(访问识别个人用户的Shopify cookie)。

换句话说:

让我们说一个Wordpress网站位于www.example.com

随附的"商店网站"将住在shop.example.com(确保此域名是Shopify方面的主域名)

要从Wordpress网站访问购物车并使用jQuery将其处理到您可以调用的模板或页面中:

jQuery.ajax({

    url: "//shop.example.com/cart.json",
    dataType: "jsonp",
    success: function( data ) {
        /* Template Code here */
    },
    error: function( jxhr, status, err ) {
        console.log("Error, status = " + status + ", err = " + err);
    }

});

JSONP格式的文件允许通过一些Javascript技巧进行跨域AJAX调用。

答案 1 :(得分:2)

这两页应该可以帮到你:

Adding to the Cart from a remote website

我不确定你现在要做什么来添加到购物车,但这是“正确”的方式。看到你已经有了这个工作,我不会太担心。

要获得购物车,您应该使用AJAX API。此API允许您在不使用链接到的REST版本的情况下为当前用户提取购物车。那个设计用于做更重的提升(例如获得所有当前活动的推车)。 AJAX版本更加简单,专为前端使用而设计。简单来说,只需致电

http://[the-shop].myshopify.com/cart.js

您将以JSON的形式获取当前会话的购物车内容。它看起来像这样:

{
"items": [
    {
        "handle": "aquarius",
        "line_price": 6000,
        "requires_shipping": true,
        "price": 2000,
        "title": "aquarius - medium",
        "url": "/products/aquarius",
        "quantity": 3,
        "id": 30104042,
        "grams": 181,
        "sku": "",
        "vendor": "the candi factory",
        "image": "http://static.shopify.com/s/files/1/0040/7092/products/aquarius_1.gif?1268045506",
        "variant_id": 30104042
    },
    {
        "handle": "amelia",
        "line_price": 4000,
        "requires_shipping": true,
        "price": 2000,
        "title": "amelia - medium",
        "url": "/products/amelia",
        "quantity": 2,
        "id": 30104012,
        "grams": 200,
        "sku": "",
        "vendor": "the candi factory",
        "image": "http://static.shopify.com/s/files/1/0040/7092/products/2766315_da1b.png?1268045506",
        "variant_id": 30104012
    }
],
"requires_shipping": true,
"total_price": 10000,
"attributes": null,
"item_count": 5,
"note": null,
"total_weight": 947

}

答案 2 :(得分:1)

如果有人遇到同样的问题。 Kameron的答案解决了我的问题。记得改变" .js" to" .json"如果您将dataType设置为" jsonp"

答案 3 :(得分:0)

尝试了许多不同的方法(包括先前的答案)后,这是我发现唯一可行的方法。该策略是在父域上设置一个包含所需信息(在本例中为购物车中的物品数)的cookie,以便可以由具有相同父域的另一个网站访问它。

它需要在Shopify商店上有一个自定义域,即不能与xxxx.myshopify.com一起使用。

在Shopify代码资产中添加一个新的Javascript文件(例如cart.js

function extractDomain(host) {
    let parts = host.split(".");
    parts.shift();
    return parts.join(".");
}

function updateCartCountCookie() {
    fetch('/cart.json')
        .then((data) => {
            data.json().then((cart) => {

                let myDate = new Date();
                myDate.setMonth(myDate.getMonth() + 1);

                document.cookie = 'kh_cart_item_count=' + cart.item_count.toString() + ';expires=' + myDate
                    + ';domain=.' + extractDomain(location.hostname) + ';path=/';
            });
        });
}
/*
 This event fires after cart changes. This is theme dependent and may need to be different.
*/
document.addEventListener("theme:loading:end", () => {
    updateCartCountCookie();
});
/* update on initial load */
document.addEventListener('DOMContentLoaded', () => {
    updateCartCountCookie();
}

将此包含在主题模板中:

    <script src="{{ 'cart.js' | asset_url }}" defer></script>

现在,将在父域中设置Cookie kh_cart_item_count,其中包含购物车中的商品数量。

在您托管在同级域中的外部网站中,将此HTML代码段添加到您希望购物车出现的位置:

<script>
    function getCookieValue(a) {
        var b = document.cookie.match('(^|;)\\s*' + a + '\\s*=\\s*([^;]+)');
        return b ? b.pop() : '';
    }
    document.addEventListener("DOMContentLoaded", () => {
        let count = getCookieValue("kh_cart_item_count");
        let el = document.getElementById("kh-cart-count")
        if (el) {
            el.innerText = count.toString();
            if (!!count && parseInt(count) !== 0)
                el.classList.remove("invisible");
        }
    });
</script>
<style>
</style>
<a href="https://shop.example.com/cart" class="kh-cart-count ml-auto mr-1">

    <svg class="icon icon--cart" viewBox="0 0 27 24" role="presentation">
        <g transform="translate(0 1)" stroke-width="2" stroke="grey" fill="none" fill-rule="evenodd">
            <circle stroke-linecap="square" cx="11" cy="20" r="2"></circle>
            <circle stroke-linecap="square" cx="22" cy="20" r="2"></circle>
            <path d="M7.31 5h18.27l-1.44 10H9.78L6.22 0H0"></path>
        </g>
    </svg>
    <span id="kh-cart-count" class="kh-cart-count invisible">0</span>
</a>

然后将此CSS添加到适当的CSS文件中:

/* shopping cart icon style */
.kh-cart-count {
  width: 4rem;
  height: 4rem;
  display: flex;
  justify-content: right;

  span {
    font-size: 0.8rem;
    font-weight: bold;
    background: #ff0000;
    color: #fff;
    padding: 1px 1px 1px;
    -webkit-border-radius: 20px;
    -moz-border-radius: 20px;
    border-radius: 20px;
    height: 1.2rem;
    width: 1.2rem;
    margin-left: 1.5rem;
    justify-content: center;
    align-items: center;
    position: absolute;
  }

  svg {
    width: 2rem;
    height: 2rem;
    position: absolute;
  }
}

如果在其他窗口中更新购物车时在一个窗口中打开网站,此操作不会自动更新,但是会在每次刷新页面时更新(或者您可以使用window.setInterval(updateCartCount, 10000);对其进行轮询- Cookie更改事件的规范草案,但尚不可用。)

结果如下:

Cart with number

您显然可以将其扩展为传递除购物车计数之外的其他数据。