我没有根据需要获得32个字符的十六进制签名

问题描述 投票:0回答:1

我必须签署我的lastfm api:

  1. 签署你的电话

构造您的api方法签名,方法是首先按参数名称的字母顺序排序调用中发送的所有参数,并使用方案将它们连接成一个字符串。因此,对于auth.getSession的调用,您可能有:

api_keyxxxxxxxxmethodauth.getSessiontokenxxxxxxx

确保您的参数是utf8编码的。现在将您的秘密附加到此字符串。最后,生成结果字符串的md5哈希值。例如,对于秘密等于'mysecret'的帐户,您的api签名将是:

api signature = md5(“api_keyxxxxxxxxmethodauth.getSessiontokenxxxxxxxmysecret”)

其中md5()是md5散列操作,其参数是要散列的字符串。散列操作应返回32个字符的十六进制md5散列。

var myAPI_key="b6720a4ef50c0a1f63419e334fbf9c74";
var myshared_secret="5df5d9e40e9375f043edf1e1fb629236";

var url = window.location.href; // or window.location.href for current url
var captured = /token=([^&]+)/.exec(url)[1]; // Value is in [1] ('384' in our case)
var result = captured ? captured : 'myDefaultValue';
console.log(captured);

function calculateApiSignature(){
  String.prototype.hashCode = function(){

  	    var hash = 0;

  	    if (this.length == 0) return hash;

  	    for (i = 0; i < this.length; i++) {

  	        char = this.charCodeAt(i);

  	        hash = ((hash<<5)-hash)+char;

  	        hash = hash & hash; // Convert to 32bit integer

  	    }

  	    return hash;

  	};
  var string = "api_key" + "b6720a4ef50c0a1f63419e334fbf9c74"+ "methodauth.getSessiontoken"+captured;
  var textoUtf8 = encodeURI(string);
  textoUtf8 = textoUtf8 + myshared_secret;
  console.log("String a firmar : " + textoUtf8);
  var ApiSignature = textoUtf8.hashCode();
  console.log("Api Signature" + ApiSignature);

}
<!DOCTYPE html>
<html>
	<head>
		<title>Menu principal Last FM</title>
		<meta charset="utf-8">
		 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
		<!-- <script type="text/javascript" src="./js/constants.js"></script>-->
			<script type="text/javascript" src="./js/main.js"></script>
		</head>
	<body>
		<h1>Im login to</h1>
		<div id="userData">
<!--<img src="https://lastfm-img2.akamaized.net/i/u/34s/cc637716959b4acecaa1a307e300f61f.png" />-->
		</div>
		<div id="success">
		    <div id="artistName"></div>
		    <div id="artistImage"></div>
		    <div id="artistBio"></div>
		</div>
		<div id="error"></div>

		<button type="button" onclick="loadUserInfoXMLDoc()">Get User information</button>
		<br><br>
		<button type="button" onclick="loadChartTopArtistsJSONDoc()">Get Top Artist Chart</button>
		<button type="button" onclick="calculateApiSignature()">Calculate API</button>

		<table id="demo"></table>

		<p id="artist"></p>

	</body>
</html>

不知道我错过了什么或做错了....我想我按照指示获得api签名....

一旦我有了api_signature,我认为id必须打个电话:

    $.ajax({
    type : 'GET',
    url : 'http://ws.audioscrobbler.com/2.0/?',
    data : 'api_key=b6720a4ef50c0a1f63419e334fbf9c74&' +
           'token:xxxx&'+
           'api_sig:apisig from above',            
    dataType : 'json',
    success : function(data) {
           //hooray
       },
    error : function(code, message){
         //upset
    }
});
javascript ajax utf-8 md5 last.fm
1个回答
0
投票

我找到的解决方案,对我有用:

/*
Metode: https://www.last.fm/api/show/auth.getSession
Objective: Fetch a session key for a user. The third step in the authentication process. See the authentication how-to for more information.
          ( as we are making a web application...https://www.last.fm/api/webauth)
Params:
token (Required) : A 32-character ASCII hexadecimal MD5 hash returned by step 1 of the authentication process (following the granting of
                  permissions to the application by the user)
api_key (Required) : A Last.fm API key.
api_sig (Required) : A Last.fm method signature. See authentication for more information

Api_sig requereix uns quants canvis ( calculs complicats que he anant fent)...

Result JSON expected:
exit ->
{
  "session": {
    "subscriber": 0,
    "name": "edufissure",
    "key": "fem3L_nnsWNwD_yGL4mtVRPOlblLynx5"
  }
}
error ->
{
  "error": 4,
  "message": "Unauthorized Token - This token has not been issued"
}
*/

function calculateApiSignatureStack()
{

/*note in captured i have a string with the actual token....


You can get it from your url: 

var url = window.location.href; // or window.location.href for current url
var captured = /token=([^&]+)/.exec(url)[1]; // Value is in [1] ('384' in our case)
*/

  // Set elsewhere but hacked into this example:
var last_fm_data = {
    'last_token':captured,
    'user': 'bob',
    'secret': '5df5d9e40e9375f043edf1e1fb629236'
};

// Kick it off.
last_fm_call('auth.getSession', {'token': last_fm_data['last_token']});


// Low level API call, purely builds a POSTable object and calls it.
function last_fm_call(method, data){
    // param data - dictionary.
    last_fm_data[method] = false;
    // Somewhere to put the result after callback.

    // Append some static variables
    data.api_key = "b6720a4ef50c0a1f63419e334fbf9c74";
    //data['format'] = 'json';
    data['method'] = method;

    post_data = last_fm_sign(data);
/*
.*/
    console.log("Post data: Last token " + post_data.token + "ApiKey: "+ post_data.api_key + "ApiSig: " + post_data.api_sig);
    sessionStorage.setItem("myApiSig",post_data.api_sig );

    var last_url="http://ws.audioscrobbler.com/2.0/?";
    $.ajax({
      type: "GET",
      url: last_url,
      data : 'method=auth.getSession' +
             '&token='+
             captured+
             '&api_key=b6720a4ef50c0a1f63419e334fbf9c74' +
             '&api_sig='+
              post_data.api_sig+
             '&format=json',
      //data: post_data,
      dataType: 'json',
      success: function(res){
          last_fm_data[method] = res;
          //var	myresposta = JSON.parse(res);
          console.log("Resposta: Name " + res.session.name);// Should return session key.
          console.log("Resposta: Key " + res.session.key);

          //store session key for further authenticate operations...
          sessionStorage.setItem("mySessionKey", res.session.key);
      },
      error : function(code, message){
          console.log("Error en autenticacion");
      }
     });
}

function last_fm_sign(params){
    ss = "";
    st = [];
    so = {};
    so['api_key'] = params['api_key'];
    so['token'] = params['token'];
    Object.keys(params).forEach(function(key){
        st.push(key); // Get list of object keys
    });
    st.sort(); // Alphabetise it
    st.forEach(function(std){
        ss = ss + std + params[std]; // build string
    });
    ss += last_fm_data['secret'];
        // console.log(ss + last_fm_data['secret']);
        // api_keyAPIKEY1323454formatjsonmethodauth.getSessiontokenTOKEN876234876SECRET348264386
    //hashed_sec = $.md5(unescape(encodeURIComponent(ss)));
    var hashed_sec = md5(unescape(encodeURIComponent(ss))); // "2063c1608d6e0baf80249c42e2be5804"
    console.log("La apiSig es: " + hashed_sec);
    so['api_sig'] = hashed_sec; // Correct when calculated elsewhere.
    return so; // Returns signed POSTable object
}
}
© www.soinside.com 2019 - 2024. All rights reserved.