Stripe.class.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. class Stripe{
  3. const ENDPOINT = 'https://api.stripe.com/v1';
  4. public $key = null,$currency='eur';
  5. function __construct($key=null){
  6. $this->key = $key;
  7. }
  8. public function customer($token,$description = '',$mail = ''){
  9. $data = array();
  10. $data['source'] = $token;
  11. $data['description'] = $description;
  12. $data['email'] = $mail;
  13. $data = http_build_query ($data);
  14. $response = self::rest(self::ENDPOINT.'/customers',$this->key.':',$data, 'POST');
  15. if(isset($response['error'])) throw new Exception("[".$response['error']['type']."] : ".$response['error']['message']);
  16. return $response['id'];
  17. }
  18. public function pay($token,$amount,$description = '',$customerDescription=''){
  19. $customer = $this->customer($token,$customerDescription);
  20. $data = array();
  21. $data['amount'] = $amount*100;
  22. $data['currency'] = isset($this->currency) ? $this->currency : 'eur';
  23. $data['customer'] = $customer;
  24. $data['description'] = $description;
  25. $data = http_build_query ($data);
  26. $response = self::rest(self::ENDPOINT.'/charges',$this->key.':',$data, 'POST');
  27. if(isset($response['error'])) throw new Exception("[".$response['error']['type']."] : ".$response['error']['message']);
  28. return $response;
  29. }
  30. public static function rest($url,$authentication = null,$data = array(),$method = 'GET',$headers = array()){
  31. $ch = curl_init($url);
  32. $options = array(
  33. CURLOPT_RETURNTRANSFER => true,
  34. CURLOPT_FOLLOWLOCATION => true,
  35. CURLOPT_SSL_VERIFYPEER => false,
  36. CURLOPT_HTTPAUTH => CURLAUTH_BASIC
  37. );
  38. if(isset($authentication)) $options[CURLOPT_USERPWD] = $authentication;
  39. if(count($headers)!=0) $options[CURLOPT_HTTPHEADER] = $headers;
  40. $options[CURLOPT_CUSTOMREQUEST] = $method;
  41. if($method=='POST' && count($data)!=0) $options[CURLOPT_POSTFIELDS] = $data;
  42. curl_setopt_array($ch, $options);
  43. $result = curl_exec($ch);
  44. if($result === false) throw new Exception("CURL :".curl_error($ch));
  45. curl_close($ch);
  46. $json = json_decode($result,true);
  47. return $json;
  48. }
  49. }
  50. ?>