Skip to content

Instantly share code, notes, and snippets.

@kevinfelisilda
Last active August 17, 2016 04:20
Show Gist options
  • Save kevinfelisilda/588f740921b819ef183d3bba0a1d5e8d to your computer and use it in GitHub Desktop.
Save kevinfelisilda/588f740921b819ef183d3bba0a1d5e8d to your computer and use it in GitHub Desktop.
Simple Giftbit Curl Library
<?php namespace App;
class GiftBit {
private $endpoint;
private $authorization;
public function init ( $endpoint, $key )
{
if ( empty($endpoint) || empty($key) )
{
throw new \Exception('GiftBit API Endpoint Not Set.');
}
$this->endpoint = $endpoint;
$this->authorization = $key;
}
public function redeem( $code, $amount, $trans_id, $currency = 'USD' )
{
$data = (object) array (
'success' => false,
'currency' => '',
'value' => 0,
'code' => htmlentities($code),
'expires' => '',
'trans_time' => '',
'message' => ''
);
$post_data = (object) array (
'amountInCents' => (float)$amount * 100,
'currency' => $currency,
'transactionId' => (string)$trans_id
);
$response = $this->_request( 'POST', 'giftbitCode/' . $code, $post_data );
if ( isset( $response->status ) )
{
switch ( $response->status ) {
case 'success':
$data->success = true;
$data->currency = $response->data->giftbitCode->currency;
$data->value = $this->_parseAmountFromCents($response->data->giftbitCode->transactionAmountInCents);
$data->expires = $response->data->giftbitCode->expires;
$data->trans_time = $response->data->giftbitCode->transactionTime;
break;
case 'error':
$data->message = $response->message;
break;
default:
$data->message = 'Request Error';
break;
}
}
return $data;
}
private function _parseAmountFromCents( $cents )
{
return round( ((float)$cents / 100), 2 );
}
private function _request ( $method, $uri, $post_data = NULL )
{
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $this->endpoint . '/' . $uri );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, TRUE );
curl_setopt( $ch, CURLOPT_HEADER, FALSE );
if ( 'POST' == strtoupper($method) )
{
curl_setopt($ch, CURLOPT_POST, TRUE);
}
if ( ! is_null($post_data) )
{
curl_setopt($ch, CURLOPT_POSTFIELDS, "{
\"amountInCents\": $post_data->amountInCents,
\"currency\": \"$post_data->currency\",
\"transactionId\": \"$post_data->transactionId\"
}");
}
curl_setopt( $ch, CURLOPT_HTTPHEADER, array (
'Content-Type: application/json',
'Authorization: Bearer ' . $this->authorization
));
$response = curl_exec( $ch );
curl_close( $ch );
return json_decode( $response );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment