生成身份验证标头

时间:2013-07-31 17:19:00

标签: paypal

是否有办法通过不使用PayPal SDK为第三方生成身份验证标头。我已经获得了他们的访问令牌和秘密。然而,这些都是通过我直截了当的卷曲请求。无论如何都要这样做吗?

另外,为了生成标题,我需要第三方的API签名?我怎么能得到这个?

感谢您的帮助。

2 个答案:

答案 0 :(得分:4)

对于其他任何寻找PayPal X-PAYPAL-AUTHORIZATION标头值的node.js解决方案的人来说,我写道:

function PayPalURLEncoder(s)
{
    var hex = "0123456789abcdef";
    var untouched = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_";
    var result = s.split('').map(function(c){
        if (untouched.indexOf(c)>=0)    { return c; }
        else if (c==' ')                { return "+"; }
        else
        {
            // Needs converting to HEX
            var code = c.charCodeAt(0);
            return "%" + hex.charAt((code & 0xf0) >> 4) + hex.charAt(code & 0xf);
        }
    });
    return result.join('');
}

exports.authorizationToken = function(accessToken,method,endpoint)
{
    var PARAM_DELIMETER = "&";
    var PARAM_SEPERATOR = "=";
    var token = { key : accessToken.token, secret : accessToken.tokenSecret};
    var consumer = { key : global.config.paypal.username, secret : global.config.paypal.password };

    // Add params
    var params = {
        "oauth_consumer_key" : consumer.key,
        "oauth_version" : "1.0",
        "oauth_signature_method" : "HMAC-SHA1",
        "oauth_token" : token.key,
        "oauth_timestamp" : Math.round(new Date().getTime() / 1000),
    };

    // Convert params into paramString
    var paramKeys = [];
    var paramString = "";
    for (var p in params) { paramKeys.push(p); } paramKeys.sort();
    for (var i=0; i<paramKeys.length; i+=1)
    {
        var p = paramKeys[i];
        paramString += (p + PARAM_SEPERATOR + params[p]);
        if (i+1<paramKeys.length) paramString += PARAM_DELIMETER;
    }

    // Create signature
    var key = PayPalURLEncoder(consumer.secret) + PARAM_DELIMETER + PayPalURLEncoder(token.secret);
    var signatureBase = method + PARAM_DELIMETER + PayPalURLEncoder(endpoint) + PARAM_DELIMETER + PayPalURLEncoder(paramString);
    var signature = CryptoJS.HmacSHA1(signatureBase, key).toString(CryptoJS.enc.Base64);
    return "token="+token.key+",signature="+signature+",timestamp="+params["oauth_timestamp"];
};

AuthToken从对&#34; / Permissions / GetAccessToken&#34;的调用返回使用常用方法并包含令牌和tokenSecret对,以代表第三方进行操作。方法将是POST,结束点将类似于&#34; https://svcs.sandbox.paypal.com/Permissions/GetBasicPersonalData&#34;。

使用上述方法可能如下所示:

exports.basicDetails = function(accessToken, callback)
{
    var http = require('https');
    var host = global.config.paypal.sandbox ? 'svcs.sandbox.paypal.com' : 'svcs.paypal.com';
    var path = '/Permissions/GetBasicPersonalData';
    var options = {
        host: host,
        path: path,
        method: 'POST',
        headers: {
            "X-PAYPAL-AUTHORIZATION" : exports.authorizationToken(accessToken,"POST","https://"+host+path),
            "X-PAYPAL-REQUEST-DATA-FORMAT" : "NV",
            "X-PAYPAL-RESPONSE-DATA-FORMAT" : "JSON",
            "X-PAYPAL-APPLICATION-ID" : global.config.paypal.sandbox ? "<<YOURAPPIDSANDBOX>>" : "<<YOURAPPID>>",
        },
    };
    var req = http.request(options, function(res){
        var str = "";
        res.setEncoding('utf8');
        res.on('data', function (chunk) { str += chunk; });
        res.on('end', function () {
            if (callback) callback(false,JSON.parse(str));
        });
    });
    req.on('error',function(e){
        if (callback) callback("Unable to connect with PayPal");
    });
    req.end("attributeList.attribute(0)=http://axschema.org/contact/email&attributeList.attribute(1)=http://schema.openid.net/contact/fullname&requestEnvelope.errorLanguage=en_US");
};

答案 1 :(得分:0)

基于Aku共享的代码,我已将其移植到Python。不幸的是,这仍然导致验证失败响应,错误代码为10002. FWIW,这里是:

from hashlib import sha1
import hmac
from base64 import b64encode
from urllib import urlencode
from datetime import datetime

def paypal_urlencode(s):
    encode = lambda x: x if x in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_+" else '%%%x' % ord(x)
    return ''.join(map(encode, s.replace(' ','+')))

def paypal_authorisation(token, ep, consumer, method="POST", sandbox=True):
    params = dict(
        oauth_consumer_key=consumer['key'],
        oauth_version='1.0',
        oauth_signature_method="HMAC-SHA1",
        oauth_token=token['key'],
        oauth_timestamp=datetime.now().strftime('%s')
    )
    key = "&".join((paypal_urlencode(consumer['secret']), paypal_urlencode(token['secret'])))
    sig_base = "&".join((method, paypal_urlencode(ep), paypal_urlencode("oauth_consumer_key=%(oauth_consumer_key)s&oauth_signature_method=%(oauth_signature_method)s&oauth_timestamp=%(oauth_timestamp)s&oauth_token=%(oauth_token)s&oauth_version=%(oauth_version)s" % params)))
    h= hmac.new(key.encode('ascii'), sig_base.encode('ascii'), sha1)
    signature=b64encode(h.digest())

    return "token=%s,signature=%s,timestamp=%s" % (token['key'], signature, params['oauth_timestamp'])