Skip to content

Instantly share code, notes, and snippets.

@paulleduc paulleduc/index.php Secret
Last active Aug 29, 2015

Embed
What would you like to do?
<?php
/*
RingPartner Invoca RingPool PHP Integration Instructions:
STEP 1:
Copy and paste this code to the top of your web page, and ensure this page has the extension .php
(you also need to have PHP installed (with PHP cURL) to your web server, most likely it already is,
if it's not, contact your server administrator)
STEP 2:
Download the PHP file named ringpartner_unified_ringpools.php on the following
page and make sure it is in the same directory as this file:
https://gist.github.com/paulleduc/762ab973d4d02b6664c8
STEP 3:
Insert your API URL(s) in the place described below (below $ringpool = new RpRingpool(array()
STEP 4:
Paste the following code wherever you want your Ringpool tracking phone number to appear in your HTML:
<?php $ringpool->number(); ?>
STEP 5 (OPTIONAL):
If your API URL is bulk-ringpool enabled (PNAPI), uncomment the line specified below by removing the two leading slashes
*/
require_once('ringpartner_unified_ringpools.php');
$ringpool = new RpRingpool(array(
// place your API URL's here. You can add as many rows as you like, and remove as many as you like, but there must be at least one.
// each should be enclosed with single quotes, followed by a comma.
'https://ringpartner.ringrevenue.com/api/2014-11-01/ring_pools/44644/allocate_number.xml?ring_pool_key=3M7Rycqn63qlLHjFgqEnlmjuSBdrOY7h&Test=',
));
// If your API URL is using Invoca's bulk ringpool system (PNAPI), please remove '//' from the start of the next line,
// $ringpool->setPnapi();
// If you would like the page content to be a JSONP JavaScript callback function, uncomment the line below and don't add any HTML to this page.
// If you're not sure, skip this.
// $ringpool->jsonp(false);
?>
<?php
if(isset($_GET['ringpool_debug'])){
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
}
class RpRingpool {
private $isPnapi;
private $isDebug;
private $apiUrls;
private $number;
private $numberFormatted;
private static $pnapiUrl = 'https://pnapi.ringrevenue.com/api/2013-07-01/bulk.json';
// accepts any number of API URL's in standard or array format
public function __construct() {
if(isset($_GET['ringpool_debug'])){
$this->isDebug = true;
}
$urls = func_get_args();
if(count($urls) == 1 && is_array($urls[0])){
$urls = $urls[0];
}
$this->apiUrls = array();
if(!empty($urls)){
foreach($urls as $url) {
$this->apiUrls[] = new RpApiUrl($url);
}
}
}
public function getRandomApiUrl() {
$num = 0;
if(count($this->apiUrls) > 0){
$num = round(mt_rand(0, count($this->apiUrls) - 1));
}else{
return false;
}
return $this->apiUrls[$num];
}
public function getPnapiRequestBody($apiUrl) {
return array("requests" => array(array("api_suffix" => $apiUrl->getSuffix())));
}
public function setDebug($isDebug = true) {
$this->isDebug = $isDebug;
}
public function isDebug() {
return $this->isDebug;
}
public function setPnapi($isPnapi = true) {
$this->isPnapi = $isPnapi;
}
private function isPnapi() {
return ($this->isPnapi ? true : false);
}
public function number($formatted = true) {
echo $this->getNumber($formatted);
}
public function jsonp($getApiUrlVariable = false) {
if($getApiUrlVariable && !isset($_GET['url'])){
self::displayError('JSONP Error. \'url\' variable does not exist! You must provide the API URL as a variable in the address bar.');
}elseif($getApiUrlVariable){
$url = str_replace(' ', '%20', $_GET['url']);
$this->apiUrls[] = new RpApiUrl($url, false);
}
if(!isset($_GET['callback'])){
self::displayError('JSONP Error. \'callback\' variable does not exist! Please ensure you are making a proper JSONP call as opposed to a standard JSON call.');
}
echo $_GET['callback'] . "(" . json_encode(array('phone' => $this->getNumber(true))) . ");";
}
public function getNumber($formatted = true) {
if($this->number){
return ($formatted ? $this->numberFormatted : $this->number);
}
$apiUrl = $this->getRandomApiUrl();
if(!$apiUrl){
self::displayError('No API URL\'s given.');
}
$requstBody = null;
if($this->isPnapi()){
$requstBody = $this->getPnapiRequestBody($apiUrl);
}
$results = $this->request($apiUrl, $requstBody);
if($this->isDebug()){
echo "<pre>Ringpool Properties:\nPNAPI: " . ($this->isPnapi() ? 'Enabled' : 'Disabled') . "\nURL's:\n" . print_r($this->apiUrls, true) . "</pre>";
echo "<pre>Request Results:\nURL: " . $apiUrl->getUrl() . "\n" . print_r($results, true) . "</pre>";
}
if(($this->isPnapi() && isset($results->responses) && count($results->responses)) || (!$this->isPnapi() && !isset($results->errors))){
if($this->isPnapi()){
$results = $results->responses[0];
}
if(isset($results->promo_number_formatted)){
$this->numberFormatted = (string) $results->promo_number_formatted;
}elseif(isset($results->PromoNumberFormatted)){
$this->numberFormatted = (string) $results->PromoNumberFormatted;
}elseif(isset($results->message)){
self::displayError('' . $results->message);
}else{
self::displayError('Could not get number from API response. URL: ' . $apiUrl->getUrl());
}
if(isset($results->promo_number)){
$this->number = (string) $results->promo_number;
}elseif(isset($results->PromoNumber)){
$this->number = (string) $results->PromoNumber;
}
return ($formatted ? $this->numberFormatted : $this->number);
}elseif(isset($results->errors) && isset($results->errors->invalid_data)){
self::displayError('' . $results->errors->invalid_data);
}else{
self::displayError('API Failed. Turn debug mode on for more information. ' . $apiUrl->getUrl());
}
}
public static function displayError($error) {
echo 'RINGPOOL ERROR: ' . $error;
die();
}
private function request($apiUrl, $post = null) {
$url = $apiUrl->getUrl();
if($this->isPnapi()){
$url = self::$pnapiUrl;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
if($post !== null){
$postStr = json_encode($post);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postStr);
}
$result = curl_exec($ch);
if($apiUrl->getFormat() == 'json'){
try {
return json_decode($result);
} catch (Exception $e) {
self::displayError('Invalid JSON returned by the API for URL: ' . $apiUrl->getUrl());
}
}elseif($apiUrl->getFormat() == 'xml'){
try {
return new SimpleXMLElement($result);
} catch (Exception $e) {
self::displayError('Invalid XML returned by the API for URL: ' . $apiUrl->getUrl());
}
}
}
}
class RpApiUrl {
private $url;
private $format;
private $suffix;
private $params;
public function __construct($url = null, $populateParams = true) {
if(empty($url)){
RpRingpool::displayError('One of the provided API URL\'s is blank.');
}
$this->url = $url;
$this->format = $this->extractFormat();
$this->params = $this->extractParams();
if($populateParams){
$this->populateParams();
}
$this->suffix = $this->extractSuffix();
}
private function extractFormat() {
if (preg_match("/allocate_number\.(xml|json)\?/", $this->url, $matches)) {
return $matches[1];
}else{
RpRingpool::displayError('All of your API URL\'s must be of format .xml or format .json.');
}
}
// suffix's are only applicable when PNAPI is enabled
private function extractSuffix() {
$parts = parse_url($this->url);
if(!isset($parts['path']) || !isset($parts['query'])){
RpRingpool::displayError('Could not extract path or query string from url: ' . $this->url);
}
if (preg_match("/ring_pools\/(.*)/", $parts['path'], $matches)) {
$suffix = $matches[1];
parse_str($parts['query'], $params);
if(isset($params['ring_pool_key'])){
$suffix .= '?ring_pool_key=' . $params['ring_pool_key'];
}
return $suffix;
}else{
RpRingpool::displayError('Could not extract suffix from url: ' . $this->url);
}
}
private function extractParams() {
$parts = parse_url($this->url);
if(!isset($parts['query'])){
RpRingpool::displayError('Could not extract query string from url: ' . $this->url);
}
parse_str($parts['query'], $params);
return $params;
}
private function populateParams() {
$params = $this->getParams(false);
foreach($params as $k => $param){
$this->params[$k] = (isset($_GET[$k]) ? urlencode($_GET[$k]) : "");
}
}
public function getUrl() {
$parts = parse_url($this->url);
return $parts['scheme'] . '://' . $parts['host'] . $parts['path'] . '?' . $this->getParamString();
}
public function getFormat() {
return $this->format;
}
public function getSuffix() {
return $this->suffix . '&' . $this->getParamString(false);
}
public function getParams($includeRingPoolKey = true) {
$params = $this->params;
if(!$includeRingPoolKey && isset($params['ring_pool_key'])){
unset($params['ring_pool_key']);
}
return $params;
}
public function getParamString($includeRingPoolKey = true) {
return http_build_query($this->getParams($includeRingPoolKey));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.