1: <?php
2: use Guzzle\Common\Event;
3: use Guzzle\Http\Client;
4: use Guzzle\Http\Message\EntityEnclosingRequest;
5:
6: require_once 'iGivefirst/Exceptions.php';
7: require_once 'iGivefirst/Common.php';
8: require_once 'iGivefirst/Donor.php';
9: require_once 'iGivefirst/Account.php';
10: require_once 'iGivefirst/Donation.php';
11:
12: 13: 14:
15: class iGivefirst {
16:
17:
18: public $donor;
19:
20: public $account;
21:
22: public $donation;
23:
24: public $client;
25: private $apikey, $apisecret;
26:
27: private $url_root = 'https://api.igivefirst.com';
28: private $url_root_sandbox = 'https://api.igivefirst.mobi';
29:
30: 31: 32: 33: 34: 35:
36: public function __construct($apikey, $apisecret, $sandbox=true) {
37: $this->apikey = $apikey;
38: $this->apisecret = $apisecret;
39:
40: $this->client = new Client($sandbox?$this->url_root_sandbox:$this->url_root);
41: $this->client->setUserAgent('iGivefirst-SDK-PHP/1.0.0');
42:
43: $this->client->getEventDispatcher()->addListener('request.before_send', function (Event $event) {
44: $this->signRequest($event['request']);
45: }, -1);
46:
47: $this->donor = new Donor($this);
48: $this->account = new Account($this);
49: $this->donation = new Donation($this);
50: }
51:
52: public function execute($request) {
53: try {
54: return $request->send();
55: }
56: catch(Guzzle\Http\Exception\CurlException $e) {
57: throw new iGivefirst_HttpError($e->getError());
58: }
59: catch(Guzzle\Http\Exception\ClientErrorResponseException $e) {
60: $r = $e->getResponse();
61:
62: switch($r->getStatusCode()) {
63: case 401:
64: throw new iGivefirst_AuthenticationError();
65: break;
66: case 404:
67: throw new iGivefirst_ObjectNotFound($r);
68: break;
69: case 405:
70: throw new iGivefirst_ObjectAlreadyExists($r);
71: break;
72: default:
73: throw new iGivefirst_HttpError($r->getMessage());
74: }
75: }
76: catch(Guzzle\Http\Exception\ServerErrorResponseException $e) {
77: $r = $e->getResponse();
78: throw new iGivefirst_HttpError($r->getStatusCode());
79: }
80: }
81:
82: private function signRequest($request) {
83: $date = gmdate("D, d M Y H:i:s O", time());
84: $method = $request->getMethod();
85: $body = '';
86: $content_type = $request->getHeader('Content-Type');
87: $u = $request->getUrl(true)->normalizePath()->getPath();
88:
89: if ($request instanceof EntityEnclosingRequest) {
90: $request_body = $request->getBody();
91: if ($request_body)
92: $body = $request_body->getContentMd5();
93: }
94:
95: $hmac = base64_encode(hash_hmac('sha1', "$method\n$body\n$content_type\n$date\n$u", $this->apisecret, true));
96: $auth = "{$this->apikey}:$hmac";
97:
98: $request->setHeader('Date', $date);
99: $request->setHeader('Authorization', 'IGF_HMAC_SHA1 ' . $auth);
100: }
101: }
102: ?>
103: