/** * Create a discount for the given user. * * @param Request $request * @param string $userId * @return Response */ public function store(Request $request, $userId) { $user = Spark::user()->where('id', $userId)->firstOrFail(); $this->validate($request, ['type' => 'required|in:amount,percent', 'value' => 'required|integer', 'duration' => 'required|in:once,forever,repeating', 'months' => 'required_if:duration,repeating']); $coupon = StripeCoupon::create(['currency' => 'usd', 'amount_off' => $request->type == 'amount' ? $request->value * 100 : null, 'percent_off' => $request->type == 'percent' ? $request->value : null, 'duration' => $request->duration, 'duration_in_months' => $request->months, 'max_redemptions' => 1], config('services.stripe.secret')); $user->applyCoupon($coupon->id); }
public function createCoupon(StripeCouponRequest $request) { //dd($request->all()); $coupon_id = $request->coupon_id; $coupon_name = $request->coupon_name; $duration = $request->duration; $duration_in_month = $duration == 'repeating' ? (int) $request->duration_in_months : NULL; $max_redemption = (int) $request->max_redemptions; $redeem_by = Carbon::parse($request->redeem_by); if ($request->amount_off_checked) { $percent_off = NULL; $coupon_currency = $request->coupon_currency; $amount_off = (int) ($request->amount_off * 100); } else { $percent_off = (int) $request->percent_off; $coupon_currency = NULL; $amount_off = NULL; } Stripe::setApiKey(getenv('STRIPE_SECRET')); $coupon = Coupon::create(array("id" => $coupon_id, "duration" => $duration, "duration_in_months" => $duration_in_month, "max_redemptions" => $max_redemption, "percent_off" => $percent_off, "amount_off" => $amount_off, "currency" => $coupon_currency, "redeem_by" => $redeem_by->timestamp)); $coupon_local = StripeCoupon::create(["coupon_id" => $coupon_id, "coupon_name" => $coupon_name, "duration" => $duration, "duration_in_months" => $duration_in_month, "max_redemptions" => $max_redemption, "percent_off" => $percent_off, "amount_off" => $amount_off, "currency" => $coupon_currency, "redeem_by" => $redeem_by]); if ($coupon_local) { flash('Your Coupon (' . $coupon_local->coupon_name . ') is successfully created.'); } else { flash('Your Coupon (' . $coupon_local->coupon_name . ') is failed to create. Please contact your administrator for assistance.'); } return redirect()->back(); }
public function testCreate() { authorizeFromEnv(); $c = Coupon::create(array('percent_off' => 25, 'duration' => 'repeating', 'duration_in_months' => 5, 'id' => 'test_coupon')); $this->assertEqual('test_coupon', $c->id); $this->assertEqual(25, $c->percent_off); }
/** * {@inheritdoc} */ public function find($code) { try { $coupon = StripeCoupon::retrieve($code, ['api_key' => config('services.stripe.secret')]); if ($coupon && $coupon->valid) { return $this->toCoupon($coupon); } } catch (Exception $e) { // } }
/** * Get the current coupon for the authenticated user. * * Used to display current discount on settings -> subscription tab. * * @return \Illuminate\Http\Response */ public function getCouponForUser() { Stripe::setApiKey(config('services.stripe.secret')); if (count(Spark::plans()) === 0) { abort(404); } try { $customer = StripeCustomer::retrieve(Auth::user()->stripe_id); if ($customer->discount) { return response()->json(Coupon::fromStripeCoupon(StripeCoupon::retrieve($customer->discount->coupon->id))); } else { abort(404); } } catch (Exception $e) { abort(404); } }
/** * Validate that the provided coupon actually exists on Stripe. * * @param \Illuminate\Validation\Validator $validator * @param \Illuminate\Http\Request $request * @return void */ protected function validateCoupon($validator, Request $request) { try { $coupon = StripeCoupon::retrieve($request->coupon, ['api_key' => config('services.stripe.secret')]); if ($coupon && $coupon->valid) { return; } } catch (Exception $e) { // } $validator->errors()->add('coupon', 'The provided coupon code is invalid.'); }
/** * Check if a coupone exists in Stripe * * @access private * @since 2.1 */ function rcp_stripe_does_coupon_exists($code) { global $rcp_options; if (!class_exists('Stripe\\Stripe')) { require_once RCP_PLUGIN_DIR . 'includes/libraries/stripe/init.php'; } if (isset($rcp_options['sandbox'])) { $secret_key = trim($rcp_options['stripe_test_secret']); } else { $secret_key = trim($rcp_options['stripe_live_secret']); } \Stripe\Stripe::setApiKey($secret_key); try { \Stripe\Coupon::retrieve($code); $exists = true; } catch (Exception $e) { $exists = false; } return $exists; }
function new_coupon(WP_REST_Request $request) { $data = $request->get_params(); $this->set_api_key(); try { $coupon = \Stripe\Coupon::create($data); return new WP_REST_Response($coupon, 200); } catch (\Stripe\Error\RateLimit $e) { $body = $e->getJsonBody(); $err = $body['error']; return new WP_Error($err['type'], __($err['message']), array('status' => $e->getHttpStatus())); } catch (\Stripe\Error\InvalidRequest $e) { $body = $e->getJsonBody(); $err = $body['error']; return new WP_Error($err['type'], __($err['message']), array('status' => $e->getHttpStatus())); } catch (\Stripe\Error\Authentication $e) { $body = $e->getJsonBody(); $err = $body['error']; return new WP_Error($err['type'], __($err['message']), array('status' => $e->getHttpStatus())); } catch (\Stripe\Error\ApiConnection $e) { $body = $e->getJsonBody(); $err = $body['error']; return new WP_Error($err['type'], __($err['message']), array('status' => $e->getHttpStatus())); } catch (\Stripe\Error\Base $e) { $body = $e->getJsonBody(); $err = $body['error']; return new WP_Error($err['type'], __($err['message']), array('status' => $e->getHttpStatus())); } catch (Exception $e) { $body = $e->getJsonBody(); $err = $body['error']; } }
/** * Retrieve stripe coupon object * * @param string $id Coupon StripeID * * @return \Stripe\Coupon */ public function retrieve($id) { return StripeCouponApi::retrieve($id); }
public function getCoupons($limit, $after = null, $before = null) { return \Stripe\Coupon::all(['limit' => $limit, 'starting_after' => $after, 'ending_before' => $before]); }
error_reporting(E_ALL); require_once './config.php'; $coupon_attempt = FALSE; $coupon_verified = FALSE; $token = $_POST['stripeToken']; $plan = $_POST['plan']; $email = $_POST['stripeEmail']; $cost = $_POST['cost']; $start_date = get_date(); var_dump($start_date); if ($plan && strlen($plan) > 4) { if (isset($_POST['coupon']) && strlen($_POST['coupon']) > 0) { $coupon_code = $_POST['coupon']; $coupon_attempt = TRUE; try { $coupon = \Stripe\Coupon::retrieve($coupon_code); if ($coupon !== NULL) { $coupon_verified = TRUE; $discount = $coupon['amount_off']; $discount = substr($discount, 0, -2); $cost = $cost - $discount; } } catch (Exception $e) { $message = $e->getMessage(); echo "Sorry, that wasn't a valid coupon code"; $coupon_verified = FALSE; } } if ($coupon_verified == TRUE) { $customer = \Stripe\Customer::create(array("source" => $token, "plan" => $plan, "email" => $email, "coupon" => $coupon_code, 'billing_cycle_anchor' => $start_date)); echo "<h1>Successfully charged for \${$cost}!</h1>";
/** * request method * * @param string $method * @param array $data * * @return array - containing 'status', 'message' and 'data' keys * if response was successful, keys will be 'success', 'Success' and the stripe response as associated array respectively, * if request failed, keys will be 'error', the card error message if it was card_error, boolen false otherwise, and * error data as an array respectively */ private function request($method = null, $data = null) { if (!$method) { throw new Exception(__('Request method is missing')); } if (is_null($data)) { throw new Exception(__('Request Data is not provided')); } Stripe::setApiKey($this->key); $success = null; $error = null; $message = false; $log = null; try { switch ($method) { /** * * CHARGES * */ case 'charge': $success = $this->fetch(Charge::create($data)); break; case 'retrieveCharge': $success = $this->fetch(Charge::retrieve($data['charge_id'])); if (!empty($success['refunds'])) { foreach ($success['refunds'] as &$refund) { $refund = $this->fetch($refund); } } break; case 'updateCharge': $charge = Charge::retrieve($data['charge_id']); foreach ($data['fields'] as $field => $value) { $charge->{$field} = $value; } $success = $this->fetch($charge->save()); break; case 'refundCharge': $charge = Charge::retrieve($data['charge_id']); // to prevent unknown param error unset($data['charge_id']); $success = $this->fetch($charge->refund($data)); foreach ($success['refunds']['data'] as &$refund) { $refund = $this->fetch($refund); } break; case 'captureCharge': $charge = Charge::retrieve($data['charge_id']); unset($data['charge_id']); $success = $this->fetch($charge->capture($data)); if (!empty($success['refunds']['data'])) { foreach ($success['refunds']['data'] as &$refund) { $refund = $this->fetch($refund); } } break; case 'listCharges': $charges = Charge::all(); $success = $this->fetch($charges); foreach ($success['data'] as &$charge) { $charge = $this->fetch($charge); if (isset($charge['refunds']['data']) && !empty($charge['refunds']['data'])) { foreach ($charge['refunds']['data'] as &$refund) { $refund = $this->fetch($refund); } unset($refund); } } break; /** * CUSTOMERS */ /** * CUSTOMERS */ case 'createCustomer': $customer = Customer::create($data); $success = $this->fetch($customer); if (!empty($success['cards']['data'])) { foreach ($success['cards']['data'] as &$card) { $card = $this->fetch($card); } unset($card); } if (!empty($success['subscriptions']['data'])) { foreach ($success['subscriptions']['data'] as &$subscription) { $subscription = $this->fetch($subscription); } unset($subscription); } break; case 'retrieveCustomer': $customer = Customer::retrieve($data['customer_id']); $success = $this->fetch($customer); if (!empty($success['cards']['data'])) { foreach ($success['cards']['data'] as &$card) { $card = $this->fetch($card); } unset($card); } if (!empty($success['subscriptions']['data'])) { foreach ($success['subscriptions']['data'] as &$subscription) { $subscription = $this->fetch($subscription); } unset($subscription); } break; case 'updateCustomer': $cu = Customer::retrieve($data['customer_id']); foreach ($data['fields'] as $field => $value) { $cu->{$field} = $value; } $success = $this->fetch($cu->save()); if (!empty($success['cards']['data'])) { foreach ($success['cards']['data'] as &$card) { $card = $this->fetch($card); } unset($card); } if (!empty($success['subscriptions']['data'])) { foreach ($success['subscriptions']['data'] as &$subscription) { $subscription = $this->fetch($subscription); } unset($subscription); } break; case 'deleteCustomer': $cu = Customer::retrieve($data['customer_id']); $success = $this->fetch($cu->delete()); break; case 'listCustomers': $customers = Customer::all($data['options']); $success = $this->fetch($customers); foreach ($success['data'] as &$customer) { $customer = $this->fetch($customer); if (!empty($customer['cards']['data'])) { foreach ($customer['cards']['data'] as &$card) { $card = $this->fetch($card); } unset($card); } if (!empty($customer['subscriptions']['data'])) { foreach ($customer['subscriptions']['data'] as &$subscription) { $subscription = $this->fetch($subscription); } unset($subscription); } } break; /** * CARDS * */ /** * CARDS * */ case 'createCard': $cu = Customer::retrieve($data['customer_id']); $validCardFields = ['object', 'address_zip', 'address_city', 'address_state', 'address_country', 'address_line1', 'address_line2', 'number', 'exp_month', 'exp_year', 'cvc', 'name', 'metadata']; // unset not valid keys to prevent unknown parameter stripe error unset($data['customer_id']); foreach ($data['source'] as $k => $v) { if (!in_array($k, $validCardFields)) { unset($data['source'][$k]); } } $card = $cu->sources->create($data); $success = $this->fetch($card); break; case 'retrieveCard': $cu = Customer::retrieve($data['customer_id']); $card = $cu->sources->retrieve($data['card_id']); $success = $this->fetch($card); break; case 'updateCard': $cu = Customer::retrieve($data['customer_id']); $cuCard = $cu->sources->retrieve($data['card_id']); foreach ($data['fields'] as $field => $value) { $cuCard->{$field} = $value; } $card = $cuCard->save(); $success = $this->fetch($card); break; case 'deleteCard': $cu = Customer::retrieve($data['customer_id']); $card = $cu->sources->retrieve($data['card_id'])->delete(); $success = $this->fetch($card); break; case 'listCards': $cu = Customer::retrieve($data['customer_id']); $cards = $cu->sources->all($data['options']); $success = $this->fetch($cards); foreach ($success['data'] as &$card) { $card = $this->fetch($card); } break; /** * SUBSCRIPTIONS * */ /** * SUBSCRIPTIONS * */ case 'createSubscription': $cu = Customer::retrieve($data['customer_id']); // unset customer_id to prevent unknown parameter stripe error unset($data['customer_id']); $subscription = $cu->subscriptions->create($data['subscription']); $success = $this->fetch($subscription); break; case 'retrieveSubscription': $cu = Customer::retrieve($data['customer_id']); $subscription = $cu->subscriptions->retrieve($data['subscription_id']); $success = $this->fetch($subscription); break; case 'updateSubscription': $cu = Customer::retrieve($data['customer_id']); $cuSubscription = $cu->subscriptions->retrieve($data['subscription_id']); foreach ($data['fields'] as $field => $value) { $cuSubscription->{$field} = $value; } $subscription = $cuSubscription->save(); $success = $this->fetch($subscription); break; case 'cancelSubscription': $cu = Customer::retrieve($data['customer_id']); $subscription = $cu->subscriptions->retrieve($data['subscription_id'])->cancel($data['at_period_end']); $success = $this->fetch($subscription); break; case 'listSubscriptions': $cu = Customer::retrieve($data['customer_id']); $subscriptions = $cu->subscriptions->all($data['options']); $success = $this->fetch($subscriptions); foreach ($success['data'] as &$subscription) { $subscription = $this->fetch($subscription); } break; /** * PLANS * */ /** * PLANS * */ case 'createPlan': $plan = Plan::create($data); $success = $this->fetch($plan); break; case 'retrievePlan': $plan = Plan::retrieve($data['plan_id']); $success = $this->fetch($plan); break; case 'updatePlan': $p = Plan::retrieve($data['plan_id']); foreach ($data['fields'] as $field => $value) { $p->{$field} = $value; } $plan = $p->save(); $success = $this->fetch($plan); break; case 'deletePlan': $p = Plan::retrieve($data['plan_id']); $plan = $p->delete(); $success = $this->fetch($plan); break; case 'listPlans': $plans = Plan::all($data['options']); $success = $this->fetch($plans); foreach ($success['data'] as &$plan) { $plan = $this->fetch($plan); } break; /** * COUPONS * */ /** * COUPONS * */ case 'createCoupon': $coupon = Coupon::create($data); $success = $this->fetch($coupon); break; case 'retrieveCoupon': $coupon = Coupon::retrieve($data['coupon_id']); $success = $this->fetch($coupon); break; case 'deleteCoupon': $c = Coupon::retrieve($data['coupon_id']); $coupon = $c->delete(); $success = $this->fetch($coupon); break; case 'listCoupons': $coupons = Coupon::all($data['options']); $success = $this->fetch($coupons); foreach ($success['data'] as &$coupon) { $coupon = $this->fetch($coupon); } break; /** * * EVENTS * */ /** * * EVENTS * */ case 'retrieveEvent': $event = Event::retrieve($data['event_id']); $success = $this->fetch($event); // cards if (isset($success['data']['object']['cards']['data']) && !empty($success['data']['object']['cards']['data'])) { foreach ($success['data']['object']['cards']['data'] as &$card) { $card = $this->fetch($card); } unset($refund); } break; case 'listEvents': $events = Event::all($data['options']); $success = $this->fetch($events); foreach ($success['data'] as &$event) { $event = $this->fetch($event); // refunds if (isset($event['data']['object']['refunds']) && !empty($event['data']['object']['refunds'])) { foreach ($event['data']['object']['refunds'] as &$refund) { $refund = $this->fetch($refund); } unset($refund); } // cards if (isset($event['data']['object']['cards']['data']) && !empty($event['data']['object']['cards']['data'])) { foreach ($event['data']['object']['cards']['data'] as &$card) { $card = $this->fetch($card); } unset($refund); } } break; } } catch (Card $e) { $body = $e->getJsonBody(); $error = $body['error']; $error['http_status'] = $e->getHttpStatus(); $message = $error['message']; } catch (InvalidRequest $e) { $body = $e->getJsonBody(); $error = $body['error']; $error['http_status'] = $e->getHttpStatus(); } catch (Authentication $e) { $error = $e->getJsonBody(); $error['http_status'] = $e->getHttpStatus(); } catch (ApiConnection $e) { $body = $e->getJsonBody(); $error['http_status'] = $e->getHttpStatus(); } catch (Base $e) { $body = $e->getJsonBody(); $error['http_status'] = $e->getHttpStatus(); } catch (\Exception $e) { $body = $e->getJsonBody(); $error['http_status'] = $e->getHttpStatus(); } if ($success) { // if ($this->logFile && in_array($this->logType, ['both', 'success'])) { // CakeLog::write('Success', $method, $this->logFile); // } return ['status' => 'success', 'message' => 'Success', 'response' => $success]; } $str = ''; $str .= $method . ", type:" . (!empty($error['type']) ? $error['type'] : ''); $str .= ", type:" . (!empty($error['type']) ? $error['type'] : ''); $str .= ", http_status:" . (!empty($error['http_status']) ? $error['http_status'] : ''); $str .= ", param:" . (!empty($error['param']) ? $error['param'] : ''); $str .= ", message:" . (!empty($error['message']) ? $error['message'] : ''); // if ($this->logFile && in_array($this->logType, array('both', 'error'))) { // CakeLog::write('Error', $str, $this->logFile ); // } return ['status' => 'error', 'message' => $message, 'response' => $error]; }
/** * Function to handle AJAX request for coupon check * * @since 2.0.0 */ function coup_ajax_check() { global $sc_options; $json = ''; $code = $_POST['coupon']; $amount = $_POST['amount']; $json['coupon']['code'] = $code; $test_mode = $_POST['test_mode']; Stripe_Checkout_Functions::set_key($test_mode); try { $coupon = \Stripe\Coupon::retrieve(trim($code)); if (!empty($coupon->percent_off)) { $json['coupon']['amountOff'] = $coupon->percent_off; $json['coupon']['type'] = 'percent'; if ($coupon->percent_off == 100) { $amount = 0; } else { $amount = round($amount * ((100 - $coupon->percent_off) / 100)); } } else { if (!empty($coupon->amount_off)) { $json['coupon']['amountOff'] = $coupon->amount_off; $json['coupon']['type'] = 'amount'; $amount = $amount - $coupon->amount_off; if ($amount < 0) { $amount = 0; } } } // Set message to amount now before checking for errors $json['success'] = true; $json['message'] = $amount; if ($amount < 50) { $json['success'] = false; $json['message'] = __('Coupon entered puts the total below the required minimum amount.', 'stripe'); } } catch (Exception $e) { // an exception was caught, so the code is invalid $json['success'] = false; $json['message'] = __('Invalid coupon code.', 'stripe'); } // Return as JSON echo json_encode($json); die; }
public function plan() { $user = $this->session->user(); // When the user isn't a Stripe customer, we need to get a payment method from them and a token... if (!$user->isStripeCustomer()) { AppController::redirect(RouteController::fqURL('subscription.payment')); } if ($this->request->isPOST()) { $post = $this->request->postData(); if (!empty($post['plan'])) { try { \Stripe\Stripe::setApiKey(AppConfig::getValue('stripe_secret_api_key')); // Fetch the Customer Object $customer = $this->getCustomer($user); // Validate the Plan $plan = \Stripe\Plan::retrieve($post['plan']); // Validate a Coupon if (!empty($post['coupon'])) { $coupon = \Stripe\Coupon::retrieve($post['coupon']); } // Are we updating an existing subscription? if ($customer->subscriptions->total_count > 0) { // Update/Change Subscription $subscription = $customer->subscriptions->retrieve($customer->subscriptions->data[0]->id); $subscription->plan = $plan->id; $subscription->coupon = isset($coupon) ? $coupon->id : null; $subscription->save(); } else { // New Subscription $customer->subscriptions->create(['plan' => $plan->id, 'coupon' => isset($coupon) ? $coupon->id : null], ['idempotency_key' => hash('sha256', $customer->id . $customer->subscriptions->data[0]->plan->id . $plan->id)]); } // Update User (internal) $user->subscription = $plan->name; $user->save(); // Done, Redirect... AppController::redirect(addQueryParams(RouteController::fqURL('subscription.manage'), ['status' => 'plan-added'])); } catch (\Stripe\Error\Card $exception) { $this->logStripeException($exception, (string) $this->request->queryArgValue('token')); } catch (\Stripe\Error\InvalidRequest $exception) { $this->logStripeException($exception, (string) $this->request->queryArgValue('token')); } catch (\Stripe\Error\Authentication $exception) { $this->logStripeException($exception, (string) $this->request->queryArgValue('token')); } catch (\Stripe\Error\ApiConnection $exception) { $this->logStripeException($exception, (string) $this->request->queryArgValue('token')); } catch (\Stripe\Error\Base $exception) { $this->logStripeException($exception, (string) $this->request->queryArgValue('token')); } } else { AppController::fatalError('plan (required) was missing from the request'); } } else { // Fetch Plans (only use required data) foreach ($this->getAvailablePlans()['data'] as $plan) { $planList[] = ['id' => $plan->id, 'name' => $plan->name, 'amount' => $plan->amount, 'currency' => $plan->currency, 'interval' => $plan->interval, 'interval_count' => $plan->interval_count]; } if (isset($planList) && count($planList)) { // Sort by Amount (ASC) usort($planList, function ($a, $b) { return $a['amount'] > $b['amount']; }); } } $this->view = new HTMLView(); $this->view->includeTemplate('subscription.plan', ['app_name' => AppConfig::getValue('app_name'), 'plans' => isset($planList) ? $planList : null]); $this->view->render(true); }
protected static function coupon($id) { return \Stripe\Coupon::create(['id' => $id . '-' . \Phalcon\Text::random(5), 'duration' => 'forever', 'percent_off' => 25]); }