Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Merge branch 'develop'

  • Loading branch information...
commit 755d9abe589df3855f8fa1600a68167f571d861a 2 parents 95cae3f + 038bbf1
@DHS DHS authored
Showing with 1,291 additions and 501 deletions.
  1. +37 −1 .gitignore
  2. +4 −0 .travis.yml
  3. +19 −0 CHANGELOG.md
  4. +4 −3 README.md
  5. +6 −1 composer.json
  6. +0 −136 examples/demo_partner.php
  7. +45 −25 examples/{demo.php → merchant.php}
  8. +154 −0 examples/partner.php
  9. +65 −0 examples/webhooks.php
  10. +56 −16 lib/{gocardless.php → GoCardless.php}
  11. +14 −10 lib/{gocardless/bill.php → GoCardless/Bill.php}
  12. +111 −258 lib/{gocardless/client.php → GoCardless/Client.php}
  13. +0 −2  lib/{gocardless/exceptions.php → GoCardless/Exceptions.php}
  14. +12 −15 lib/{gocardless/merchant.php → GoCardless/Merchant.php}
  15. +11 −11 lib/{gocardless/pre_authorization.php → GoCardless/PreAuthorization.php}
  16. +175 −0 lib/GoCardless/Request.php
  17. +9 −9 lib/{gocardless/subscription.php → GoCardless/Subscription.php}
  18. +8 −8 lib/{gocardless/user.php → GoCardless/User.php}
  19. +4 −6 lib/{gocardless/utils.php → GoCardless/Utils.php}
  20. +9 −0 phpunit.xml
  21. +28 −0 spec/GoCardlessSpec.php
  22. +3 −0  spec/SpecHelper.php
  23. +38 −0 spec/lib/ClientSpec.php
  24. +12 −0 tests/bootstrap.php
  25. +53 −0 tests/gocardless.php
  26. +41 −0 tests/lib/bill.php
  27. +286 −0 tests/lib/client.php
  28. +46 −0 tests/lib/merchant.php
  29. +41 −0 tests/lib/utils.php
