<?php

class Stripe{
	const ENDPOINT = 'https://api.stripe.com/v1';
	
	public $key = null,$currency='eur';

	function __construct($key=null){
		$this->key = $key;
	}

	public  function customer($token,$description = '',$mail = ''){
		$data = array();
		$data['source'] = $token;
		$data['description'] = $description;
		$data['email'] = $mail;
		
		$data = http_build_query ($data);
		$response = self::rest(self::ENDPOINT.'/customers',$this->key.':',$data, 'POST');
	
		if(isset($response['error'])) throw new Exception("[".$response['error']['type']."] : ".$response['error']['message']);
		return $response['id'];
	}

	public function pay($token,$amount,$description = '',$customerDescription=''){
		$customer = $this->customer($token,$customerDescription);
		$data = array();
		$data['amount'] = $amount*100;
		$data['currency'] = isset($this->currency) ? $this->currency : 'eur';
		$data['customer'] = $customer;
		$data['description'] = $description;
		
		$data = http_build_query ($data);
		$response = self::rest(self::ENDPOINT.'/charges',$this->key.':',$data, 'POST');
		
		if(isset($response['error'])) throw new Exception("[".$response['error']['type']."] : ".$response['error']['message']);
		return $response;
	}


	public static function rest($url,$authentication = null,$data = array(),$method = 'GET',$headers = array()){
		$ch = curl_init($url);
		$options = array(
			CURLOPT_RETURNTRANSFER => true,    
			CURLOPT_FOLLOWLOCATION => true,    
			CURLOPT_SSL_VERIFYPEER => false,
			CURLOPT_HTTPAUTH => CURLAUTH_BASIC
          
		);

		if(isset($authentication))  $options[CURLOPT_USERPWD] = $authentication;
		if(count($headers)!=0) $options[CURLOPT_HTTPHEADER] = $headers;
		$options[CURLOPT_CUSTOMREQUEST] = $method;
		if($method=='POST' && count($data)!=0) $options[CURLOPT_POSTFIELDS] = $data;
			


		curl_setopt_array($ch, $options);
		$result = curl_exec($ch);


		if($result === false) throw new Exception("CURL :".curl_error($ch));
		curl_close($ch);
		$json =  json_decode($result,true);
		return $json;
	}
}

?>