Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Stripe basic class

NOTE

Always handle errors when you use stripe functions. You don't want to make mistakes when it comes to people's money.

Create a customer

$stripe_client = new Stripe_Client( $user, $stripe_secret, $token );

try {
  $customer = $stripe_client->create_customer();
} catch (Exception $e) {
  //Handle it.  
}

Charge a customer

$stripe_client = new Stripe_Client( $user, $stripe_secret );

//First we get him
try {
    $customer = $stripe_client->retrieve_customer();
} catch ( Exception $e ) {
  //Handle it. 
}

//Now we charge
try {
    $charge = $stripe_client->charge_customer( $customer, 50000, 'Product payment');
} catch ( Exception $e ) {
    //Handle it.
}
<?php
class Stripe_Client {
private $user;
private $payment_token;
public function __construct( $user, $stripe_secret, $payment_token = null ) {
$this->user = $user;
$this->payment_token = $payment_token;
\Stripe\Stripe::setApiKey( $stripe_secret );
}
public function set_user_stripe_id( $customer_id ) {
update_user_meta( $this->user->ID, 'stripe_id', $customer_id);
}
public function create_customer() {
$customer = \Stripe\Customer::create( [
'email' => $this->user->user_email,
'source' => $this->payment_token
] );
$this->set_user_stripe_id( $customer->id );
return $customer;
}
public function retrieve_customer() {
$user_stripe_id = get_user_meta($this->user->ID, 'stripe_id', true);
return \Stripe\Customer::retrieve( $user_stripe_id );
}
public function charge_customer( $customer, $amount, $description ) {
$charge = \Stripe\Charge::create( [
"amount" => $amount,
"currency" => "usd",
"description" => $description,
"customer" => $customer->id
] );
return $charge;
}
public function update_customer_card( $customer ) {
$customer->source = $this->payment_token;
$customer->save();
return $customer;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment