Skip to content

Instantly share code, notes, and snippets.

@chucktrukk
Forked from Andrew67/rpx.class.php
Created November 30, 2011 22:04
Show Gist options
  • Save chucktrukk/1411221 to your computer and use it in GitHub Desktop.
Save chucktrukk/1411221 to your computer and use it in GitHub Desktop.
<?php
/**
* RPX Helper Class for JanRain Engage
* @author Andres Cordero
* @license MIT
* See http://www.opensource.org/licenses/mit-license.html
* if LICENSE file not present
* Make sure cURL is installed and allowed to initiate HTTPS connections
*/
class Rpx {
/**
* Contains the current API Key.
*/
protected $apiKey;
/**
* RPX API Base URL
*/
const BASE_URL = 'https://rpxnow.com/api/v2/';
/**
* Construct a usable Rpx utility class.
* @param $apiKey The RPX api key.
*/
public function __construct($apiKey) {
$this->apiKey = $apiKey;
}
/**
* Overloaded __call allows calls to any API method to be caught by it.
* So you can do $rpx->auth_info($data) and it works.
* Because of overloading, even if new API methods are added, they'll work!
*/
public function __call($name, $arguments) {
return $this->apiCall($name, $arguments[0]);
}
/**
* Return the result of an RPX API Method Call.
* Should not be invoked directly.
* @param $method_name The name of the method to invoke.
* @param $parameters Parameters required by the method.
* @return An associative array containing the api response.
* @throws RpxException
*/
protected function apiCall($method_name, $parameters) {
if (!is_array($parameters) || empty($parameters)) {
throw new InvalidArgumentException('API arguments should be passed as an array');
}
// These are abstracted away so whatever the user specifies is irrelevant
$parameters['apiKey'] = $this->apiKey;
$parameters['format'] = 'json';
// Using snippet from http://gist.github.com/291396
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, self::BASE_URL . $method_name);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $parameters);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$raw_json = curl_exec($curl);
curl_close($curl);
$api_response = json_decode($raw_json, true);
if ($api_response['stat'] == 'fail') {
throw new RpxException($api_response['err']['msg'], $api_response['err']['code']);
}
else if ($api_response['stat'] == 'ok') {
return $api_response;
}
else {
throw new UnexpectedValueException('Unexpected response from server');
}
}
}
/**
* This exception is thrown when Rpx returns a 'fail' status code.
*/
class RpxException extends Exception { }
@chucktrukk
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment