<?php
/* Paypal Payment-Method class
 * REQUIRES: Database connection
 */
class Paypal {
	public $token = "";
	public $token_url = "https://api.sandbox.paypal.com/v1/oauth2/token";
	public $sale_url = "https://api.sandbox.paypal.com/v1/payments/payment";
	
	public $client_id = "AeUP2RDYj43PmZ16j-eCFXd2bWmyUffTZM1kElrVLcPJzrH8sV5eJek_6DQw";
	public $secret = "EDoqShC7qGMT0ivkHSz9VopvrfXNQu0XRKtRqkuvNIlYTOqvEdYHaOZxXCHX";
	public $curl;
	
	function __construct(){ $this->curl=curl_init(); }
	
	function getAccessToken(){
		$params = array('client_id' => $this->client_id, 'secret' => $this->secret, 'grant_type' => 'client_credentials');
		$headers = array();
		$headers[] = 'Accept: application/json';
		$headers[] = 'Accept-Language: en_US';
		$headers[] = 'Content-Type: application/x-www-form-urlencoded';
		$nvps = ''; foreach($params as $var=>$val){ $nvps .= '&'.$var.'='.urlencode($val); }
		//settings
		curl_setopt($this->curl, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($this->curl, CURLOPT_POST, true);
		curl_setopt($this->curl, CURLOPT_URL, $this->token_url);
		curl_setopt($this->curl, CURLOPT_USERPWD, "{$this->client_id}:{$this->secret}");
		curl_setopt($this->curl, CURLOPT_POSTFIELDS, $nvps);
		curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false);
		
		$result = curl_exec($this->curl);
		if(!$result){//echo "Error: ".curl_error($this->curl)."<br />Code: ".curl_errno($this->curl);
			$this->token = "";
		}else{
			$result_arr = json_decode($result, true);
			$this->token = trim($result_arr['access_token']);
		}
		return $this->token;
	}

	function makeSale($amt){echo $amt;

		/*$this->curl = curl_init();
		$this->getAccessToken();
		$sales_headers = array();
		$sales_headers[] = 'Content-Type: application/json';
		$sales_headers[] = 'Authorization: Bearer '.$this->token;
		
		$params = array(
			"intent" => "sale", 
			"redirect_urls" => array("return_url"=>"http://www.gmail.com", "cancel_url"=>"http://www.yahoo.com"),
			"payer" => array("payment_method"=>"paypal"),
			"transactions" => array(array("amount"=>array("total"=>$amt,"currency"=>"USD")))
		);
		$sales_data = json_encode($params);
		curl_setopt($this->curl, CURLOPT_HTTPHEADER, $sales_headers);
		curl_setopt($this->curl, CURLOPT_VERBOSE, 1);
		curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($this->curl, CURLOPT_TIMEOUT, 30);
		curl_setopt($this->curl, CURLOPT_URL, $this->sale_url);
		curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($this->curl, CURLOPT_POSTFIELDS, $sales_data);
		
		$result = curl_exec($this->curl);
		echo $result;*/
		//curl_close($this->curl);
	}
}
?>