Skip to content

Instantly share code, notes, and snippets.

@jagroop jagroop/Stripe.php
Created Sep 19, 2017

Embed
What would you like to do?
Stripe Library
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use Carbon\Carbon;
class Stripe {
/**
* Default Platform Country
* @var string
*/
protected $country = "US";
/**
* Default Platform currency
* @var string
*/
protected $currency = "usd";
/**
* Account Type || true = managed , default standlone
* @var boolean
*/
protected $managed = true;
/**
* [$captureCharge description]
* @var boolean
*/
protected $captureCharge = false;
/**
* Account Type (business or individual)
* @var string
*/
protected $business_type = 'individual';
protected $tmp_upload_path = "storage/uploads/tmp/";
public $platformFees = 100; //Amount in cents (1 USD)
/**
* Get Stripe Application Fees
* @param int $amount Charge Ammount
* @return float Returns Application Fees
*/
public function getAppFee($amount) {
return round((0.029 * $amount) + 30 + $this->platformFees);
}
public function __construct() {
Stripe\Stripe::setApiKey(config_item('stripe_sec_key'));
}
/**
* Get all Customer Credit cards
* @param string $customer Stripe Customer ID
* @return object Collection of Customer cards
*/
public function getCustomerCards($customer) {
$cards = Stripe\Customer::retrieve($customer)->sources->all(array('object' => 'card'));
return $cards->data;
}
/**
* Get all User's Banks Accounts
* @param string $acc Stripe Account id
* @return object Collection of User's Bank Accounts
*/
public function getBankAccounts($acc) {
$banks = Stripe\Account::retrieve($acc)->external_accounts->all(array('object' => 'bank_account'));
return $banks->data;
}
public function subscribeToPlan($cus, $plan) {
return Stripe\Subscription::create(array(
"customer" => $cus,
"plan" => $plan,
));
}
public function getCurrentPlan($cus) {
$customer = Stripe\Customer::retrieve($cus);
return @$customer->subscriptions->data[0];
}
/**
* Determine if the subscription is within its grace period after cancellation.
*
* @return bool
*/
public function onGracePeriod($endsAt)
{
if (!is_null($endsAt)) {
return Carbon::now()->lt(Carbon::instance($endsAt));
} else {
return false;
}
}
public function active($status) {
return $status === 'active';
}
/**
* Determine if the subscription is within its trial period.
*
* @return bool
*/
public function onTrial()
{
if (! is_null($this->trial_ends_at)) {
return Carbon::today()->lt($this->trial_ends_at);
} else {
return false;
}
}
/**
* Check If Customer's plan is still Active
* @param string $cus Stripe Customer ID
* @return boolean
*/
public function isSubscribed($cus) {
try {
$plan = $this->getCurrentPlan($cus);
if(!$plan){
return false;
}
$currentPeriodEndsAt = Carbon::createFromTimestamp($plan->current_period_end);
return $this->active($plan->status) || $this->onGracePeriod($currentPeriodEndsAt);
} catch (Exception $e) {
return false;
}
}
public function getCustomerSubscriptions($cus) {
return Stripe\Subscription::all(array('limit' => 1, 'customer' => $cus));
}
/**
* Get all Users's Debit Cards
* @param string $acc Stripe Account id
* @return object Collection Users's Debit Cards
*/
public function getDebitCards($acc) {
$cards = Stripe\Account::retrieve($acc)->external_accounts->all(array('object' => 'card'))->__toArray(TRUE);
$cards = ($cards['data']) ? $cards['data'] : array();
uasort($cards, function ($a, $b) {
return ($a['default_for_currency'] > $b['default_for_currency']) ? -1 : 1;
});
return array_values($cards);
}
public function getEvent($id) {
try {
return Stripe\Event::retrieve($id);
} catch (Exception $e) {
return null;
}
}
/**
* To check if newly added card is duplicate or not
* @param string $cus Stripe Customer Id
* @param string $finger_print Credit Card Fingerprint
* @param int $exp_month Expiry Month of Credit card
* @param int $exp_year Expiry Year of Credit Card
* @return boolean Returns true of card is duplicate else false
*/
public function isDuplicate($cus, $finger_print, $exp_month, $exp_year) {
$cards = $this->getCustomerCards($cus);
if (count($cards) > 1) {
$counts = 0;
foreach ($cards as $card) {
if ($card->fingerprint === $finger_print && $card->exp_month === $exp_month && $card->exp_year === $exp_year) {
$counts++;
}
}
return ($counts > 1) ? true : false;
}
return false;
}
/**
* Generate Credit Card Token
* @param array $cardDetails Card details
* @return string Returns Token generated by stripe
*/
public function generateCardToken(array $cardDetails) {
$token = Stripe\Token::create(array(
"card" => $cardDetails,
));
return $token->id;
}
public function generateBankAccountToken(array $bankDetails) {
$token = Stripe\Token::create(array(
"bank_account" => $bankDetails,
));
return $token->id;
}
/**
* Create a Account on stripe
* @param string $bname Business Name
* @param string $email Email of Account Holder
* @return mixed(int||boolean) Returns Account id if Account was created otherwise returnd boolean false
*/
public function createAccount($bname, $email) {
try {
$createAccount = Stripe\Account::create(array(
"managed" => $this->managed,
"country" => $this->country,
"email" => $email,
"business_name" => $bname,
));
// $this->writeLog($createAccount);
return (isset($createAccount->id)) ? $createAccount->id : false;
} catch (Exception $e) {
$this->writeLog($e->getMessage());
return false;
}
return false;
}
/**
* Delete an Account from stripe
* @param strin $account Stripe Account Id
* @return boolean
*/
public function deleteAccount($account) {
$del = Stripe\Account::retrieve($account)->delete();
return isset($del->deleted) ? $del->deleted : false;
}
/**
* Create Cutomer On Stripe
* @param string $name Name of Customer
* @param string $email Customer Email Id
* @return [type] [description]
*/
public function createCustomer($name, $email, $token) {
$cus = Stripe\Customer::create(array(
"description" => $name,
"email" => $email,
"source" => $token,
));
return @$cus->id;
}
/**
* Delete a customer from Stripe
* @param strin $customer Stripte Customer Id
* @return boolean
*/
public function deleteCustomer($customer) {
$del = Stripe\Customer::retrieve($customer)->delete();
return isset($del->deleted) ? $del->deleted : false;
}
/**
* Add Customer Card on stripe
* @param strin $cus Customer Id on stripe
* @param array $cardDetails Card Details
*/
public function addCustomerCard($cus, $token, $cusName) {
$customer = Stripe\Customer::retrieve($cus);
$getCustomer = $customer;
$card = $customer->sources->create(array("source" => $token));
if ($card) {
$cardRet = $getCustomer->sources->retrieve($card->id);
$cardRet->name = $cusName;
$cardRet->save();
}
// if ($this->isDuplicate($cus, $card->fingerprint, $card->exp_month, $card->exp_year)) {
// $this->removeCustomerCard($cus, $card->id);
// return 'duplicate';
// }
return @$card->id;
}
public function setDefaultCreditCard($customer, $card, $cusName) {
$make_card_default = Stripe\Customer::retrieve($customer);
$card = $make_card_default->sources->retrieve($card);
$card->name = $cusName;
$card->save();
$make_card_default->default_source = $card;
$make = $make_card_default->save();
return ($make) ? true : false;
}
public function setDefaultAccountResource($acc, $resource) {
$account = Stripe\Account::retrieve($acc);
$bank_account = $account->external_accounts->retrieve($resource);
$bank_account->default_for_currency = true;
$save = $bank_account->save();
return ($save) ? true : false;
}
/**
* Remove Customer Card from Stripe
* @param string $customer Stripe Cutomer Id
* @param string $card Card ID
* @return boolean
*/
public function removeCustomerCard($customer, $card) {
$customer = Stripe\Customer::retrieve($customer);
$del = $customer->sources->retrieve($card)->delete();
return isset($del->deleted) ? $del->deleted : false;
}
/**
* Add bank Account on stripe for merchat
* @param string $acc Stripe Account ID
* @param array $bankDetails Bank Account Details
*/
public function addBankAccount($acc, $bankAccount, $legalEntityData, $uploadedDoc) {
$account = Stripe\Account::retrieve($acc);
$accountStatus = $account['legal_entity']['verification']['status'];
$personal_id_provided = $account['legal_entity']['personal_id_number_provided'];
$addPersonID = false;
if ($personal_id_provided === false && $legalEntityData['personal_id_number'] != "") {
$addPersonID = true;
}
if ($accountStatus === "unverified") {
if ($uploadedDoc) {
$fileName = md5(time()) . $_FILES['file']['name'];
if (is_uploaded_file($_FILES['file']['tmp_name'])) {
if (!move_uploaded_file($_FILES['file']['tmp_name'], $this->tmp_upload_path . $fileName)) {
throw new Exception("File Upload Error", 1);
} else {
move_uploaded_file($_FILES['file']['tmp_name'], $this->tmp_upload_path . $fileName);
}
}
$fileUpload = Stripe\FileUpload::create(
array(
"purpose" => "identity_document",
"file" => fopen($this->tmp_upload_path . $fileName, 'r'),
),
array("stripe_account" => trim($userAccount['stripe_account']))
);
if (isset($fileUpload->id)) {
$account->legal_entity->verification->document = $fileUpload->id;
}
if (file_exists($this->tmp_upload_path . $fileName)) {
unlink($this->tmp_upload_path . $fileName);
}
}
if ($addPersonID === true) {
$account->legal_entity->personal_id_number = $legalEntityData['personal_id_number'];
}
$account->legal_entity->ssn_last_4 = $legalEntityData['ssn_last_4'];
$account->legal_entity->first_name = $legalEntityData['first_name'];
$account->legal_entity->last_name = $legalEntityData['last_name'];
$account->legal_entity->address = $legalEntityData['address'];
$account->legal_entity->type = $this->business_type;
if (!is_null($legalEntityData['dob'])) {
$account->legal_entity->dob = $legalEntityData['dob'];
}
$account->tos_acceptance->date = time();
$account->tos_acceptance->ip = $_SERVER['REMOTE_ADDR'];
}
$token = $this->generateBankAccountToken($bankAccount);
$bank = $account->external_accounts->create(array("external_account" => $token));
$account->save();
return (isset($bank->id)) ? true : false;
}
/**
* Add Customer Card on stripe
* @param strin $cus Customer Id on stripe
* @param array $cardDetails Card Details
*/
public function addDebitCard($acc, array $cardDetails, array $legalEntityData, $uploadedDoc) {
$account = Stripe\Account::retrieve($acc);
$accountStatus = $account['legal_entity']['verification']['status'];
$personal_id_provided = $account['legal_entity']['personal_id_number_provided'];
$addPersonID = false;
if ($personal_id_provided === false && $legalEntityData['personal_id_number'] != "") {
$addPersonID = true;
}
if ($accountStatus === "unverified") {
if ($uploadedDoc) {
$fileName = md5(time()) . $_FILES['file']['name'];
if (is_uploaded_file($_FILES['file']['tmp_name'])) {
if (!move_uploaded_file($_FILES['file']['tmp_name'], $this->tmp_upload_path . $fileName)) {
throw new Exception("File Upload Error", 1);
} else {
move_uploaded_file($_FILES['file']['tmp_name'], $this->tmp_upload_path . $fileName);
}
}
$fileUpload = Stripe\FileUpload::create(
array(
"purpose" => "identity_document",
"file" => fopen($this->tmp_upload_path . $fileName, 'r'),
),
array("stripe_account" => trim($userAccount['stripe_account']))
);
if (isset($fileUpload->id)) {
$account->legal_entity->verification->document = $fileUpload->id;
}
if (file_exists($this->tmp_upload_path . $fileName)) {
unlink($this->tmp_upload_path . $fileName);
}
}
if ($addPersonID === true) {
$account->legal_entity->personal_id_number = $legalEntityData['personal_id_number'];
}
$account->legal_entity->ssn_last_4 = $legalEntityData['ssn_last_4'];
$account->legal_entity->first_name = $legalEntityData['first_name'];
$account->legal_entity->last_name = $legalEntityData['last_name'];
$account->legal_entity->address = $legalEntityData['address'];
$account->legal_entity->type = $this->business_type;
if (!is_null($legalEntityData['dob'])) {
$account->legal_entity->dob = $legalEntityData['dob'];
}
$account->tos_acceptance->date = time();
$account->tos_acceptance->ip = $_SERVER['REMOTE_ADDR'];
}
$token = $this->generateCardToken($cardDetails);
$card = $account->external_accounts->create(array("external_account" => $token));
$account->save();
return (isset($card->id)) ? $card->id : false;
}
public function createCharge($amount, $cus, $desc, $currency = "USD") {
try {
return Stripe\Charge::create(array(
"amount" => $amount,
"currency" => $currency,
"customer" => $cus,
"description" => $desc,
));
} catch (Exception $e) {
return $e->getMessage();
}
// return (isset($charge->id)) ? $charge : false;
}
// public function createCharge($amount, $source, $sourceValue, $account, $fee) {
// // $appFee = $this->getAppFee($totalAmount);
// // $transferAmount = $totalAmount - $appFee;
// $charge = Stripe\Charge::create(array(
// "amount" => $amount,
// "currency" => $this->currency,
// $source => $sourceValue,
// "application_fee" => $fee,
// "capture" => $this->captureCharge,
// "destination" => $account,
// ));
// return (isset($charge->id)) ? $charge : false;
// }
public function createTransfer($acc, $amount, $resource) {
$account = Stripe\Account::retrieve($acc);
$resource = $account->external_accounts->retrieve($resource);
$resource->default_for_currency = true;
$resource->save();
$transfer = Stripe\Transfer::create(
array(
"amount" => $amount * 100,
"currency" => $this->currency,
"destination" => "default_for_currency",
),
array("stripe_account" => $acc)
);
return (isset($transfer->id)) ? $transfer : false;
}
public function getAvailableBalance($acc) {
$balance = Stripe\Balance::retrieve(array('stripe_account' => trim($acc)));
return number_format($balance->available[0]->amount / 100, 2);
}
public function accountBalance($acc) {
$response = array();
$balance = Stripe\Balance::retrieve(array('stripe_account' => trim($acc)));
$response['balance'] = array(
'available' => array('amount' => number_format($balance->available[0]->amount / 100, 2), 'currency' => $balance->available[0]->currency),
'pending' => array('amount' => number_format($balance->pending[0]->amount / 100, 2), 'currency' => $balance->pending[0]->currency),
);
return $response;
}
public function deleteDebitCardOrbankAccount($acc, $resource) {
$account = Stripe\Account::retrieve($acc);
$delete = $account->external_accounts->retrieve($resource)->delete();
return ($delete) ? true : false;
}
public function capturePayment($ch) {
try {
$ch = Stripe\Charge::retrieve($ch);
$capture = $ch->capture();
$this->writeLog($capture);
return $capture;
} catch (Exception $e) {
return false;
}
}
}
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.