javascript / php - 将亚马逊 awis 示例从 php 移植到 javascript

发布于 2024-12-12 06:07:56 字数 3937 浏览 0 评论 0原文

您好,我正在尝试转换此处找到的 AWIS 请求的 PHP 代码示例:

http://aws .amazon.com/code/AWIS/402

到 javascript/jquery。我觉得我已经非常接近了,但我收到了“未经授权”的 401 响应。我很想让它启动并运行,我想知道是否有人可以告诉我我做错了什么,或者为我指出使用 javascript 的示例的方向。

<html>
    <head>
        <title>AWIS</title>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
        <script type="text/javascript" src="http://crypto-js.googlecode.com/files/2.3.0-crypto-sha256-hmac.js"></script>
        <script type="text/javascript" src="http://crypto-js.googlecode.com/files/2.3.0-crypto-min.js"></script>
    </head>
    <body>
        <div id="output"></div>
        <script>
        var actionName = 'UrlInfo';
        var responseGroupName = 'Rank,LinksInCount';
        var serviceHost = 'awis.amazonaws.com';
        var count = 10;
        var startNum = 1;
        var sigVersion = '2';
        var hashVersion = 'HmacSHA256';
        var accessKeyID = 'XXXAJA664T37BDNPSXXX';
        var accessKey = 'XXXoImq0sZ4J/vYRewLuNjPFXYQ809DfLmzcpXXX';
        var site = 'http://site.com';

        function getURLInfo(){
            var queryParams = buildQueryParams();
            var sig = generateSignature(queryParams);
            var requestURL = 'http://' + serviceHost + '/?' + queryParams + '&Signature=' + sig;
            console.log('requestURL:' + requestURL);

            $.ajax({
                type: 'GET',
                url: requestURL,
                dataType: 'xml',
                crossDomain: true,
                error: function(jqXHR,textStatus, errorThrown){
                    console.log(textStatus + "|" + errorThrown)
                },
                success: function(data, textStatus, jqXHR){
                    console.log(data);
                }
            });


        }

        function ISODateString(d){
          function pad(n){return n<10 ? '0'+n : n}
          return d.getUTCFullYear()+'-'
              + pad(d.getUTCMonth()+1)+'-'
              + pad(d.getUTCDate())+'T'
              + pad(d.getUTCHours())+':'
              + pad(d.getUTCMinutes())+':'
              + pad(d.getUTCSeconds())+'.000Z'
        }   

        function getTimeStamp(){
            var d = new Date();
            var now = ISODateString(d);
            //var hardcoded_time = "2011-10-28T16:33:03.000Z"; //USE THIS TO TEST BETWEEN SAMPLE PHP AND JS
            return now;
        }

        function buildQueryParams(){
            var params = {};
            params.AWSAccessKeyId = accessKeyID;
            params.Action = actionName;
            params.Count = count;
            params.ResponseGroup = responseGroupName;
            params.SignatureMethod = hashVersion;
            params.SignatureVersion = sigVersion;
            params.Start = startNum;
            params.Timestamp = getTimeStamp();
            params.Url = site;

            paramString = $.param(params);
            return paramString;
        }

        function generateSignature(sigParams){
            var sign = "GET\n" + serviceHost + "\n/\n" + sigParams;
            console.log("SIGN: \n" + sign);
            var sigHash = Crypto.HMAC(Crypto.SHA256, sign, accessKey, { asString: true });
            console.log("HMAC:" + sigHash);
            var sigBytes = Crypto.charenc.Binary.stringToBytes(sigHash);
            var sig64 = Crypto.util.bytesToBase64(sigBytes);
            console.log("BASE 64: " + sig64);
            var sigEnc = encodeURIComponent(sig64);
            console.log("ENCODED URL: " + sigEnc)
            return sigEnc;
        }

        function awisResponse(response){
            console.log(response);
        }

        getURLInfo();

        </script>
    </body>
</html>

Hi I'm trying to convert the PHP Code example for an AWIS request found here:

http://aws.amazon.com/code/AWIS/402

to javascript / jquery. I feel like I'm very close, but I'm getting an "unauthorized" 401 response. I would love to get this up and running, and I was wondering if anyone could tell me what I'm doing wrong, or point me in the direction of an example using javascript.

