在Shopify中创建自定义产品

Vas*_*asu 4 shopify

我需要Shopify Storefront创建自定义产品.

文档链接:http://docs.shopify.com/api/product#create

我试过以下代码:

$('#addProduct').click(function() {
        $.ajax({
            url:'https://xxxxxx:yyyyyyyyyy@rmisys.myshopify.com/admin/products.json',
            type: 'POST',
            contentType : 'application/json',
            dataType: 'json',
            data: {
                  "product": {
                    "title": "Burton Custom Freestlye 151",
                    "body_html": "<strong>Good snowboard!</strong>",
                    "vendor": "Burton",
                    "product_type": "Snowboard",
                    "tags": "Barnes & Noble, John's Fav, \"Big Air\""
                  }
                },
            success: function(response) {
                console.log(response);
            },
            error: function(xhr) {
                console.log(xhr.statusText);
            }
        }).done(function(data) {
            console.log(data);
        });
    });
Run Code Online (Sandbox Code Playgroud)

以上代码在ajax请求时显示Chrome控制台中的以下错误:

选项https://rmisys.myshopify.com/admin/products.json 405(不允许)jquery-1.10.2.js:8706选项https://rmisys.myshopify.com/admin/products.json否'访问 - Control-Allow-Origin'标头出现在请求的资源上.因此不允许来源" http://rmisys.myshopify.com "访问.jquery-1.10.2.js:8706 XMLHttpRequest无法加载https://rmisys.myshopify.com/admin/products.json.请求的资源上不存在"Access-Control-Allow-Origin"标头.因此不允许来源" http://rmisys.myshopify.com "访问.design-your-shirt:1错误

Vas*_*asu 5

经过很长一段时间的搜索,我找到了解决方案.

问题是跨源资源共享(CORS).

http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

这用于防止CSRF保护.

https://docs.djangoproject.com/en/1.4/ref/contrib/csrf/

在大多数情况下,API应接受具有相同原始策略的 请求http://en.wikipedia.org/wiki/Same-origin_policy

所以,

如果我们从"http"主机方式请求,我们从Shopify获得以下AJAX请求错误:

请求的资源上不存在"Access-Control-Allow-Origin"标头.

解决方案是在用户使用" http "协议访问我们的网站时将用户重定向到" https " .

我尝试使用以下附加代码并成功添加了自定义产品.

<script>
window.onload = RedirNonHttps();

function RedirNonHttps() {
    if (location.href.indexOf("https://") == -1) {
        location.href = location.href.replace("http://", "https://");
    }
}
</script>
Run Code Online (Sandbox Code Playgroud)

注意:如果我们使用脚本从客户端添加自定义产品,则它不安全,因为密钥随后是公开可用的,用户可以使用该API密钥执行任何他们想要的操作.因此,要保持Secure Auth,然后客户端脚本与Secure Auth交互.

我希望这个答案能为初学者提供CORS(跨源资源共享)的想法.