View
38 .gitignore
@@ -1 +1,37 @@
-docs/build
+# Numerous always-ignore extensions
+*.diff
+*.err
+*.orig
+*.log
+*.rej
+*.swo
+*.swp
+*.vi
+*~
+*.sass-cache
+
+# OS or Editor folders
+.DS_Store
+Thumbs.db
+.cache
+.project
+.settings
+.tmproj
+*.esproj
+nbproject
+*.sublime-project
+*.sublime-workspace
+
+# Dreamweaver added files
+_notes
+dwsync.xml
+
+# Komodo
+*.komodoproject
+.komodotools
+
+# Folders to ignore
+.hg
+.svn
+.CVS
+.idea
View
4 .travis.yml
@@ -0,0 +1,4 @@
+language: php
+php:
+ - 5.2
+ - 5.3
View
19 CHANGELOG.md
@@ -0,0 +1,19 @@
+## 0.2.0 - March 21, 2012
+
+- Fixed cancelling subscriptions
+- Abstracted out Request class
+- Started using PHPSpec
+- Improved PSR-0 compatibility
+- Add `state` support to `new_{subscription,pre_authorization,bill}_url`
+- Improved merchant and partner demos
+- Added webhook demo
+
+
+## 0.1.1 - February 27, 2012
+
+- Fixed merchant subscription and user methods
+
+
+## 0.1.0 - February 20, 2012
+
+- Initial release
View
7 README.md
@@ -21,12 +21,12 @@ $ git clone git://github.com/gocardless/gocardless-php.git
#### Installing from the tarball
```console
-$ curl -L https://github.com/downloads/gocardless/gocardless-php/gocardless-php-v0.1.1.tgz | tar xzv
+$ curl -L https://github.com/downloads/gocardless/gocardless-php/gocardless-php-v0.2.0.tgz | tar xzv
```
#### Download the Zip
-[Click here](https://github.com/downloads/gocardless/gocardless-php/gocardless-php-v0.1.1.zip)
+[Click here](https://github.com/downloads/gocardless/gocardless-php/gocardless-php-v0.2.0.zip)
to download the zip file.
#### Installing with Composer
@@ -36,8 +36,9 @@ Add `gocardless/gocardless` to the contents of your composer.json:
```javascript
{
"require": {
- "gocardless/gocardless": ">=0.1.1"
+ "gocardless/gocardless": ">=0.2.0"
}
}
```
+[![Build Status](https://secure.travis-ci.org/gocardless/gocardless-php.png?branch=master)](http://travis-ci.org/gocardless/gocardless-php)
View
7 composer.json
@@ -14,8 +14,13 @@
"email": "dave@gocardless.com",
"homepage": "https://gocardless.com/"
}],
- "version": "0.1.1",
+ "version": "0.2.0",
"require": {
"php": ">= 5.2.0"
+ },
+ "autoload": {
+ "psr-0": {
+ "GoCardless": "lib/"
+ }
}
}
View
136 examples/demo_partner.php
@@ -1,136 +0,0 @@
-<?php
-
-/**
- * First create your partner application in the GoCardless sandbox:
- * https://sandbox.gocardless.com
- *
- * Then grab your application identifier and secret and paste them in below
- *
- * Now test the 'authorize app' link which will generate an access_token
- *
- * Save access_token and merchant_id in your database against the current user
- * And use them to initialize GoCardless for that user
- *
- * NB. You can then paste in access_token and merchant_id below for testing
- * And you may want to replace the ids in the various API calls too.
- *
- *
- * This page then does the following:
- *
- * 1. Generates an authorize link
- * 2. Generates an access_token from the retured $_GET['code']
- * 3. Instantiates a new GoCardless_Client object
- * 4. Fetch the current merchant's details
- * 5. Fetch the current merchant's pre-authorizations
- * 6. Create a bill under a pre-authorizations
- * 7. Repeat steps 4 and 5 with a new GoCardless_Client object
- *
-*/
-
-// Include library
-include_once '../lib/gocardless.php';
-
-// Sandbox
-GoCardless::$environment = 'sandbox';
-
-// Config vars for your PARTNER account
-$account_details = array(
- 'app_id' => null,
- 'app_secret' => null,
- 'access_token' => null,
- 'merchant_id' => null
-);
-
-$gocardless_client = new GoCardless_Client($account_details);
-
-if (isset($_GET['code'])) {
-
- $params = array(
- 'client_id' => $account_details['app_id'],
- 'code' => $_GET['code'],
- 'redirect_uri' => 'http://localhost/examples/demo_partner.php',
- 'grant_type' => 'authorization_code'
- );
-
- // Fetching token returns merchant_id and access_token
- $token = $gocardless_client->fetch_access_token($params);
-
- $account_details = array(
- 'app_id' => null,
- 'app_secret' => null,
- 'access_token' => null,
- 'merchant_id' => null
- );
-
- $gocardless_client = new GoCardless_Client($account_details);
-
- echo '<p>Authorization successful!
- <br />Add the following to your database for this merchant
- <br />Access token: '.$token['access_token'].'
- <br />Merchant id: '.$token['merchant_id'].'</p>';
-
-}
-
-if ($account_details['access_token']) {
- // We have an access token
-
- echo '<h2>Partner authorization</h2>';
-
- echo '<p>Access token found!</p>';
-
- echo '$gocardless_client->merchant()';
- echo '<blockquote><pre>';
- $merchant = $gocardless_client->merchant();
- print_r($merchant);
- echo '</pre></blockquote>';
-
- echo 'echo $gocardless_client->merchant()->pre_authorizations()';
- echo '<blockquote><pre>';
- $preauths = $gocardless_client->merchant()->pre_authorizations();
- print_r($preauths);
- echo '</pre></blockquote>';
-
- echo '$gocardless_client->create_bill($pre_auth_details)';
- echo '<blockquote><pre>';
- $pre_auth_details = array(
- 'pre_authorization_id' => '014PS77JW3',
- 'amount' => '5.00'
- );
- $bill = $gocardless_client->create_bill($pre_auth_details);
- print_r($bill);
- echo '</pre></blockquote>';
-
- $account_details = array(
- 'app_id' => null,
- 'app_secret' => null,
- 'access_token' => null,
- 'merchant_id' => null
- );
-
- $gocardless_client2 = new GoCardless_Client($account_details);
-
- echo 'echo $gocardless_client2->merchant()';
- echo '<blockquote><pre>';
- $merchant = $gocardless_client2->merchant();
- print_r($merchant);
- echo '</pre></blockquote>';
-
- echo '$gocardless_client2->merchant()->pre_authorizations()';
- echo '<blockquote><pre>';
- $preauths = $gocardless_client2->merchant()->pre_authorizations();
- print_r($preauths);
- echo '</pre></blockquote>';
-
-} else {
- // No access token so show new authorization link
-
- echo '<h2>Partner authorization</h2>';
- $authorize_url_options = array(
- 'redirect_uri' => 'http://localhost/examples/demo_partner.php'
- );
- $authorize_url = $gocardless_client->authorize_url($authorize_url_options);
- echo '<p><a href="'.$authorize_url.'">Authorize app</a></p>';
-
-}
-
-?>
View
70 examples/demo.php → examples/merchant.php
@@ -1,12 +1,10 @@
<?php
-// First create your application in the GoCardless sandbox:
-// https://sandbox.gocardless.com
-// Then grab your application id and secret and paste them in below
-// You'll also need to to change the various ids throughout this demo
+// Sign up for an account at GoCardless.com
+// Copy your app id and secret from the developer tab and paste them in below
// Include library
-include_once '../lib/gocardless.php';
+include_once '../lib/GoCardless.php';
// Sandbox
GoCardless::$environment = 'sandbox';
@@ -18,6 +16,15 @@
'merchant_id' => null,
'access_token' => null
);
+
+// Fail nicely if no account details set
+if ( ! $account_details['app_id'] && ! $account_details['app_secret']) {
+ echo '<p>First sign up to <a href="http://gocardless.com">GoCardless</a> and
+copy your sandbox API credentials from the \'Developer\' tab into the top of
+this script.</p>';
+ exit();
+}
+
// Initialize GoCardless
GoCardless::set_account_details($account_details);
@@ -38,7 +45,9 @@
$confirmed_resource = GoCardless::confirm_resource($confirm_params);
- echo '<p>Payment confirmed!</p>';
+ echo '<p>Payment confirmed:<br /><pre>';
+ print_r($confirmed_resource);
+ echo '</pre></p>';
}
@@ -58,7 +67,7 @@
// New pre-authorization
$payment_details = array(
- 'max_amount' => '20.00',
+ 'max_amount' => '100.00',
'interval_length' => 1,
'interval_unit' => 'month'
);
@@ -85,33 +94,44 @@
echo '<h2>API calls</h2>';
-echo 'GoCardless_Merchant::find(\'258584\')';
+echo 'GoCardless_Merchant::find(\''.$account_details['merchant_id'].'\')';
echo '<blockquote><pre>';
-$merchant = GoCardless_Merchant::find('258584');
+$merchant = GoCardless_Merchant::find($account_details['merchant_id']);
print_r($merchant);
echo '</pre></blockquote>';
-echo 'GoCardless_Merchant::find(\'258584\')->pre_authorizations()';
+echo 'GoCardless_Merchant::find(\''.$account_details['merchant_id'].'\')->pre_authorizations()';
echo '<blockquote><pre>';
-$preauths = GoCardless_Merchant::find('258584')->pre_authorizations();
+$preauths = GoCardless_Merchant::find($account_details['merchant_id'])->pre_authorizations();
print_r($preauths);
echo '</pre></blockquote>';
-echo 'GoCardless_PreAuthorization::find(\'992869\')->create_bill($bill_details)';
+// Create a pre-auth using the url generated above then fetch it's ID
+// using the query above. Now you can create bills within that pre-auth
+// like this:
+
+//echo 'GoCardless_PreAuthorization::find(\'992869\')->create_bill($bill_details)';
+//echo '<blockquote><pre>';
+//$pre_auth = GoCardless_PreAuthorization::find('013M018V0K');
+//$bill_details = array(
+// 'amount' => '5.00'
+//);
+//$bill = $pre_auth->create_bill($bill_details);
+//print_r($bill);
+//echo '</pre></blockquote>';
+
+echo 'GoCardless_Merchant::find(\''.$account_details['merchant_id'].'\')->subscriptions()';
echo '<blockquote><pre>';
-$pre_auth = GoCardless_PreAuthorization::find('013M018V0K');
-$bill_details = array(
- 'amount' => '15.00'
-);
-$bill = $pre_auth->create_bill($bill_details);
-print_r($bill);
+$preauths = GoCardless_Merchant::find($account_details['merchant_id'])->subscriptions();
+print_r($preauths);
echo '</pre></blockquote>';
-echo 'validate webhook:';
-echo '<blockquote><pre>';
-$webhook_json = '{"payload":{"bills":[{"id":"880807"},{"status":"pending"},{"source_type":"subscription"},{"source_id":"21"},{"uri":"https:\/\/sandbox.gocardless.com\/api\/v1\/bills\/880807"}],"action":"created","resource_type":"bill","signature":"f25a611fb9afbc272ab369ead52109edd8a88cbb29a3a00903ffbce0ec6be5cb"}}';
-$webhook = json_decode($webhook_json, true);
-var_dump(GoCardless::validate_webhook($webhook['payload']));
-echo '</pre></blockquote>';
+// Create a subscription using the url generated above then fetch it's ID
+// using the query above. Now you can cancel subscriptions using the
+// following:
-?>
+//echo 'GoCardless_Subscription::find('01BXN6FKSP')->cancel()';
+//echo '<blockquote><pre>';
+//$sub = GoCardless_Subscription::find('01BXN6FKSP')->cancel();
+//print_r($sub);
+//echo '</pre></blockquote>';
View
154 examples/partner.php
@@ -0,0 +1,154 @@
+<?php
+
+/**
+ * Sign up for an account at GoCardless.com
+ * Email help@gocardless.com to upgrade to a partner account
+ * Copy your app id and secret from the developer tab and paste them in below
+ *
+ * Load the page and use the 'authorize app' link to generate an access_token
+ *
+ * Now you can initialize a Client object using that access_token
+ * You'll probably want to save the access_token in your database too
+ *
+ *
+ * This page does the following:
+ *
+ * 1. Generates an authorize link
+ * 2. Generates an access_token (using $_GET['code'])
+ * 3. Instantiates a Client object
+ * 4. Fetches the current merchant's details
+ * 5. Fetches the current merchant's pre-authorizations
+ * 6. Creates a bill under a pre-authorizations
+ * 7. Repeats steps 4 and 5 with a different Client object
+ *
+ */
+
+// Include library
+include_once '../lib/GoCardless.php';
+
+// Sandbox
+GoCardless::$environment = 'sandbox';
+
+// Config vars for your PARTNER account
+$account_details = array(
+ 'app_id' => null,
+ 'app_secret' => null,
+// 'merchant_id' => null,
+// 'access_token' => null
+);
+
+// Fail nicely if no account details set
+if ( ! $account_details['app_id'] && ! $account_details['app_secret']) {
+ echo '<p>First sign up to <a href="http://gocardless.com">GoCardless</a> and
+copy your sandbox API credentials from the \'Developer\' tab into the top of
+this script.</p>';
+ exit();
+}
+
+// Initalize new Client object
+$gocardless_client = new GoCardless_Client($account_details);
+
+if (isset($_GET['code'])) {
+ // Code being passed as a get var
+
+ $params = array(
+ 'client_id' => $account_details['app_id'],
+ 'code' => $_GET['code'],
+ 'redirect_uri' => 'http://localhost/examples/demo_partner.php',
+ 'grant_type' => 'authorization_code'
+ );
+
+ // Fetching token returns merchant_id and access_token
+ $token = $gocardless_client->fetch_access_token($params);
+
+ $account_details = array(
+ 'app_id' => $account_details['app_id'],
+ 'app_secret' => $account_details['app_secret'],
+ 'access_token' => $token['access_token'],
+ 'merchant_id' => $token['merchant_id']
+ );
+
+ // Create new Client object
+ $gocardless_client = new GoCardless_Client($account_details);
+
+ // Yay!
+ echo '<p>Authorization successful!
+ <br />Copy and paste this access token into the top of the code for this
+ page to continue testing the partner demo. In your own app, you\'ll want to
+ save it to your database.
+ <br />Access token: '.$account_details['access_token'].'
+ <br />Merchant id: '.$account_details['merchant_id'].'</p>';
+
+}
+
+if (isset($account_details['access_token'])) {
+ // We have an access token, run some API queries using our shiny new token
+
+ echo '<h2>Partner authorization</h2>';
+
+ echo '<p>Access token found!</p>';
+
+ echo '$gocardless_client->merchant()';
+ echo '<blockquote><pre>';
+ $merchant = $gocardless_client->merchant();
+ print_r($merchant);
+ echo '</pre></blockquote>';
+
+ echo 'echo $gocardless_client->merchant()->pre_authorizations()';
+ echo '<blockquote><pre>';
+ $preauths = $gocardless_client->merchant()->pre_authorizations();
+ print_r($preauths);
+ echo '</pre></blockquote>';
+
+ //echo '$gocardless_client->create_bill($pre_auth_details)';
+ //echo '<blockquote><pre>';
+ //$pre_auth_details = array(
+ // 'pre_authorization_id' => '014PS77JW3',
+ // 'amount' => '5.00'
+ //);
+ //$bill = $gocardless_client->create_bill($pre_auth_details);
+ //print_r($bill);
+ //echo '</pre></blockquote>';
+
+ // Instantiate a second client object, just as an experiment
+ $account_details = array(
+ 'app_id' => $account_details['app_id'],
+ 'app_secret' => $account_details['app_secret'],
+ 'merchant_id' => null,
+ 'access_token' => null
+ );
+
+ // Fail nicely if no second set of account details
+ if (!isset($account_details['merchant_id'])
+ || !isset($account_details['access_token'])) {
+ echo '<p>To fully test partner mode, authorize a second merchant account
+ and paste the merchant_id access_token into the $account_details for
+ $gocardless_client2.</p>';
+ exit();
+ }
+
+ $gocardless_client2 = new GoCardless_Client($account_details);
+
+ echo 'echo $gocardless_client2->merchant()';
+ echo '<blockquote><pre>';
+ $merchant = $gocardless_client2->merchant();
+ print_r($merchant);
+ echo '</pre></blockquote>';
+
+ echo '$gocardless_client2->merchant()->pre_authorizations()';
+ echo '<blockquote><pre>';
+ $preauths = $gocardless_client2->merchant()->pre_authorizations();
+ print_r($preauths);
+ echo '</pre></blockquote>';
+
+} else {
+ // No access token so show new authorization link
+
+ echo '<h2>Partner authorization</h2>';
+ $authorize_url_options = array(
+ 'redirect_uri' => 'http://localhost/examples/demo_partner.php'
+ );
+ $authorize_url = $gocardless_client->authorize_url($authorize_url_options);
+ echo '<p><a href="'.$authorize_url.'">Authorize app</a></p>';
+
+}
View
65 examples/webhooks.php
@@ -0,0 +1,65 @@
+<?php
+
+// Include library
+include_once '../lib/GoCardless.php';
+
+// Sandbox
+GoCardless::$environment = 'sandbox';
+
+// Config vars
+$account_details = array(
+ 'app_id' => null,
+ 'app_secret' => null,
+ 'merchant_id' => null,
+ 'access_token' => null
+);
+
+// Initialize GoCardless
+GoCardless::set_account_details($account_details);
+
+// Use this line to fetch the body of the HTTP request
+$webhook = file_get_contents('php://input');
+
+// Or use this json blog for testing
+//$webhook = '{
+// "payload": {
+// "resource_type": "bill",
+// "action": "paid",
+// "bills": [
+// {
+// "id": "AKJ398H8KA",
+// "status": "paid",
+// "source_type": "subscription",
+// "source_id": "KKJ398H8K8",
+// "paid_at": "2011-12-01T12:00:00Z",
+// "uri": "https://sandbox.gocardless.com/api/v1/bills/AKJ398H8KA"
+// },
+// {
+// "id": "AKJ398H8KB",
+// "status": "paid",
+// "source_type": "subscription",
+// "source_id": "8AKJ398H78",
+// "paid_at": "2011-12-09T12:00:00Z",
+// "uri": "https://sandbox.gocardless.com/api/v1/bills/AKJ398H8KB"
+// }
+// ],
+// "signature": "f6b9e6cd8eef30c444da48370e646839c9bb9e1cf10ea16164d5cf93a50231eb"
+// }
+//}';
+
+// Convert json blog to array
+$webhook_array = json_decode($webhook, true);
+
+// Validate webhook
+if (GoCardless::validate_webhook($webhook_array['payload'])) {
+
+ // Write webhook to a file for inspection
+ // You'll probably need to create this file and make it writable
+ $log = fopen("webhooks.txt", "a");
+ fwrite($log, print_r($webhook_array, TRUE) . "\n\n");
+ fclose($log);
+
+ // Send a success header
+ header('HTTP/1.1 200 OK');
+
+}
View
72 lib/gocardless.php → lib/GoCardless.php
@@ -6,22 +6,17 @@
* @package GoCardless
*/
-if (!function_exists('curl_init')) {
+if ( ! function_exists('curl_init')) {
throw new Exception('GoCardless needs the CURL PHP extension.');
}
-if (!function_exists('json_decode')) {
+if ( ! function_exists('json_decode')) {
throw new Exception('GoCardless needs the JSON PHP extension.');
}
-// Include subclasses
-require 'gocardless/utils.php';
-require 'gocardless/exceptions.php';
-require 'gocardless/bill.php';
-require 'gocardless/user.php';
-require 'gocardless/client.php';
-require 'gocardless/merchant.php';
-require 'gocardless/subscription.php';
-require 'gocardless/pre_authorization.php';
+// Autoload sub-classes
+spl_autoload_register(array('GoCardless', 'autoload'));
+
+require 'GoCardless/Exceptions.php';
/**
* GoCardless class
@@ -29,12 +24,17 @@
*/
class GoCardless {
- const VERSION = '0.1.1';
+ /**
+ * The environment: sandbox or live
+ *
+ * @var constant VERSION
+ */
+ const VERSION = '0.2.0';
/**
* The environment: sandbox or live
*
- * @var array $environment
+ * @var string $environment
*/
public static $environment;
@@ -46,9 +46,51 @@ class GoCardless {
public static $client;
/**
+ * Class References
+ * Help map references to static classes for use in mocking
+ *
+ * @var array $classes
+ */
+ protected static $classes = array(
+ 'Request' => 'GoCardless_Request',
+ );
+
+ /**
+ * Set the class to use
+ *
+ * @param string $name The nickname of the class to load
+ * @param object $class The class to load
+ */
+ public static function setClass($name, $class) {
+ self::$classes[$name] = $class;
+ }
+
+ /**
+ * Get the class to use
+ *
+ * @param string $name The nickname of the class to get
+ *
+ * @return The loaded class
+ */
+ public static function getClass($name) {
+ return self::$classes[$name];
+ }
+
+ /**
+ * Autoload sub-classes
+ *
+ * @param string $class Name of the class to load
+ */
+ public static function autoload($class) {
+ if (strpos($class, 'GoCardless') === 0) {
+ require str_replace('_', '/', $class).'.php';
+ }
+ }
+
+ /**
* Initialization function called with account details
*
- * @param $account_details array Array of account details
+ * @param array $account_details Array of account details
*/
public static function set_account_details($account_details) {
GoCardless::$client = new GoCardless_Client($account_details);
@@ -110,5 +152,3 @@ public static function validate_webhook($params) {
}
}
-
-?>
View
24 lib/gocardless/bill.php → lib/GoCardless/Bill.php
@@ -27,13 +27,15 @@ class GoCardless_Bill {
*
* @return object The bill object
*/
- function __construct($client, $attrs) {
+ function __construct($client, array $attrs = null) {
$this->client = $client;
- foreach ($attrs as $key => $value) {
- $this->$key = $value;
- }
+ if (is_array($attrs)) {
+ foreach ($attrs as $key => $value) {
+ $this->$key = $value;
+ }
+ }
}
@@ -49,7 +51,9 @@ public static function find($id, $client = null) {
$endpoint = self::$endpoint . '/' . $id;
- return new self(GoCardless::$client, GoCardless::$client->api_get($endpoint));
+ $client or $client = parent::$client;
+
+ return new self($client, $client->request('get', $endpoint));
}
@@ -65,7 +69,7 @@ public function find_with_client($client, $id) {
$endpoint = self::$endpoint . '/' . $id;
- return new self($client, GoCardless::$client->api_get($endpoint));
+ return new self($client, $client->request('get', $endpoint));
}
@@ -78,12 +82,12 @@ public function find_with_client($client, $id) {
*/
public function create($params) {
- $params['headers']['authorization'] = true;
+ $endpoint = self::$endpoint;
+
+ $params['http_authorization'] = true;
- return new self($this->$client, $this->client->api_post(self::$endpoint, $params));
+ return new self($this->client, $this->client->request('post', $endpoint, $params));
}
}
-
-?>
View
369 lib/gocardless/client.php → lib/GoCardless/Client.php
@@ -20,11 +20,11 @@ class GoCardless_Client {
public $account_details;
/**
- * The (empty) base_url to use for API queries
+ * The base_url for the API to use for all client requests
*
* @var string $base_url
*/
- public static $base_url;
+ public $base_url;
/**
* Array of possible base_urls to use
@@ -63,23 +63,28 @@ public function __construct($account_details) {
}
// Check for app_id
- if (!isset($this->account_details['app_id'])) {
+ if ( ! isset($this->account_details['app_id'])) {
throw new GoCardless_ClientException('No app_id specified');
}
// Check for app_secret
- if (!isset($this->account_details['app_secret'])) {
+ if ( ! isset($this->account_details['app_secret'])) {
throw new GoCardless_ClientException('No app_secret specfied');
}
// If environment is not set then default to production
- if (!isset(GoCardless::$environment)) {
+ if ( ! isset(GoCardless::$environment)) {
GoCardless::$environment = 'production';
}
- // If base_url is not set then set it based on environment
- if (!isset(GoCardless_Client::$base_url)) {
- GoCardless_Client::$base_url = GoCardless_Client::$base_urls[GoCardless::$environment];
+ // Take base_url from array
+ if (isset($account_details['base_url'])) {
+ $this->base_url = $account_details['base_url'];
+ unset($account_details['base_url']);
+
+ } else {
+ // Otherwise set it based on environment
+ $this->base_url = self::$base_urls[GoCardless::$environment];
}
}
@@ -91,122 +96,105 @@ public function __construct($account_details) {
*
* @return string The generated url
*/
- public function authorize_url($options) {
+ public function authorize_url($options = null) {
- if (!isset($options['redirect_uri'])) {
+ if ( ! isset($options['redirect_uri'])) {
throw new GoCardless_ArgumentsException('redirect_uri required');
}
$endpoint = '/oauth/authorize';
- $url = GoCardless_Client::$base_url . $endpoint .
+ return $this->base_url . $endpoint .
'?client_id='. urlencode($this->account_details['app_id']) .
'&redirect_uri=' . urlencode($options['redirect_uri']) .
'&scope=manage_merchant' .
'&response_type=code';
- return $url;
-
}
/**
- * Fetch an access token for the current user
+ * Returns the merchant associated with the client's access token
*
- * @param array $options The parameters to use
+ * @param string $id The id of the merchant to fetch
*
- * @return string The access token
+ * @return object The merchant object
*/
- public function fetch_access_token($options){
+ public function merchant($id = null) {
- if (!isset($options['redirect_uri'])) {
- throw new GoCardless_ArgumentsException('redirect_uri required');
+ if ($id == null) {
+ $id = $this->account_details['merchant_id'];
}
- $path = '/oauth/access_token';
-
- $options['http_authorization'] = $this->account_details['app_id'] . ':' . $this->account_details['app_secret'];
-
- $response = $this->request('post', $path, $options);
-
- $merchant = explode(':', $response['scope']);
- $merchant_id = $merchant[1];
- $access_token = $response['access_token'];
-
- $return = array(
- 'merchant_id' => $merchant_id,
- 'access_token' => $access_token
- );
-
- return $return;
+ return GoCardless_Merchant::find_with_client($this, $id);
}
/**
- * Configure a GET request
+ * Make a request to the API
*
- * @param string $path The URL to make the request to
- * @param array $params The parameters to use for the POST body
+ * @param string $method The request method to use
+ * @param string $endpoint The API endpoint to call
+ * @param string $params The parameters to send with the request
*
- * @return string The response text
+ * @return object The returned object
*/
- public function api_get($path, $params = array()) {
+ public function request($method, $endpoint, $params = array()) {
- $path = GoCardless_Client::$api_path . $path;
+ // If there is no http_authorization, try checking for access_token
+ if ( ! isset($params['http_authorization'])) {
- return $this->request('get', $path, $params);
+ // No http_authorization and no access_token? Fail
+ if ( ! isset($this->account_details['access_token'])) {
+ throw new GoCardless_ClientException('Access token missing');
+ }
- }
+ // access_token found so set Authorization header to contain bearer
+ $params['http_bearer'] = $this->account_details['access_token'];
- /**
- * Configure a POST request
- *
- * @param string $path The URL to make the request to
- * @param array $data The parameters to use for the POST body
- *
- * @return string The response text
- */
- public function api_post($path, $data = array()) {
+ }
- $path = GoCardless_Client::$api_path . $path;
+ if (substr($endpoint, 0, 6) == '/oauth') {
- return $this->request('post', $path, $data);
+ // OAuth API calls don't require /api/v1 base
+ $url = $this->base_url . $endpoint;
- }
+ } else {
- /**
- * Configure a PUT request
- *
- * @param string $path The URL to make the request to
- * @param array $data The parameters to use for the PUT body
- *
- * @return string The response text
- */
- public function api_put($path, $data = array()) {
+ // http://sandbox.gocardless.com | /api/v1 | /test
+ $url = $this->base_url . self::$api_path . $endpoint;
- $path = GoCardless_Client::$api_path . $path;
+ }
- return $this->request('put', $path, $data);
+ // Call the Request library (might be aliases for testing) with URL and params
+ return call_user_func(GoCardless::getClass('Request').'::'.$method, $url, $params);
}
/**
- * Returns the merchant associated with the client's access token
+ * Fetch an access token for the current user
*
- * @param string $id The id of the merchant to fetch
+ * @param array $params The parameters to use
*
- * @return object The merchant object
+ * @return string The access token
*/
- public function merchant($id = null) {
+ public function fetch_access_token($params) {
- if ($id == null) {
- $id = $this->account_details['merchant_id'];
+ if ( ! isset($params['redirect_uri'])) {
+ throw new GoCardless_ArgumentsException('redirect_uri required');
}
- if (!isset($this->account_details['access_token'])) {
- throw new GoCardless_ClientException('Access token missing');
- }
+ $params['http_authorization'] = $this->account_details['app_id'] . ':' . $this->account_details['app_secret'];
- return GoCardless_Merchant::find_with_client($this, $id);
+ $response = $this->request('post', '/oauth/access_token', $params);
+
+ $merchant = explode(':', $response['scope']);
+ $merchant_id = isset($merchant[1]) ? $merchant[1] : null;
+ $access_token = $response['access_token'];
+
+ return array(
+ 'merchant_id' => $merchant_id,
+ 'access_token' => $access_token
+ );
}
@@ -218,13 +206,7 @@ public function merchant($id = null) {
* @return object The subscription matching the id requested
*/
public function subscription($id) {
-
- if (!isset($this->account_details['access_token'])) {
- throw new GoCardless_ClientException('Access token missing');
- }
-
return GoCardless_Subscription::find_with_client($this, $id);
-
}
/**
@@ -235,13 +217,7 @@ public function subscription($id) {
* @return object The pre-authorization matching the id requested
*/
public function pre_authorization($id) {
-
- if (!isset($this->account_details['access_token'])) {
- throw new GoCardless_ClientException('Access token missing');
- }
-
return GoCardless_PreAuthorization::find_with_client($this, $id);
-
}
/**
@@ -252,13 +228,7 @@ public function pre_authorization($id) {
* @return object The user object matching the id requested
*/
public function user($id) {
-
- if (!isset($this->account_details['access_token'])) {
- throw new GoCardless_ClientException('Access token missing');
- }
-
return GoCardless_User::find_with_client($this, $id);
-
}
/**
@@ -269,13 +239,7 @@ public function user($id) {
* @return object The bill object matching the id requested
*/
public function bill($id) {
-
- if (!isset($this->account_details['access_token'])) {
- throw new GoCardless_ClientException('Access token missing');
- }
-
return GoCardless_Bill::find_with_client($this, $id);
-
}
/**
@@ -287,11 +251,7 @@ public function bill($id) {
*/
public function create_bill($attrs) {
- if (!isset($this->account_details['access_token'])) {
- throw new GoCardless_ClientException('Access token missing');
- }
-
- if (!isset($attrs['pre_authorization_id'])) {
+ if ( ! isset($attrs['pre_authorization_id'])) {
throw new GoCardless_ArgumentsException('pre_authorization_id missing');
}
@@ -358,7 +318,7 @@ public function confirm_resource($params) {
// Loop through required params
// Add to $data or throw exception if missing
foreach ($required_params as $key => $value) {
- if (!isset($params[$value])) {
+ if ( ! isset($params[$value])) {
throw new GoCardless_ArgumentsException("$value missing");
}
$data[$value] = $params[$value];
@@ -394,18 +354,18 @@ public function confirm_resource($params) {
$confirm_params['http_authorization'] = $this->account_details['app_id'] . ':' . $this->account_details['app_secret'];
// If no method-specific redirect sent, use class level if available
- if (!isset($params['redirect_uri']) && isset($this)) {
+ if ( ! isset($params['redirect_uri']) && isset($this->redirect_uri)) {
$confirm_params['redirect_uri'] = $this->redirect_uri;
}
// Do query
- $response = $this->api_post($endpoint, $confirm_params);
+ $response = $this->request('post', $endpoint, $confirm_params);
if ($response['success'] == true) {
$endpoint = '/' . $params['resource_type'] . 's/' . $params['resource_id'];
- return $this->api_get($endpoint);
+ return $this->request('get', $endpoint, $params);
} else {
@@ -427,7 +387,7 @@ public function validate_webhook($params) {
$sig = $params['signature'];
unset($params['signature']);
- if (!isset($sig)) {
+ if ( ! isset($sig)) {
return false;
}
@@ -441,127 +401,6 @@ public function validate_webhook($params) {
}
- /**
- * Makes an HTTP request
- *
- * @param string $method The method to use for the request
- * @param string $path The API path to make the request to
- * @param array $opts The parameters to use for the request
- *
- * @return string The response text
- */
- protected function request($method, $path, $opts = array()) {
-
- $path = GoCardless_Client::$base_url . $path;
-
- $ch = curl_init($path);
-
- $curl_options = array(
- CURLOPT_CONNECTTIMEOUT => 10,
- CURLOPT_RETURNTRANSFER => true,
- CURLOPT_TIMEOUT => 60
- );
-
- // Request format
- $curl_options[CURLOPT_HTTPHEADER][] = 'Accept: application/json';
-
- $authorization = $this->account_details['access_token'];
-
- // HTTP Authentication (for confirming new payments)
- if (isset($opts['http_authorization'])) {
-
- $curl_options[CURLOPT_USERPWD] = $opts['http_authorization'];
- unset($opts['http_authorization']);
-
- } else {
-
- if (!isset($this->account_details['access_token'])) {
- throw new GoCardless_ClientException('Access token missing');
- }
-
- $curl_options[CURLOPT_HTTPHEADER][] = 'Authorization: Bearer ' . $this->account_details['access_token'];
-
- }
-
- if ($method == 'post') {
-
- $curl_options[CURLOPT_POST] = 1;
-
- if (isset($opts)) {
- $curl_options[CURLOPT_POSTFIELDS] = http_build_query($opts, null, '&');
- }
-
- } elseif ($method == 'get') {
-
- $curl_options[CURLOPT_HTTPGET] = 1;
-
- } elseif ($method == 'put') {
-
- $curl_options[CURLOPT_PUT] = 1;
-
- }
-
- // Debug
- //if ($method == 'post') {
- // // POST request, so show url and vars
- // $vars = htmlspecialchars(print_r($curl_options[CURLOPT_POSTFIELDS], true));
- // echo "<pre>\n\nRequest\n\nPOST: $path\n";
- // echo "Post vars sent:\n";
- // echo "$vars\n";
- // echo "Full curl vars:\n";
- // print_r($curl_options);
- // echo '</pre>';
- //} elseif ($method == 'get') {
- // // GET request, so show just show url
- // echo "<pre>\n\nRequest\nGET: $path\n";
- // echo "Full curl vars: ";
- // print_r($curl_options);
- // echo '</pre>';
- //} else {
- // echo "Method not set!";
- //}
-
- curl_setopt_array($ch, $curl_options);
-
- $result = curl_exec($ch);
-
- // Debug
- //echo "<pre>\nCurl result: ";
- //print_r(curl_getinfo($ch));
- //echo "</pre>";
-
- // Grab the response code and throw an exception if it's not good
- $http_response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- if ($http_response_code < 200 || $http_response_code > 300) {
-
- $response = json_decode($result, true);
-
- // Urgh
- $message = '';
- if (is_array($response)) {
- foreach ($response as $key => $value) {
- if (is_array($value)) {
- foreach ($value as $key2 => $value2) {
- $message .= $key2 . ' : ' . $value2 . '. ';
- }
- } else {
- $message .= $key . ' : ' . $value . '. ';
- }
- }
- }
-
- throw new GoCardless_ApiException($message, $http_response_code);
-
- }
-
- curl_close($ch);
-
- $object = json_decode($result, true);
-
- return $object;
-
- }
-
// Sign params
/**
@@ -573,13 +412,9 @@ protected function request($method, $path, $opts = array()) {
*/
public function validate_signature($params) {
- $new_sig = Utils::generate_signature($params['data'], $params['secret']);
+ $new_sig = GoCardless_Utils::generate_signature($params['data'], $params['secret']);
- if ($new_sig == $params['signature']) {
- return true;
- } else {
- return false;
- }
+ return ($new_sig === $params['signature']);
}
@@ -606,38 +441,60 @@ public function generate_nonce() {
* Generate a new payment url
*
* @param string $type Payment type
- * @param string $limit_params The specific parameters for this payment
+ * @param string $params The specific parameters for this payment
*
* @return string The new payment URL
*/
- private function new_limit_url($type, $limit_params) {
+ private function new_limit_url($type, $params) {
+
+ // Declare empty array
+ $request = array();
+
+ // Add in merchant id
+ $params['merchant_id'] = $this->account_details['merchant_id'];
+
+ // Define optional parameters
+ $opt_params = array(
+ 'redirect_uri',
+ 'cancel_uri',
+ 'state'
+ );
+
+ // Loop through optional parameters
+ foreach ($opt_params as $opt_param) {
+ if (isset($params[$opt_param])) {
+ $request[$opt_param] = $params[$opt_param];
+ unset($params[$opt_param]);
+ }
+ }
// If no method-specific redirect submitted then
// use class level if available
- if (!isset($limit_params['redirect_uri']) && isset($this)) {
- $limit_params['redirect_uri'] = $this->redirect_uri;
+ if ( ! isset($request['redirect_uri']) && isset($this->redirect_uri)) {
+ $request['redirect_uri'] = $this->redirect_uri;
}
- // Add in merchant id
- $limit_params['merchant_id'] = $this->account_details['merchant_id'];
+ // Grab the state, if there is one, and remove it from
+ // the params so it doesn't get attached to the "type" object
+ if (isset($limit_params['state'])) {
+ $state = $limit_params['state'];
+ unset($limit_params['state']);
+ }
- // Add passed params to an array named by type
- $limit_params = array($type => $limit_params);
+ // Create array of payment params
+ $payment_params = array($type => $params);
- // Merge passed and mandatory params
- $request = array_merge($limit_params, $this->generate_mandatory_params());
+ // Put together all the bits: passed params inc payment params & mandatory
+ $request = array_merge($request, $payment_params, $this->generate_mandatory_params());
// Generate signature
- $request['signature'] = Utils::generate_signature($request, $this->account_details['app_secret']);
+ $request['signature'] = GoCardless_Utils::generate_signature($request, $this->account_details['app_secret']);
// Generate query string from all parameters
- $query_string = Utils::generate_query_string($request);
+ $query_string = GoCardless_Utils::generate_query_string($request);
// Generate url NB. Pluralises resource
- $url = GoCardless_Client::$base_url . '/connect/' . $type . 's/new?' . $query_string;
-
- // Return the result
- return $url;
+ return $this->base_url . '/connect/' . $type . 's/new?' . $query_string;
}
@@ -651,16 +508,12 @@ public function generate_mandatory_params() {
// Create new UTC date object
$date = new DateTime(null, new DateTimeZone('UTC'));
- $request = array(
+ return array(
'client_id' => $this->account_details['app_id'],
'nonce' => GoCardless_Client::generate_nonce(),
'timestamp' => $date->format('Y-m-d\TH:i:s\Z')
);
- return $request;
-
}
}
-
-?>
View
2  lib/gocardless/exceptions.php → lib/GoCardless/Exceptions.php
@@ -81,5 +81,3 @@ public function __construct($description = 'Signature error') {
}
}
-
-?>
View
27 lib/gocardless/merchant.php → lib/GoCardless/Merchant.php
@@ -27,12 +27,14 @@ class GoCardless_Merchant {
*
* @return object The merchant object
*/
- function __construct($client, $attrs) {
+ function __construct($client, array $attrs = null) {
$this->client = $client;
- foreach ($attrs as $key => $value) {
- $this->$key = $value;
+ if (is_array($attrs)) {
+ foreach ($attrs as $key => $value) {
+ $this->$key = $value;
+ }
}
}
@@ -46,9 +48,9 @@ function __construct($client, $attrs) {
*/
public static function find($id) {
- $endpoint = self::$endpoint . '/' . $id;
+ $client = GoCardless::$client;
- return new self(GoCardless::$client, GoCardless::$client->api_get($endpoint));
+ return new self($client, $client->request('get', self::$endpoint . '/' . $id));
}
@@ -62,9 +64,7 @@ public static function find($id) {
*/
public static function find_with_client($client, $id) {
- $endpoint = self::$endpoint . '/' . $id;
-
- return new self($client, $client->api_get($endpoint));
+ return new self($client, $client->request('get', self::$endpoint . '/' . $id));
}
@@ -79,12 +79,11 @@ public function subscriptions() {
$endpoint = self::$endpoint . '/' . $this->id . '/subscriptions';
- foreach ($this->client->api_get($endpoint) as $value) {
+ foreach ($this->client->request('get', $endpoint) as $value) {
$objects[] = new GoCardless_Subscription($this->client, $value);
}
return $objects;
-
}
/**
@@ -98,7 +97,7 @@ public function pre_authorizations() {
$objects = array();
- foreach ($this->client->api_get($endpoint) as $value) {
+ foreach ($this->client->request('get', $endpoint) as $value) {
$objects[] = new GoCardless_PreAuthorization($this->client, $value);
}
@@ -117,7 +116,7 @@ public function users() {
$objects = array();
- foreach (GoCardless::$client->api_get($endpoint) as $value) {
+ foreach ($this->client->request('get', $endpoint, $params) as $value) {
$objects[] = new GoCardless_User($this->client, $value);
}
@@ -136,7 +135,7 @@ public function bills() {
$objects = array();
- foreach ($this->client->api_get($endpoint) as $value) {
+ foreach ($this->client->request('get', $endpoint, $params) as $value) {
$objects[] = new GoCardless_Bill($this->client, $value);
}
@@ -145,5 +144,3 @@ public function bills() {
}
}
-
-?>
View
22 lib/gocardless/pre_authorization.php → lib/GoCardless/PreAuthorization.php
@@ -27,13 +27,15 @@ class GoCardless_PreAuthorization {
*
* @return object The pre-auth object
*/
- function __construct($client, $attrs) {
+ function __construct($client, array $attrs = null) {
$this->client = $client;
- foreach ($attrs as $key => $value) {
- $this->$key = $value;
- }
+ if (is_array($attrs)) {
+ foreach ($attrs as $key => $value) {
+ $this->$key = $value;
+ }
+ }
}
@@ -48,7 +50,7 @@ public static function find($id) {
$endpoint = self::$endpoint . '/' . $id;
- return new self(GoCardless::$client, GoCardless::$client->api_get($endpoint));
+ return new self(GoCardless::$client, GoCardless::$client->request('get', $endpoint));
}
@@ -64,7 +66,7 @@ public static function find_with_client($client, $id) {
$endpoint = self::$endpoint . '/' . $id;
- return new self($client, $client->api_get($endpoint));
+ return new self($client, GoCardless::$client->request('get', $endpoint));
}
@@ -77,7 +79,7 @@ public static function find_with_client($client, $id) {
*/
public function create_bill($attrs) {
- if(!isset($attrs['amount'])) {
+ if ( ! isset($attrs['amount'])) {
throw new GoCardless_ArgumentsException('Amount required');
}
@@ -98,7 +100,7 @@ public function create_bill($attrs) {
$endpoint = GoCardless_Bill::$endpoint;
- return new GoCardless_Bill($this->client, $this->client->api_post($endpoint, $params));
+ return new GoCardless_Bill($this->client, $this->client->request('post', $endpoint));
}
@@ -111,10 +113,8 @@ public function cancel() {
$endpoint = self::$endpoint . '/' . $this->id . '/cancel';
- return new self($this->client, $this->client->api_put($endpoint));
+ return new self($this->client, $this->client->request('put', $endpoint));
}
}
-
-?>
View
175 lib/GoCardless/Request.php
@@ -0,0 +1,175 @@
+<?php
+
+/**
+ * GoCardless request functions
+ *
+ * @package GoCardless\Request
+ */
+
+/**
+ * GoCardless request class
+ *
+ */
+class GoCardless_Request {
+
+ /**
+ * Configure a GET request
+ *
+ * @param string $url The URL to make the request to
+ * @param array $params The parameters to use for the POST body
+ *
+ * @return string The response text
+ */
+ public static function get($url, $params = array()) {
+ return self::call('get', $url, $params);
+ }
+
+ /**
+ * Configure a POST request
+ *
+ * @param string $url The URL to make the request to
+ * @param array $params The parameters to use for the POST body
+ *
+ * @return string The response text
+ */
+ public static function post($url, $params = array()) {
+ return self::call('post', $url, $params);
+ }
+
+ /**
+ * Configure a PUT request
+ *
+ * @param string $url The URL to make the request to
+ * @param array $params The parameters to use for the PUT body
+ *
+ * @return string The response text
+ */
+ public static function put($url, $params = array()) {
+ return self::call('put', $url, $params);
+ }
+
+ /**
+ * Makes an HTTP request
+ *
+ * @param string $method The method to use for the request
+ * @param string $url The API url to make the request to
+ * @param array $params The parameters to use for the request
+ *
+ * @return string The response text
+ */
+ protected static function call($method, $url, $params = array()) {
+
+ $ch = curl_init($url);
+
+ $curl_options = array(
+ CURLOPT_CONNECTTIMEOUT => 10,
+ CURLOPT_RETURNTRANSFER => true,
+ CURLOPT_TIMEOUT => 60
+ );
+
+ // Request format
+ $curl_options[CURLOPT_HTTPHEADER][] = 'Accept: application/json';
+
+ // HTTP Authentication (for confirming new payments)
+ if (isset($params['http_authorization'])) {
+
+ $curl_options[CURLOPT_USERPWD] = $params['http_authorization'];
+ unset($params['http_authorization']);
+
+ } else {
+
+ if ( ! isset($params['http_bearer'])) {
+ throw new GoCardless_ClientException('Access token missing');
+ }
+
+ $curl_options[CURLOPT_HTTPHEADER][] = 'Authorization: Bearer ' . $params['http_bearer'];
+ unset($params['http_bearer']);
+
+ }
+
+ if ($method == 'post') {
+
+ $curl_options[CURLOPT_POST] = 1;
+
+ if (isset($params)) {
+ $curl_options[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
+ }
+
+ } elseif ($method == 'get') {
+
+ $curl_options[CURLOPT_HTTPGET] = 1;
+
+ } elseif ($method == 'put') {
+
+ $curl_options[CURLOPT_PUT] = 1;
+ $fh = fopen('php://memory', 'rw+');
+ $curl_options[CURLOPT_INFILE] = $fh;
+ $curl_options[CURLOPT_INFILESIZE] = 0;
+
+ }
+
+ // Debug
+ //if ($method == 'post') {
+ // // POST request, so show url and vars
+ // $vars = htmlspecialchars(print_r($curl_options[CURLOPT_POSTFIELDS], true));
+ // echo "<pre>\n\nRequest\n\nPOST: $url\n";
+ // echo "Post vars sent:\n";
+ // echo "$vars\n";
+ // echo "Full curl vars:\n";
+ // print_r($curl_options);
+ // echo '</pre>';
+ //} elseif ($method == 'get') {
+ // // GET request, so show just show url
+ // echo "<pre>\n\nRequest\nGET: $url\n";
+ // echo "Full curl vars: ";
+ // print_r($curl_options);
+ // echo '</pre>';
+ //} else {
+ // echo "Method not set!";
+ //}
+
+ curl_setopt_array($ch, $curl_options);
+
+ $result = curl_exec($ch);
+
+ // Debug
+ //echo "<pre>\nCurl result: ";
+ //print_r(curl_getinfo($ch));
+ //echo "</pre>";
+
+ // Grab the response code and throw an exception if it's not good
+ $http_response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+ if ($http_response_code < 200 || $http_response_code > 300) {
+
+ $response = json_decode($result, true);
+
+ // Convert json blob API error messages into a readable string
+ // One layer of recursion due to arbitrary keys
+ $message = '';
+ if (is_array($response)) {
+ foreach ($response as $key => $value) {
+ if (is_array($value)) {
+ foreach ($value as $key2 => $value2) {
+ $message .= $key2 . ' : ' . $value2 . '. ';
+ }
+ } else {
+ $message .= $key . ' : ' . $value . '. ';
+ }
+ }
+ }
+
+ throw new GoCardless_ApiException($message, $http_response_code);
+
+ }
+
+ curl_close($ch);
+
+ if (isset($fh)) {
+ fclose($fh);
+ }
+
+ return json_decode($result, true);
+
+ }
+
+}
View
18 lib/gocardless/subscription.php → lib/GoCardless/Subscription.php
@@ -27,13 +27,15 @@ class GoCardless_Subscription {
*
* @return object The subscription object
*/
- function __construct($client, $attrs) {
+ function __construct($client, array $attrs = null) {
$this->client = $client;
- foreach ($attrs as $key => $value) {
- $this->$key = $value;
- }
+ if (is_array($attrs)) {
+ foreach ($attrs as $key => $value) {
+ $this->$key = $value;
+ }
+ }
}
@@ -48,7 +50,7 @@ public static function find($id) {
$endpoint = self::$endpoint . '/' . $id;
- return new self(GoCardless::$client, GoCardless::$client->api_get($endpoint));
+ return new self(GoCardless::$client, GoCardless::$client->request('get', $endpoint));
}
@@ -64,7 +66,7 @@ public static function find_with_client($client, $id) {
$endpoint = self::$endpoint . '/' . $id;
- return new self($client, $client->api_get($endpoint));
+ return new self($client, $client->request('get', $endpoint));
}
@@ -77,10 +79,8 @@ public function cancel() {
$endpoint = self::$endpoint . '/' . $this->id . '/cancel';
- return new self($this->client, $this->client->api_put($endpoint));
+ return new self($this->client, $this->client->request('put', $endpoint));
}
}
-
-?>
View
16 lib/gocardless/user.php → lib/GoCardless/User.php
@@ -27,13 +27,15 @@ class GoCardless_User {
*
* @return object The user object
*/
- function __construct($client, $attrs) {
+ function __construct($client, array $attrs = null) {
$this->client = $client;
- foreach ($attrs as $key => $value) {
- $this->$key = $value;
- }
+ if (is_array($attrs)) {
+ foreach ($attrs as $key => $value) {
+ $this->$key = $value;
+ }
+ }
}
@@ -48,7 +50,7 @@ public static function find($id) {
$endpoint = self::$endpoint . '/' . $id;
- return new self(GoCardless::$client, GoCardless::$client->api_get($endpoint));
+ return new self(GoCardless::$client, GoCardless::$client->request('get', $endpoint));
}
@@ -64,10 +66,8 @@ public static function find_with_client($client, $id) {
$endpoint = self::$endpoint . '/' . $id;
- return new self($client, $client->api_get($endpoint));
+ return new self($client, $client->request('get', $endpoint));
}
}
-
-?>
View
10 lib/gocardless/utils.php → lib/GoCardless/Utils.php
@@ -10,7 +10,7 @@
* GoCardless utils class
*
*/
-class Utils {
+class GoCardless_Utils {
/**
* Generate a signature for a request given the app secret
@@ -22,7 +22,7 @@ class Utils {
*/
public static function generate_signature($params, $key) {
- return hash_hmac('sha256', Utils::generate_query_string($params), $key);
+ return hash_hmac('sha256', GoCardless_Utils::generate_query_string($params), $key);
}
@@ -42,9 +42,9 @@ public static function generate_query_string($params, &$pairs = array(), $namesp
foreach ($params as $k => $v) {
if (is_int($k)) {
- Utils::generate_query_string($v, $pairs, $namespace . '[]');
+ GoCardless_Utils::generate_query_string($v, $pairs, $namespace . '[]');
} else {
- Utils::generate_query_string($v, $pairs, $namespace !== null ? $namespace . "[$k]" : $k);
+ GoCardless_Utils::generate_query_string($v, $pairs, $namespace !== null ? $namespace . "[$k]" : $k);
}
}
@@ -71,5 +71,3 @@ public static function generate_query_string($params, &$pairs = array(), $namesp
}
}
-
-?>
View
9 phpunit.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<phpunit colors="true" stopOnFailure="false" bootstrap="tests/bootstrap.php">
+ <testsuites>
+ <testsuite name="lib">
+ <directory suffix=".php">./tests/lib</directory>
+ </testsuite>
+ </testsuites>
+</phpunit>
View
28 spec/GoCardlessSpec.php
@@ -0,0 +1,28 @@
+<?php
+
+class DescribeGoCardless extends \PHPSpec\Context {
+
+ private $_account_details;
+
+ public function before() {
+
+ $this->_account_details = array(
+ 'app_id' => 'X',
+ 'app_secret' => 'X',
+ 'merchant_id' => 1,
+ 'access_token' => 'X'
+ );
+
+ }
+
+ public function itShouldThrowAnExceptionWhenAppIdIsMissing() {
+
+ unset($this->_account_details['app_id']);
+
+ //$this->spec(
+ // GoCardless::set_account_details($this->_account_details)
+ //)->should->throwException();
+
+ }
+
+}
View
3  spec/SpecHelper.php
@@ -0,0 +1,3 @@
+<?php
+
+include 'lib/GoCardless.php';
View
38 spec/lib/ClientSpec.php
@@ -0,0 +1,38 @@
+<?php
+
+class DescribeClient extends \PHPSpec\Context {
+
+ private $_account_details;
+
+ public function before() {
+
+ $this->_account_details = array(
+ 'app_id' => 'X',
+ 'app_secret' => 'X',
+ 'merchant_id' => 1,
+ 'access_token' => 'X'
+ );
+
+ }
+
+ public function itShouldReturnCorrectProductionUrl() {
+
+ GoCardless::$environment = 'production';
+
+ $client = $this->spec(new GoCardless_Client($this->_account_details));
+
+ $client->base_url->should->equal('https://gocardless.com');
+
+ }
+
+ public function itShouldReturnCorrectSandboxUrl() {
+
+ GoCardless::$environment = 'sandbox';
+
+ $client = $this->spec(new GoCardless_Client($this->_account_details));
+
+ $client->base_url->should->equal('https://sandbox.gocardless.com');
+
+ }
+
+}
View
12 tests/bootstrap.php
@@ -0,0 +1,12 @@
+<?php
+
+// Load the PUPUnit Autoloader
+include_once('PHPUnit/Autoload.php');
+
+/**
+ * Set error reporting and display errors settings. You will want to change these when in production.
+ */
+error_reporting(E_ALL);
+ini_set('display_errors', true);
+
+include 'lib/GoCardless.php';
View
53 tests/gocardless.php
@@ -0,0 +1,53 @@
+<?php
+
+class Test_GoCardless extends PHPUnit_Framework_TestCase {
+
+ public function setUp() {
+
+
+
+ }
+
+
+ public function testAccountDetails()
+ {
+ // Initialize GoCardless
+ GoCardless::set_account_details(array(
+ 'app_id' => 'X',
+ 'app_secret' => 'X',
+ 'merchant_id' => 1,
+ 'access_token' => 'X',
+ ));
+
+ $class = get_class(GoCardless::$client);
+
+ $this->assertEquals('GoCardless_Client', $class);
+ }
+
+/*
+ it "gets upset if the token is missing" do
+ expect {
+ subject.account_details = @details.merge(:token => nil)
+ }.to raise_exception GoCardless::ClientError
+ end
+ end
+
+
+ describe "delegated methods" do
+ %w(new_subscription_url new_pre_authorization_url new_bill_url confirm_resource webhook_valid?).each do |name|
+ it "#{name} delegates to @client" do
+ subject.account_details = @details
+ subject.instance_variable_get(:@client).expects(name.to_sym)
+ subject.send(name)
+ end
+
+ it "raises an exception if the account details aren't set" do
+ expect {
+ subject.send(name)
+ }.to raise_exception GoCardless::ClientError
+ end
+ end
+ end
+*/
+
+}
View
41 tests/lib/bill.php
@@ -0,0 +1,41 @@
+<?php
+
+class Test_Bill extends PHPUnit_Framework_TestCase {
+
+ public function setUp() {
+
+ $this->config = array(
+ 'app_id' => 'abc',
+ 'app_secret' => 'xyz',
+ 'access_token' => 'foo',
+ );
+
+ // Assign as a method for the next test
+ GoCardless::set_account_details($this->config);
+
+ }
+
+ /**
+ * Find bill with source returns bill objects
+ */
+ public function testGetWithSource() {
+
+ //$bill = GoCardless_Bill::find('123');
+ //
+ //$this->assertEquals(get_class_name($bill), 'GoCardless_Bill')''
+
+ }
+
+ /**
+ * Find bill with source returns bill objects
+ */
+ public function testSetWithSource() {
+
+ //$bill = GoCardless_Bill::find('123');
+ //$subscription = new GoCardless_Subscription('123');
+ //