Here is an example of a helper class that you could use:
<?php class Paypal { const VERSION = 51.0; private $allowedEnvs = array( 'beta-sandbox', 'live', 'sandbox' ); private $config = array(); private $url; public function __construct($username, $password, $signature, $environment = 'live') { 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 ); } 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); } private function encodeFields(array $fields) { return array_map('urlencode', $fields); } private function decodeFields(array $fields) { return array_map('urldecode', $fields); } private function getUrl() { if (is_null($this->url)) { switch ($this->config['environment']) { case 'sandbox': case 'beta-sandbox': $this->url = "https://api-3t.$environment.paypal.com/nvp"; break; default: $this->url = 'https://api-3t.paypal.com/nvp'; } } return $this->url; } }
And can be used as:
<?php include 'Paypal.php'; $paypal = new Paypal('username', 'password', 'signature'); $response = $paypal->call('GetBalance'); print_r($response);
More details
source share