<html>
    <head>
        <title>AWIS</title>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
        <script type="text/javascript" src="http://crypto-js.googlecode.com/files/2.3.0-crypto-sha256-hmac.js"></script>
        <script type="text/javascript" src="http://crypto-js.googlecode.com/files/2.3.0-crypto-min.js"></script>
    </head>
    <body>
        <div id="output"></div>
        <script>
        var actionName = 'UrlInfo';
        var responseGroupName = 'Rank,LinksInCount';
        var serviceHost = 'awis.amazonaws.com';
        var count = 10;
        var startNum = 1;
        var sigVersion = '2';
        var hashVersion = 'HmacSHA256';
        var accessKeyID = 'XXXAJA664T37BDNPSXXX';
        var accessKey = 'XXXoImq0sZ4J/vYRewLuNjPFXYQ809DfLmzcpXXX';
        var site = 'http://site.com';

        function getURLInfo(){
            var queryParams = buildQueryParams();
            var sig = generateSignature(queryParams);
            var requestURL = 'http://' + serviceHost + '/?' + queryParams + '&Signature=' + sig;
            console.log('requestURL:' + requestURL);

            $.ajax({
                type: 'GET',
                url: requestURL,
                dataType: 'xml',
                crossDomain: true,
                error: function(jqXHR,textStatus, errorThrown){
                    console.log(textStatus + "|" + errorThrown)
                },
                success: function(data, textStatus, jqXHR){
                    console.log(data);
                }
            });


        }

        function ISODateString(d){
          function pad(n){return n<10 ? '0'+n : n}
          return d.getUTCFullYear()+'-'
              + pad(d.getUTCMonth()+1)+'-'
              + pad(d.getUTCDate())+'T'
              + pad(d.getUTCHours())+':'
              + pad(d.getUTCMinutes())+':'
              + pad(d.getUTCSeconds())+'.000Z'
        }   

        function getTimeStamp(){
            var d = new Date();
            var now = ISODateString(d);
            //var hardcoded_time = "2011-10-28T16:33:03.000Z"; //USE THIS TO TEST BETWEEN SAMPLE PHP AND JS
            return now;
        }

        function buildQueryParams(){
            var params = {};
            params.AWSAccessKeyId = accessKeyID;
            params.Action = actionName;
            params.Count = count;
            params.ResponseGroup = responseGroupName;
            params.SignatureMethod = hashVersion;
            params.SignatureVersion = sigVersion;
            params.Start = startNum;
            params.Timestamp = getTimeStamp();
            params.Url = site;

            paramString = $.param(params);
            return paramString;
        }

        function generateSignature(sigParams){
            var sign = "GET\n" + serviceHost + "\n/\n" + sigParams;
            console.log("SIGN: \n" + sign);
            var sigHash = Crypto.HMAC(Crypto.SHA256, sign, accessKey, { asString: true });
            console.log("HMAC:" + sigHash);
            var sigBytes = Crypto.charenc.Binary.stringToBytes(sigHash);
            var sig64 = Crypto.util.bytesToBase64(sigBytes);
            console.log("BASE 64: " + sig64);
            var sigEnc = encodeURIComponent(sig64);
            console.log("ENCODED URL: " + sigEnc)
            return sigEnc;
        }

        function awisResponse(response){
            console.log(response);
        }

        getURLInfo();

        </script>
    </body>
</html>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

热风软妹 2024-12-19 06:07:56

[更新]
德普。我想我在这里指出了几个突出的问题,但必须承认我仍然没有完全理解跨站点的问题。

最后一个难题是使用代理,以便 PHP 可以获取 xml。所以这不是一个只有 javascript 的解决方案,但主要是:
http://benalman.com/projects/php-simple-proxy/
[/更新]

我希望你不要因为错误的原因而放弃这个。您会记得 AJAX 中的 X 代表 XML :)

所以两个想法基于 duskwuff 的评论。

  • 您当然可以使用 javascript 解析 XML。您正在使用的函数已经支持“xml”作为数据类型。
  • 看来你的回调部分出了问题。您可以将回调函数传递给完成、成功和/或错误。

代码如下:

$.ajax({
    type: 'GET',
    url: requestURL,
    dataType: 'xml',
    error: function(jqXHR, textStatus, errorThrown){
        console.log(textStatus);
    },
    success: function(data, textStatus, jqXHR){
        console.log(data);
    }
});

您更紧迫的问题在于身份验证,但也许您现在可以使用错误函数及其 errorThrown 参数获得更多详细信息。

我的建议是看看你是否可以在另一个上下文中生成URL,并将其与你必须看到的进行比较,看看你是否做得正确(已经几个月了,但我想我记得有一个亚马逊工具可以生成您的请求 URL)。

[UPDATE]
Derp. I think I pointed out several outstanding issues here, but must admit I still wasn't quite catching onto the problem of cross site.

The final piece of the puzzle is using a proxy so PHP can get the xml. So this isn't a javascript only solution, but mostly it is:
http://benalman.com/projects/php-simple-proxy/
[/UPDATE]

I'd prefer you don't give up on this for the wrong reason. You'll remember that the X in AJAX stands for XML :)

So two ideas based on duskwuff's commments.

  • You surely can parse XML with javascript. The function you are using already supports 'xml' as a datatype.
  • It seems like you are going wrong with the callback part. You can pass a callback function to either complete, success, and/or error.

Here's the code:

$.ajax({
    type: 'GET',
    url: requestURL,
    dataType: 'xml',
    error: function(jqXHR, textStatus, errorThrown){
        console.log(textStatus);
    },
    success: function(data, textStatus, jqXHR){
        console.log(data);
    }
});

Your more pressing problem is in the authentication, but perhaps you will be able to get more details now using the error function and it's errorThrown argument.

My recommendation is to see if you can get the URL generated in another context and compare that to what you have to see if you're doing it right (it's been a few months, but I thought I remember there being an amazon tool that generated the request URL for you).

糖粟与秋泊 2024-12-19 06:07:56

Alexa Web 信息服务不支持 JSONP 操作(例如,您提供的callback 参数将被忽略;响应始终为 XML)。因此,无法从 JavaScript 中使用它。

The Alexa Web Information Service does not support JSONP operation (e.g, the callback parameter you're providing is ignored; the response is always XML). As such, there is no way to use it from JavaScript.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文