使用jQuery OAUTH检索临时访问令牌

时间:2012-07-11 11:34:29

标签: javascript jquery oauth-2.0 shopify

我正在尝试对Shopify进行API OAUTH2调用以进行身份​​验证。当我转到我的应用程序时,第一个屏幕出现。我按安装,然后它将我重定向回我开始的地方。问题是,当我被重定向时,我似乎无法在我的jQuery ajax函数中捕获它,因此我无法获得我需要从OAUTH创建永久令牌的临时令牌。第二张图显示了按下安装后发生的情况。到目前为止我的代码在下面提出。运行ajax调用后,没有调用console.log()函数。

我的应用的应用网址设置为

http://localhost 

我的应用程序正在运行

http://localhost/shippingcalculator.

我在外部REST客户端程序中测试了调用,并且设法成功获取了访问令牌,因此我的凭据不存在问题。

200OK and then the 302 Redirect

Runs fine in a REST client tester

<!DOCTYPE html>

                 

 <script type="text/javascript">
function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    console.log(window.location.search);
    var results = regex.exec(window.location.search);
    if (results == null) return "";
    else return decodeURIComponent(results[1].replace(/\+/g, " "));
}

function getTemporaryToken(token) {
    jso_configure({
        "shopify": {
            client_id: "67d7af798dd0a42e731af51ffa", //This is your API Key for your App
            //redirect_uri: "", OPTIONAL - The URL that the merchant will be sent to once authentication is complete. Must be the same host as the Return URL specified in the application settings
            authorization: "https://emard-ratke3131.myshopify.com/admin/oauth/authorize",
            //In your case the authorization would be https://SHOP_NAME.myshopify.com/admin/oauth/authorize
            scope: ["read_products"], //Set the scope to whatever you want to access from the API. Full list here: http://api.shopify.com/authentication.html
        }
    });
    $.oajax({
        url: "https://emard-ratke3131.myshopify.com/admin/oauth/authorize",
        jso_provider: "shopify",
        jso_scopes: ["read_products"],
        jso_allowia: true,
        success: function(data) {
            //Use data and exchange temporary token for permanent one
            if (jqXHR.status === 200) {
                console.log("200");
            }
            if (jqXHR.status === 302) {
                console.log("300");
            }
            console.log("Response (shopify):");
            console.log(data);
        },
        error: function(e) {
            console.log("Fail GET Request");
            console.log(e);
        },
        complete: function(xmlHttp) {
            // xmlHttp is a XMLHttpRquest object
            console.log(xmlHttp.status);
        }
    });
    console.log("Code: " + getParameterByName("code"));
}
}
$(document).ready(function() {
    getTemporaryToken();
});
</script>
</head>
<body>
Hello World!
</body>
</html>

1 个答案:

答案 0 :(得分:3)

完成所有这些客户端是一个非常糟糕的主意,您的API密钥将清晰可供任何人查看和使用。除此之外,您将存储令牌?所有浏览器中都内置了跨站点脚本限制,这些限制将阻止JavaScript调用除加载js之外的站点的调用。

您应该真正进行身份验证并从服务器进行所有API调用。