PHP: 获得PayPal余额(GetBalance API), PHP paypal nvp

 

 

方法一:简单,单一

Paypal.php

<?php

class Paypal
{
    /**
     * API Version
     */
    const VERSION = 51.0;

    /**
     * List of valid API environments
     * @var array
     */
    private $allowedEnvs = array(
        'beta-sandbox',
        'live',
        'sandbox'
    );

    /**
     * Config storage from constructor
     * @var array
     */
    private $config = array();

    /**
     * URL storage based on environment
     * @var string
     */
    private $url;

    /**
     * Build PayPal API request
     *
     * @param string $username
     * @param string $password
     * @param string $signature
     * @param string $environment
     * @throws Exception
     */
    public function __construct($username, $password, $signature, $environment = 'sandbox')
    {
        if (!in_array($environment, $this->allowedEnvs)) {
            throw new Exception('Specified environment is not allowed.');
        }
        $this->config = array(
            'username'    => $username,
            'password'    => $password,
            'signature'   => $signature,
            'environment' => $environment
        );
    }

    /**
     * Make a request to the PayPal API
     *
     * @param  string $method API method (e.g. GetBalance)
     * @param  array $params Additional fields to send in the request (e.g. array('RETURNALLCURRENCIES' => 1))
     * @return array
     * @throws Exception
     */
    public function call($method, array $params = array())
    {
        $fields = $this->encodeFields(array_merge(
            array(
                'METHOD'    => $method,
                'VERSION'   => self::VERSION,
                'USER'      => $this->config['username'],
                'PWD'       => $this->config['password'],
                'SIGNATURE' => $this->config['signature']
            ),
            $params
        ));
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->getUrl());
        curl_setopt($ch, CURLOPT_POST, count($fields));
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $response = curl_exec($ch);
        if (!$response) {
            throw new Exception('Failed to contact PayPal API: ' . curl_error($ch) . ' (Error No. ' . curl_errno($ch) . ')');
        }
        curl_close($ch);
        parse_str($response, $result);
        return $this->decodeFields($result);
    }

    /**
     * Prepare fields for API
     *
     * @param  array  $fields
     * @return array
     */
    private function encodeFields(array $fields)
    {
        return array_map('urlencode', $fields);
    }

    /**
     * Make response readable
     *
     * @param  array  $fields
     * @return array
     */
    private function decodeFields(array $fields)
    {
        return array_map('urldecode', $fields);
    }

    /**
     * Get API url based on environment
     *
     * @return string
     */
    private function getUrl()
    {
        if (is_null($this->url)) {
            switch ($this->config['environment']) {
                case 'sandbox':
                case 'beta-sandbox':
                    $this->url = "https://api-3t.sandbox.paypal.com/nvp";
                    break;
                default:
                    $this->url = 'https://api-3t.paypal.com/nvp';
            }
        }
        return $this->url;
    }
}

 

用法:

<?php

include 'Paypal.php';
$paypal = new Paypal('username', 'password', 'signature');

$response = $paypal->call('GetBalance');

print_r($response);

关于如何获取 username password 和 signature 这三个参数,python: 获得PayPal余额(GetBalance API), python paypal nvp 一文中有提到,可以参阅。

更多参考:PHP: 获得PayPal Transaction信息,payment 信息(GetTransactionDetails API), PHP paypal nvp

 

方法二

GetBalance来自Classic API,尚未包含在REST API中 在这个时候,但你可以直接执行N使用HTTPRequest进行VP调用 这个, API端点:

https://api-3t.paypal.com/nvp

POST请求有效负载:

USER=seller_api1.paypal.com
&PWD=56A9R4JPVFPMER2X
&SIGNATURE=AFcWxV21C7fd0v3bYYYRCpSSRl31AociN2kspFBnMbzOGg6NdiC7ZXtg
&VERSION=109.0
&METHOD=GetBalance
&RETURNALLCURRENCIES=1

响应:

L_AMT0=265.17
L_CURRENCYCODE0=USD
TIMESTAMP=2015-08-09T14:21:25Z
CORRELATIONID=802b0b6666022
ACK=Success
VERSION=109.0
BUILD=000000

还有哟你可以获得[Classic API SDK](http://paypal.github.io/sdk/) 用你喜欢的编程语言,并选择“商家”SDK这次。 我的示例PHP代码可以帮助您了解流程,

<?php
$version = "124";
$user = "API UserName";
$pwd = "API Password";
$signature = "API Signature";
$API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
 
$resArray = CallGetBalance ( $API_Endpoint, $version, $user, $pwd, $signature );
$ack = strtoupper ( $resArray ["ACK"] );
if ($ack == "SUCCESS") {
    $balance = urldecode ( $resArray ["L_AMT0"] );
    $currency = urldecode ( $resArray ["L_CURRENCYCODE0"] );
    echo "Account Balance: " . $balance . " " . $currency;
}
 
 
function CallGetBalance($API_Endpoint, $version, $user, $pwd, $signature) {
    // setting the curl parameters.
    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $API_Endpoint );
    curl_setopt ( $ch, CURLOPT_VERBOSE, 1 );
    curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
    curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt ( $ch, CURLOPT_POST, 1 );
 
    // NVPRequest for submitting to server
    $nvpreq = "METHOD=GetBalance" . "&RETURNALLCURRENCIES=1" . "&VERSION=" . $version . "&PWD=" . $pwd . "&USER=" . $user . "&SIGNATURE=" . $signature;
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $nvpreq );
    $response = curl_exec ( $ch );
 
    $nvpResArray = deformatNVP ( $response );
 
    curl_close ( $ch );
 
    return $nvpResArray;
}
 
/*
 * This function will take NVPString and convert it to an Associative Array and it will decode the response. It is usefull to search for a particular key and displaying arrays. @nvpstr is NVPString. @nvpArray is Associative Array.
 */
function deformatNVP($nvpstr) {
    $intial = 0;
    $nvpArray = array ();
 
    while ( strlen ( $nvpstr ) ) {
        // postion of Key
        $keypos = strpos ( $nvpstr, '=' );
        // position of value
        $valuepos = strpos ( $nvpstr, '&' ) ? strpos ( $nvpstr, '&' ) : strlen ( $nvpstr );
 
        /* getting the Key and Value values and storing in a Associative Array */
        $keyval = substr ( $nvpstr, $intial, $keypos );
        $valval = substr ( $nvpstr, $keypos + 1, $valuepos - $keypos - 1 );
        // decoding the respose
        $nvpArray [urldecode ( $keyval )] = urldecode ( $valval );
        $nvpstr = substr ( $nvpstr, $valuepos + 1, strlen ( $nvpstr ) );
    }
    return $nvpArray;
}

 

或者:

 <?php 
 $info = 'USER=[API_USERNAME]'
        .'&PWD=[API_PASSWORD]'
        .'&SIGNATURE=[API_SIGNATURE]'
        .'&METHOD=TransactionSearch'
        .'&TRANSACTIONCLASS=RECEIVED'
        .'&STARTDATE=2013-01-08T05:38:48Z'
        .'&ENDDATE=2013-07-14T05:38:48Z'
        .'&VERSION=94';

$curl = curl_init('https://api-3t.paypal.com/nvp');
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

curl_setopt($curl, CURLOPT_POSTFIELDS,  $info);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_POST, 1);

$result = curl_exec($curl);

# Bust the string up into an array by the ampersand (&)
# You could also use parse_str(), but it would most likely limit out
$result = explode("&", $result);

# Loop through the new array and further bust up each element by the equal sign (=)
# and then create a new array with the left side of the equal sign as the key and the right side of the equal sign as the value
foreach($result as $value){
    $value = explode("=", $value);
    $temp[$value[0]] = $value[1];
}

# At the time of writing this code, there were 11 different types of responses that were returned for each record
# There may only be 10 records returned, but there will be 110 keys in our array which contain all the different pieces of information for each record
# Now create a 2 dimensional array with all the information for each record together
for($i=0; $i<count($temp)/11; $i++){
    $returned_array[$i] = array(
        "timestamp"         =    urldecode($result["L_TIMESTAMP".$i]),
        "timezone"          =    urldecode($result["L_TIMEZONE".$i]),
        "type"              =    urldecode($result["L_TYPE".$i]),
        "email"             =    urldecode($result["L_EMAIL".$i]),
        "name"              =    urldecode($result["L_NAME".$i]),
        "transaction_id"    =    urldecode($result["L_TRANSACTIONID".$i]),
        "status"            =    urldecode($result["L_STATUS".$i]),
        "amt"               =    urldecode($result["L_AMT".$i]),
        "currency_code"     =    urldecode($result["L_CURRENCYCODE".$i]),
        "fee_amount"        =    urldecode($result["L_FEEAMT".$i]),
        "net_amount"        =    urldecode($result["L_NETAMT".$i]));
}
?>

 

方法三

更多功能,也可以使用官方  PayPal-PHP-SDK

项目地址:http://paypal.github.io/PayPal-PHP-SDK/

 

PHP: 获得PayPal余额(GetBalance API), PHP paypal nvp
PHP: 获得PayPal余额(GetBalance API), PHP paypal nvp

直接安装:

composer require paypal/rest-api-sdk-php:*

或者直接下载:https://github.com/paypal/PayPal-PHP-SDK/wiki/Installation-Direct-Download

PHP: 获得PayPal余额(GetBalance API), PHP paypal nvp
PHP: 获得PayPal余额(GetBalance API), PHP paypal nvp

实例:

https://paypal.github.io/PayPal-PHP-SDK/sample/

first.php

<?php
// 1. Autoload the SDK Package. This will include all the files and classes to your autoloader
// Used for composer based installation
require __DIR__  . '/vendor/autoload.php';
// Use below for direct download installation
// require __DIR__  . '/PayPal-PHP-SDK/autoload.php';

// Step 1 : Provide the ClientId and Secret. Optionally, Replace the given one with your app clientId, and Secret
// https://developer.paypal.com/developer/applications/
$apiContext = new \PayPal\Rest\ApiContext(
    new \PayPal\Auth\OAuthTokenCredential(
        'AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRS',     // ClientID
        'EGnHDxD_qRPdaLdZz8iCr8N7_MzF-YHPTkjs6NKYQvQSBngp4PTTVWkPZRbL'      // ClientSecret
    )
);

// Step 2 : Lets try to create a new Payment as mentioned
$payer = new \PayPal\Api\Payer();
$payer->setPaymentMethod('paypal');

$amount = new \PayPal\Api\Amount();
$amount->setTotal('1.00');
$amount->setCurrency('USD');

$transaction = new \PayPal\Api\Transaction();
$transaction->setAmount($amount);

$redirectUrls = new \PayPal\Api\RedirectUrls();
$redirectUrls->setReturnUrl("https://example.com/your_redirect_url.html")
    ->setCancelUrl("https://example.com/your_cancel_url.html");

$payment = new \PayPal\Api\Payment();
$payment->setIntent('sale')
    ->setPayer($payer)
    ->setTransactions(array($transaction))
    ->setRedirectUrls($redirectUrls);

// Step 3 : Make a Create Call
try {
    $payment->create($apiContext);
    echo $payment;

    echo "\n\nRedirect user to approval_url: " . $payment->getApprovalLink() . "\n";
}
catch (\PayPal\Exception\PayPalConnectionException $ex) {
    // This will print the detailed information on the exception.
    //REALLY HELPFUL FOR DEBUGGING
    echo $ex->getData();
}

运行:

> php -f first.php
{
    "intent": "sale",
    "payer": {
        "payment_method": "paypal"
    },
    "transactions": [
        {
            "amount": {
                "total": "1.00",
                "currency": "USD"
            },
            "related_resources": []
        }
    ],
    "redirect_urls": {
        "return_url": "https://example.com/your_redirect_url.html",
        "cancel_url": "https://example.com/your_cancel_url.html"
    },
    "id": "PAY-3MC96102SY030652JLHXXPMA",
    "state": "created",
    "create_time": "2017-10-24T17:26:07Z",
    "links": [
        {
            "href": "https://api.sandbox.paypal.com/v1/payments/payment/PAY-3MC96102SY030652JLHXXPMA",
            "rel": "self",
            "method": "GET"
        },
        {
            "href": "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-1NT485541R0509947",
            "rel": "approval_url",
            "method": "REDIRECT"
        },
        {
            "href": "https://api.sandbox.paypal.com/v1/payments/payment/PAY-3MC96102SY030652JLHXXPMA/execute",
            "rel": "execute",
            "method": "POST"
        }
    ]
}
Redirect user to approval_url: https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-1NT485541R0509947

That’s it. Follow the steps in our developer docs to get approval from user, and execute a sale on above payment object.

 

更多

python版:python: 获得PayPal余额(GetBalance API), python paypal nvp

更多:PHP: 获得PayPal Transaction信息,payment 信息(GetTransactionDetails API), PHP paypal nvp

 

本文:PHP: 获得PayPal余额(GetBalance API), PHP paypal nvp

2 Comments

Leave a Reply