Esempio n. 1
0
 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();
 }
Esempio n. 2
0
 /**
  * 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);
 }
Esempio n. 3
0
 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);
 }
Esempio n. 4
0
 /**
  * Create new coupon
  *
  * @param string $duration
  * @param array|null $params
  *
  * @return \Stripe\Coupon
  * @throws StripeException
  */
 public function create($duration, $params = null)
 {
     if (empty($params['amount_off']) && empty($params['percent_off'])) {
         throw new StripeException('Coupon should have amount or percent off');
     }
     if (!empty($params['amount_off']) && empty('currency')) {
         throw new StripeException('Coupon should have currency for amount off');
     }
     if ($duration == self::DURATION_REPEATING && empty($params['duration_in_months'])) {
         throw new StripeException('Coupon should have duration_in_months for repeating duration');
     }
     $params = array_merge(array('duration' => $duration), $params);
     return StripeCouponApi::create($params);
 }
/**
 * Update a discount in Stripe when a local code is updated
 *
 * @access      private
 * @since       2.1
 */
function rcp_stripe_update_discount()
{
    if (!is_admin()) {
        return;
    }
    if (function_exists('rcp_stripe_add_discount')) {
        return;
        // Old Stripe gateway is active
    }
    if (!rcp_is_gateway_enabled('stripe')) {
        return;
    }
    global $rcp_options;
    if (!class_exists('Stripe\\Stripe')) {
        require_once RCP_PLUGIN_DIR . 'includes/libraries/stripe/init.php';
    }
    if (!empty($_REQUEST['deactivate_discount']) || !empty($_REQUEST['activate_discount'])) {
        return;
    }
    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);
    if (!rcp_stripe_does_coupon_exists($_POST['code'])) {
        try {
            if ($_POST['unit'] == '%') {
                \Stripe\Coupon::create(array("percent_off" => sanitize_text_field($_POST['amount']), "duration" => "forever", "id" => sanitize_text_field($_POST['code']), "currency" => strtolower($rcp_options['currency'])));
            } else {
                \Stripe\Coupon::create(array("amount_off" => sanitize_text_field($_POST['amount']) * 100, "duration" => "forever", "id" => sanitize_text_field($_POST['code']), "currency" => strtolower($rcp_options['currency'])));
            }
        } catch (Exception $e) {
            wp_die('<pre>' . $e . '</pre>', __('Error', 'rcp_stripe'));
        }
    } else {
        // first delete the discount in Stripe
        try {
            $cpn = \Stripe\Coupon::retrieve($_POST['code']);
            $cpn->delete();
        } catch (Exception $e) {
            wp_die('<pre>' . $e . '</pre>', __('Error', 'rcp_stripe'));
        }
        // now add a new one. This is a fake "update"
        try {
            if ($_POST['unit'] == '%') {
                \Stripe\Coupon::create(array("percent_off" => sanitize_text_field($_POST['amount']), "duration" => "forever", "id" => sanitize_text_field($_POST['code']), "currency" => strtolower($rcp_options['currency'])));
            } else {
                \Stripe\Coupon::create(array("amount_off" => sanitize_text_field($_POST['amount']) * 100, "duration" => "forever", "id" => sanitize_text_field($_POST['code']), "currency" => strtolower($rcp_options['currency'])));
            }
        } catch (\Stripe\Error\InvalidRequest $e) {
            // Invalid parameters were supplied to Stripe's API
            $body = $e->getJsonBody();
            $err = $body['error'];
            $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
            if (isset($err['code'])) {
                $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
            }
            $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
            $error .= "<p>Message: " . $err['message'] . "</p>";
            wp_die($error, __('Error', 'rcp'), array('response' => 401));
        } catch (\Stripe\Error\Authentication $e) {
            // Authentication with Stripe's API failed
            // (maybe you changed API keys recently)
            $body = $e->getJsonBody();
            $err = $body['error'];
            $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
            if (isset($err['code'])) {
                $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
            }
            $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
            $error .= "<p>Message: " . $err['message'] . "</p>";
            wp_die($error, __('Error', 'rcp'), array('response' => 401));
        } catch (\Stripe\Error\ApiConnection $e) {
            // Network communication with Stripe failed
            $body = $e->getJsonBody();
            $err = $body['error'];
            $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
            if (isset($err['code'])) {
                $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
            }
            $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
            $error .= "<p>Message: " . $err['message'] . "</p>";
            wp_die($error, __('Error', 'rcp'), array('response' => 401));
        } catch (\Stripe\Error\Base $e) {
            // Display a very generic error to the user
            $body = $e->getJsonBody();
            $err = $body['error'];
            $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
            if (isset($err['code'])) {
                $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
            }
            $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
            $error .= "<p>Message: " . $err['message'] . "</p>";
            wp_die($error, __('Error', 'rcp'), array('response' => 401));
        } catch (Exception $e) {
            // Something else happened, completely unrelated to Stripe
            $error = '<p>' . __('An unidentified error occurred.', 'rcp') . '</p>';
            $error .= print_r($e, true);
            wp_die($error, __('Error', 'rcp'), array('response' => 401));
        }
    }
}
 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'];
     }
 }
 /**
  * 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];
 }
Esempio n. 8
0
 protected static function coupon($id)
 {
     return \Stripe\Coupon::create(['id' => $id . '-' . \Phalcon\Text::random(5), 'duration' => 'forever', 'percent_off' => 25]);
 }