0

有没有办法通过不使用 PayPal SDK 为第三方生成身份验证标头。我已经得到了他们的访问令牌和秘密。然而,这些都是通过 curl 请求完成的,这对我来说很简单。反正有这样做吗?

另外,要生成标头,我需要第三方的 API 签名吗?我怎么会得到这个?

感谢您的帮助。

4

2 回答 2

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 使用常用方法从对“/Permissions/GetAccessToken”的调用中返回,并包含一个令牌和 tokenSecret 对,用于代表第三方进行操作。方法是 POST,终点是“ https://svcs.sandbox.paypal.com/Permissions/GetBasicPersonalData ”。

使用上面的方法可能看起来像这样:

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");
};
于 2015-03-02T22:16:04.983 回答
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'])
于 2015-07-29T11:02:14.920 回答