public function do_charge() { if (wp_verify_nonce($_POST['wp-simple-pay-pro-nonce'], 'charge_card')) { global $sc_options; $query_args = array(); // Set redirect $redirect = $_POST['sc-redirect']; $fail_redirect = $_POST['sc-redirect-fail']; $failed = null; $message = ''; // Get the credit card details submitted by the form $token = $_POST['stripeToken']; $amount = $_POST['sc-amount']; $description = $_POST['sc-description']; $store_name = $_POST['sc-name']; $currency = $_POST['sc-currency']; $details_placement = $_POST['sc-details-placement']; $charge = null; $sub = isset($_POST['sc_sub_id']); $interval = isset($_POST['sc_sub_interval']) ? $_POST['sc_sub_interval'] : 'month'; $interval_count = isset($_POST['sc_sub_interval_count']) ? $_POST['sc_sub_interval_count'] : 1; $statement_description = isset($_POST['sc_sub_statement_description']) ? $_POST['sc_sub_statement_description'] : ''; $setup_fee = isset($_POST['sc_sub_setup_fee']) ? $_POST['sc_sub_setup_fee'] : 0; $coupon = isset($_POST['sc_coup_coupon_code']) ? $_POST['sc_coup_coupon_code'] : ''; $test_mode = isset($_POST['sc_test_mode']) ? $_POST['sc_test_mode'] : 'false'; if ($sub) { $sub = !empty($_POST['sc_sub_id']) ? $_POST['sc_sub_id'] : 'custom'; } Stripe_Checkout_Functions::set_key($test_mode); $meta = array(); if (!empty($setup_fee)) { $meta['Setup Fee'] = Stripe_Checkout_Misc::to_formatted_amount($setup_fee, $currency); } $meta = apply_filters('sc_meta_values', $meta); try { if ($sub == 'custom') { $timestamp = time(); $plan_id = $_POST['stripeEmail'] . '_' . $amount . '_' . $timestamp; $name = __('Subscription:', 'sc_sub') . ' ' . Stripe_Checkout_Misc::to_formatted_amount($amount, $currency) . ' ' . strtoupper($currency) . '/' . $interval; // Create a plan $plan_args = array('amount' => $amount, 'interval' => $interval, 'name' => $name, 'currency' => $currency, 'id' => $plan_id, 'interval_count' => $interval_count); if (!empty($statement_description)) { $plan_args['statement_descriptor'] = $statement_description; } $new_plan = \Stripe\Plan::create($plan_args); // Create a customer and charge $new_customer = \Stripe\Customer::create(array('email' => $_POST['stripeEmail'], 'card' => $token, 'plan' => $plan_id, 'metadata' => $meta, 'account_balance' => $setup_fee)); } else { // Create new customer $cust_args = array('email' => $_POST['stripeEmail'], 'card' => $token, 'plan' => $sub, 'metadata' => $meta, 'account_balance' => $setup_fee); if (!empty($coupon)) { $cust_args['coupon'] = $coupon; } $new_customer = \Stripe\Customer::create($cust_args); // Set currency based on sub $plan = \Stripe\Plan::retrieve($sub); //echo $subscription . '<Br>'; $currency = strtoupper($plan->currency); } // We want to add the meta data and description to the actual charge so that users can still view the meta sent with a subscription + custom fields // the same way that they would normally view it without subscriptions installed. // We need the steps below to do this // First we get the latest invoice based on the customer ID $invoice = \Stripe\Invoice::all(array('customer' => $new_customer->id, 'limit' => 1)); // If this is a trial we need to skip this part since a charge is not made $trial = $invoice->data[0]->lines->data[0]->plan->trial_period_days; if (empty($trial) || !empty($setup_fee)) { // Now that we have the invoice object we can get the charge ID $inv_charge = $invoice->data[0]->charge; // Finally, with the charge ID we can update the specific charge and inject our meta data sent from Stripe Custom Fields $ch = \Stripe\Charge::retrieve($inv_charge); $charge = $ch; if (!empty($meta)) { $ch->metadata = $meta; } if (!empty($description)) { $ch->description = $description; } $ch->save(); $query_args = array('charge' => $ch->id, 'store_name' => urlencode($store_name)); $failed = false; } else { $sub_id = $invoice->data[0]->subscription; if (!empty($description)) { $customer = \Stripe\Customer::retrieve($new_customer->id); $subscription = $customer->subscriptions->retrieve($sub_id); $subscription->metadata = array('product' => $description); $subscription->save(); } $query_args = array('cust_id' => $new_customer->id, 'sub_id' => $sub_id, 'store_name' => urlencode($store_name)); $failed = false; } } catch (Exception $e) { // Something else happened, completely unrelated to Stripe $redirect = $fail_redirect; $failed = true; $e = $e->getJsonBody(); $query_args = array('sub' => true, 'error_code' => $e['error']['type'], 'charge_failed' => true); } unset($_POST['stripeToken']); do_action('sc_redirect_before'); if ($test_mode == 'true') { $query_args['test_mode'] = 'true'; } if ('below' == $details_placement) { $query_args['details_placement'] = $details_placement; } if (!empty($trial) && empty($setup_fee)) { $query_args['trial'] = 1; } wp_redirect(esc_url_raw(add_query_arg(apply_filters('sc_redirect_args', $query_args, $charge), apply_filters('sc_redirect', $redirect, $failed)))); exit; } }
public function testSave() { $customer = self::createTestCustomer(); $customer->email = '*****@*****.**'; $customer->save(); $this->assertEqual($customer->email, '*****@*****.**'); $customer2 = Customer::retrieve($customer->id); $this->assertEqual($customer->email, $customer2->email); }
/** * @param User $user * @param $request * @return boolean */ public function addCard(User $user, $request) { $stripeToken = $request->request->get('token'); if ($stripeToken) { $customer = StripeCustomer::retrieve($this->getCustomerId($user)); $card = $customer->sources->create(['source' => $stripeToken]); return $card instanceof StripeCard; } return false; }
public static function getCards($customerId) { $customer = \Stripe\Customer::retrieve($customerId); $cardsCollection = \Stripe\Customer::retrieve($customerId)->sources->all(['object' => 'card']); $cards = []; foreach ($cardsCollection['data'] as $card) { $cards[] = ['cardId' => $card->id, 'last4' => $card->last4, 'expMonth' => $card->exp_month, 'expYear' => $card->exp_year]; } return $cards; }
/** * updateSubscriptions * -------------------------------------------------- * Updating the StripeSubscriptions. * @returns The stripe plans. * @throws StripeNotConnected * -------------------------------------------------- */ public function updateSubscriptions() { // Connecting to stripe. // Deleting all subscription to avoid constraints. $this->updatePlans(); $subscriptions = array(); foreach ($this->getCustomers() as $customer) { $decodedData = json_decode($this->loadJSON(\Stripe\Customer::retrieve($customer['id'])->subscriptions->all()), TRUE); foreach ($decodedData['data'] as $subscription) { $new_subscription = new StripeSubscription(array('subscription_id' => $subscription['id'], 'start' => $subscription['start'], 'status' => $subscription['status'], 'customer' => $subscription['customer'], 'ended_at' => $subscription['ended_at'], 'canceled_at' => $subscription['canceled_at'], 'quantity' => $subscription['quantity'], 'discount' => $subscription['discount'], 'trial_start' => $subscription['trial_start'], 'trial_end' => $subscription['trial_start'], 'discount' => $subscription['discount'])); $plan = StripePlan::where('plan_id', $subscription['plan']['id'])->first(); if ($plan === null) { // Stripe integrity error, link to a non-existing plan. return array(); } $new_subscription->plan()->associate($plan); array_push($subscriptions, $new_subscription); } } // Save new. foreach ($subscriptions as $subscription) { $subscription->save(); } return $subscriptions; }
/** * Attempts to create or retrieve the Stripe Customer for this model. * * @return Customer|false */ public function stripeCustomer() { $app = $this->getApp(); $apiKey = $app['config']->get('stripe.secret'); // attempt to retreive the customer on stripe try { if ($custId = $this->stripe_customer) { return Customer::retrieve($custId, $apiKey); } } catch (StripeError $e) { $app['logger']->debug($e); $app['errors']->push(['error' => 'stripe_error', 'message' => $e->getMessage()]); return false; } // create the customer on stripe try { // This is necessary because save() on stripe objects does // not accept an API key or save one from the retrieve() request Stripe::setApiKey($app['config']->get('stripe.secret')); $customer = Customer::create($this->stripeCustomerData(), $apiKey); // save the new customer id on the model $this->stripe_customer = $customer->id; $this->grantAllPermissions()->save(); $this->enforcePermissions(); return $customer; } catch (StripeError $e) { // log any errors not related to invalid cards if (!$e instanceof StripeCardError) { $app['logger']->error($e); } $app['errors']->push(['error' => 'stripe_error', 'message' => $e->getMessage()]); } return false; }
/** * Check stripe data. * * @access public * @return void */ public function run() { $paymentGateway = Payment_gateways::findOneActiveBySlug('stripe'); if ($paymentGateway->exists()) { \Stripe\Stripe::setApiKey($paymentGateway->getFieldValue('apiKey')); $subscriptions = new Subscription(); $allSubscriptions = $subscriptions->where('status', Subscription::STATUS_ACTIVE)->get(); /* @var Subscription $_subscription */ foreach ($allSubscriptions as $_subscription) { $end = DateTime::createFromFormat('Y-m-d', $_subscription->end_date); if ($end->getTimestamp() > strtotime('now')) { $paymentTransaction = $_subscription->payment_transaction->get(); if ($paymentTransaction->system == 'stripe') { $user = new User($_subscription->user_id); try { $customer = \Stripe\Customer::retrieve($user->stripe_id); $subscription = $customer->subscriptions->retrieve($paymentTransaction->payment_id); } catch (Exception $e) { log_message('CRON_ERROR', __FUNCTION__ . ' > ' . $e->getMessage()); } if (!isset($subscription) || $subscription->status != 'active') { $_subscription->deactivate(); $_subscription->save(); } } } } log_message('CRON_SUCCESS', __FUNCTION__); } }
/** * @param \Enlight_Controller_ActionEventArgs $args */ public function onPostDispatchCheckout($args) { $action = $args->getSubject(); $request = $action->Request(); $view = $action->View(); $apiKey = $this->bootstrap->Config()->get('stripeSecretKey'); \Stripe\Stripe::setApiKey($apiKey); $token = $request->getPost('stripeToken'); if (!empty($token)) { try { $this->onStripeToken($request); } catch (\Stripe\Error\Card $e) { $eJson = $e->getJsonBody(); $error = $eJson['error']; $view->assign('sErrorMessages', [$error['message']]); if ($request->getControllerName() == 'checkout') { $action->forward('shippingPayment'); } else { $action->forward('payment'); } $request->setPost('stripeToken', null); $action->Response()->clearHeader('Location')->setHttpResponseCode(200); return; } } if (!empty($view->sPayments) && !empty($view->sUserData['additional']['user']['viisonStripeCustomerId'])) { $customerId = $view->sUserData['additional']['user']['viisonStripeCustomerId']; $customer = \Stripe\Customer::retrieve($customerId); $view->stripeSources = $this->convertCards($customer['sources']['data']); } }
/** * Check stripe data. * * @access public * @return void */ public function run() { try { $paymentGateway = Payment_gateways::findOneActiveBySlug('stripe'); if ($paymentGateway->exists()) { \Stripe\Stripe::setApiKey($paymentGateway->getFieldValue('apiKey')); $subscriptions = new Subscription(); $allSubscriptions = $subscriptions->get(); /* @var Subscription $_subscription */ foreach ($allSubscriptions as $_subscription) { if ($_subscription->end_date <= strtotime('now')) { $paymentTransaction = $_subscription->payment_transaction->get(); if ($paymentTransaction->system == 'stripe') { $user = new User($_subscription->user_id); $customer = \Stripe\Customer::retrieve($user->stripe_id); $subscription = $customer->subscriptions->retrieve($paymentTransaction->payment_id); if ($subscription->status == 'active') { $date = new DateTime(); $date->setTimestamp($subscription->current_period_end); $_subscription->end_date = $date->format('Y-m-d'); $_subscription->activate(); $_subscription->save(); } } } } log_message('CRON_SUCCESS', __FUNCTION__); } else { log_message('CRON_ERROR', __FUNCTION__ . ' > ' . 'No Stripe Api key.'); } } catch (Exception $e) { log_message('CRON_ERROR', __FUNCTION__ . ' > ' . $e->getMessage()); } }
function __construct() { \Stripe\Stripe::setApiKey(EcommercePlugin::secretKey()); $order_items = array(); $user = getLoggedInUser(); $stripe_cust = $user->stripe_cust; $cart = Cache::get("cart", "session"); if (!$stripe_cust) { try { $cu = \Stripe\Customer::create(array("description" => $user->email, "source" => getInput("stripeToken"))); } catch (Exception $e) { new SystemMessage("There has been an error. Please contact us."); forward("home"); } $user->stripe_cust = $cu->id; $user->save(); } else { $cu = \Stripe\Customer::retrieve($stripe_cust); try { $cu->source = getInput("stripeToken"); } catch (Exception $e) { new SystemMessage("There has been an error. Please contact us."); forward("home"); } $cu->save(); } foreach ($cart as $guid => $details) { $product = getEntity($guid); if ($product->interval == "one_time") { $order_item = array("type" => "sku", "parent" => $product->stripe_sku, "description" => $product->description . $details); $order_items[] = $order_item; } else { try { $cu->subscriptions->create(array("plan" => $guid)); } catch (Exception $e) { new SystemMessage("There has been an error. Please contact us."); forward("home"); } } } if (!empty($order_items)) { try { $order = \Stripe\Order::create(array("items" => $order_items, "currency" => "usd", "customer" => $cu->id)); $order->pay(array("customer" => $cu->id, "email" => $user->email)); } catch (Exception $e) { new SystemMessage("There has been an error. Please contact us."); forward("home"); } } $invoice = new Invoice(); $invoice->items = $cart; $invoice->status = "paid"; $invoice->owner_guid = getLoggedInUserGuid(); $invoice->stripe_order = $order->id; $invoice->save(); Cache::delete("cart", "session"); new SystemMessage("Your purchase is complete."); forward("billing"); }
public function testInvalidObject() { authorizeFromEnv(); try { Customer::retrieve('invalid'); } catch (InvalidRequestError $e) { $this->assertEqual(404, $e->getHttpStatus()); } }
/** * Display the specified resource. * * @param int $id * @return Response */ public function show($customerID) { Stripe::setApiKey($this->stripeConfig['testSecretKey']); $customerRetrieve = StripeCustomer::retrieve($customerID); /*echo '<pre>'; print_r($customerRetrieve); echo '</pre>';*/ return view('customer.show', compact('customerRetrieve')); }
public function deleteCreditCard($email, $index) { $cstmrAssocId = $this->getAssocCustomerId($email); $customer = \Stripe\Customer::retrieve($cstmrAssocId); $list = $this->getCreditCards($email); $card_id = $list[$index]["id"]; $customer->sources->retrieve($card_id)->delete(); return $this->getCreditCards($email); }
function cancel_suscription($customer_id, $suscription_id) { try { $customer = \Stripe\Customer::retrieve($customer_id); $subscription = $customer->subscriptions->retrieve($suscription_id); $subscription->cancel(); } catch (Exception $e) { http_response_code(404); return $e->getJsonBody(); } }
function __construct() { gateKeeper(); $user = getLoggedInUser(); $subscription = pageArray(2); if ($subscription && $user->stripe_cust) { \Stripe\Stripe::setApiKey(EcommercePlugin::secretKey()); $cu = \Stripe\Customer::retrieve($user->stripe_cust); $cu->subscriptions->retrieve($subscription)->cancel(); new SystemMessage("Your subscription has been canceled."); } forward(); }
public static function deleteCard($id) { self::init(); // Return if no stripe token. if (!Auth::user()->stripe_key) { return true; } // Delete the card. $customer = \Stripe\Customer::retrieve(Auth::user()->stripe_key); $customer->sources->retrieve($id)->delete(); // Return true; return true; }
public static function boot() { parent::boot(); User::deleting(function ($user) { if (App::environment('local')) { Stripe::setApiKey(Config::get('stripe.development.secret')); } else { Stripe::setApiKey(Config::get('stripe.production.secret')); } $cu = \Stripe\Customer::retrieve($user->stripe_customer_id); $cu->delete(); return true; }); }
public function cancel() { $this->requireIdentity(); $user = $this->getIdentity(); if ($user->{'stripe.customer.id'}) { $customer = \Stripe\Customer::retrieve($user->{'stripe.customer.id'}); $subscription = $customer->subscriptions->retrieve($this->app->get('PARAMS.id')); $subscription->cancel(); \Dsc\System::instance()->addMessage("Plan Deleted", 'success'); } else { \Dsc\System::instance()->addMessage("Somthing went wrong", 'error'); } $this->app->reroute('/account/subscriptions'); }
/** * try to pay * * @param $transactionId * @param null $planPeriodId */ public function pay($transactionId, $planPeriodId = null) { $transaction = new Payment_transaction($transactionId); $this->throwModelNotFoundException($transaction); if (!$transaction->isPending()) { $this->throwAccessDeniedException('The transaction cannot be processed!'); } $paymentGateway = Payment_gateways::findOneActiveBySlug($transaction->system); $this->throwModelNotFoundException($paymentGateway); $parameters = $this->generateParameters($transaction); if ($paymentGateway->isSlug('stripe')) { if ($this->isRequestMethod('post') && ($stripeToken = $this->getRequest()->request->get('stripeToken', null))) { $parameters['token'] = $stripeToken; \Stripe\Stripe::setApiKey($paymentGateway->getFieldValue('apiKey')); $user = $this->getUser(); if (!$user->stripe_id) { $customer = \Stripe\Customer::create(array('email' => $user->email)); $user->stripe_id = $customer->id; $user->save(); } else { $customer = \Stripe\Customer::retrieve($user->stripe_id); } try { $response = $customer->subscriptions->create(array('plan' => $planPeriodId, 'source' => $parameters['token'])); } catch (Exception $e) { $this->addFlash($e->getMessage(), 'error'); $this->template->set('publishableApiKey', $paymentGateway->getFieldValue('publishableApiKey')); $this->template->set('transaction', $transaction); $this->template->current_view = 'payment/gateway/stripePopup'; $this->template->render('default'); return; } $this->get('core.payment.transactions.manager')->completeStripe($transaction, $response); $redirectResponse = RedirectResponse::create(site_url('payment/success')); $this->sendResponse($transaction, $redirectResponse); } else { $this->template->set('publishableApiKey', $paymentGateway->getFieldValue('publishableApiKey')); $this->template->set('transaction', $transaction); $this->template->current_view = 'payment/gateway/stripePopup'; $this->template->render('default'); return; } } $paymentProvider = $this->get('core.payment.system.provider'); $paymentProvider->setGateway($paymentGateway); $response = $paymentProvider->purchase($parameters); $this->processResponse($response, $transaction); }
public function subscriptionsAction(Request $request) { try { $customer_id = $request->query->get('customer_id'); $limit = $request->query->get('limit') ? $request->query->get('limit') : 10; $starting_after = $request->query->get('starting_after') ? $request->query->get('starting_after') : -1; $ending_before = $request->query->get('ending_before') ? $request->query->get('ending_before') : -1; $request_array = array("limit" => $limit); if ($starting_after != -1) { $request_array["starting_after"] = $starting_after; } if ($ending_before != -1) { $request_array["ending_before"] = $ending_before; } \Stripe\Stripe::setApiKey("Input User API KEY HERE"); $response = \Stripe\Customer::retrieve($customer_id)->subscriptions->all($request_array); $subscriptions = array(); $i = 0; foreach ($response['data'] as $subscription) { $subscription_item = array("id" => $subscription['id'], "created" => $subscription['plan']['created'], "status" => $subscription['status']); $subscriptions[$i] = $subscription_item; $i++; } $subscriptions = json_encode($subscriptions); } catch (\Stripe\Error\ApiConnection $e) { // Network communication with Stripe failed $error = array("error" => "Connection Error"); return new Response(json_encode($error), 422); } catch (\Stripe\Error\Authentication $e) { // Authentication with Stripe's API failed $error = array("error" => "Invalid API Key"); return new Response(json_encode($error), 422); } catch (\Stripe\Error\InvalidRequest $e) { // Invalid parameters were supplied to Stripe's API $error = array("error" => "Invalid Request"); return new Response(json_encode($error), 422); } catch (\Stripe\Error\Base $e) { // Display a very generic error to the user, and maybe send $error = array("error" => $e); return new Response(json_encode($error), 422); } catch (Exception $e) { // Something else happened, completely unrelated to Stripe $error = array("error" => $e); return new Response(json_encode($error), 422); } return new Response($subscriptions, 200); }
/** * 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); } }
/** * Gets info for a customer. * * @return array|null */ public function info() { if (!$this->id) { return null; } if (!$this->stripe_customer) { $this->stripe_customer = Stripe_Customer::retrieve($this->id); } if (!$this->stripe_customer) { return null; } $discounts = array(); if ($this->stripe_customer->discount) { $discounts[] = array('coupon' => $this->stripe_customer->discount->coupon->id, 'amount_off' => $this->stripe_customer->discount->coupon->amount_off, 'percent_off' => $this->stripe_customer->discount->coupon->percent_off, 'started_at' => date('Y-m-d H:i:s', $this->stripe_customer->discount->start), 'ends_at' => $this->stripe_customer->discount->end ? date('Y-m-d H:i:s', $this->stripe_customer->discount->end) : null); } return array('id' => $this->id, 'description' => $this->stripe_customer->description, 'email' => $this->stripe_customer->email, 'created_at' => date('Y-m-d H:i:s', $this->stripe_customer->created), 'discounts' => $discounts); }
public function cancel_subscription() { $subscription = $this->c_user->getLastSubscription(); if ($this->c_user->stripe_id) { $paymentGateway = Payment_gateways::findOneActiveBySlug('stripe'); if ($paymentGateway->exists()) { \Stripe\Stripe::setApiKey($paymentGateway->getFieldValue('apiKey')); $customer = \Stripe\Customer::retrieve($this->c_user->stripe_id); $paymentTransaction = $subscription->payment_transaction->get(); if ($paymentTransaction->exists()) { $customer->subscriptions->retrieve($paymentTransaction->payment_id)->cancel(); } } } $subscription->is_stripe_active = false; $subscription->save(); redirect('settings/subscriptions'); }
public function __construct() { parent::__construct(); $this->prependSiteTitle(lang('Invoices')); Stripe::setApiKey(env('STRIPE_KEY')); if ($this->activeOrganisation->stripe_identifier_id) { try { $this->customer = Customer::retrieve($this->activeOrganisation->stripe_identifier_id); } catch (\Exception $e) { } } if ($this->isPostBack()) { $this->post->credit_number->addValidation([new ValidateInputInteger()]); $this->post->exp_month->addValidation([new ValidateInputInteger(), new ValidateInputMaxLength(2)]); $this->post->exp_year->addValidation([new ValidateInputInteger(), new ValidateInputMaxLength(4)]); $this->post->security_code->addValidation([new ValidateInputInteger(), new ValidateInputMaxLength(4)]); if (!$this->hasErrors()) { try { if ($this->customer && !$this->customer['deleted']) { $this->customer->card = ['number' => $this->input('credit_number'), 'exp_month' => $this->input('exp_month'), 'exp_year' => $this->input('exp_year'), 'cvc' => $this->input('security_code')]; $this->customer->description = $this->activeOrganisation->name; $this->customer->save(); } else { $this->customer = Customer::create(['card' => ['number' => $this->input('credit_number'), 'exp_month' => $this->input('exp_month'), 'exp_year' => $this->input('exp_year'), 'cvc' => $this->input('security_code')], 'description' => $this->activeOrganisation->name]); } } catch (\Exception $e) { $this->setError($e->getMessage()); response()->refresh(); } $this->setMessage(lang('Credit card saved'), 'success'); $this->activeOrganisation->stripe_identifier_id = $this->customer['id']; $this->activeOrganisation->update(); response()->refresh(); } } }
/** * [getCustomer Retrieves the details of an existing customer. You need only supply the unique customer * identifier that was returned upon customer creation.] * * @param $customer_id [ID stripe of customer] * * @return [A customer object] */ public function getCustomer($customer_id) { return \Stripe\Customer::retrieve($customer_id); }
/** * Cancel a member's payment profile * * @access public * @since 2.1 */ function rcp_cancel_member_payment_profile( $member_id = 0 ) { global $rcp_options; $success = false; $member = new RCP_Member( $member_id ); if( ! rcp_can_member_cancel( $member_id ) ) { return $success; } if( rcp_is_stripe_subscriber( $member_id ) ) { 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 { $cu = \Stripe\Customer::retrieve( $member->get_payment_profile_id() ); $cu->cancelSubscription( array( 'at_period_end' => false ) ); $success = true; } 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>" . __( 'Error code:', '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>" . __( 'Error code:', '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>" . __( 'Error code:', '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>" . __( 'Error code:', '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 = "<h4>" . __( 'An error occurred', 'rcp' ) . "</h4>"; $error .= print_r( $e, true ); wp_die( $error, __( 'Error', 'rcp' ), array( 'response' => 401 ) ); } } elseif( rcp_is_paypal_subscriber( $member_id ) ) { if( rcp_has_paypal_api_access() && $member->get_payment_profile_id() ) { // Set PayPal API key credentials. $api_username = isset( $rcp_options['sandbox'] ) ? 'test_paypal_api_username' : 'live_paypal_api_username'; $api_password = isset( $rcp_options['sandbox'] ) ? 'test_paypal_api_password' : 'live_paypal_api_password'; $api_signature = isset( $rcp_options['sandbox'] ) ? 'test_paypal_api_signature' : 'live_paypal_api_signature'; $api_endpoint = isset( $rcp_options['sandbox'] ) ? 'https://api-3t.sandbox.paypal.com/nvp' : 'https://api-3t.paypal.com/nvp'; $args = array( 'USER' => $rcp_options[ $api_username ], 'PWD' => $rcp_options[ $api_password ], 'SIGNATURE' => $rcp_options[ $api_signature ], 'VERSION' => '76.0', 'METHOD' => 'ManageRecurringPaymentsProfileStatus', 'PROFILEID' => $member->get_payment_profile_id(), 'ACTION' => 'Cancel' ); $error_msg = ''; $request = wp_remote_post( $api_endpoint, array( 'body' => $args, 'timeout' => 30 ) ); if ( is_wp_error( $request ) ) { $success = false; $error_msg = $request->get_error_message(); } else { $body = wp_remote_retrieve_body( $request ); if( is_string( $body ) ) { wp_parse_str( $body, $body ); } if( empty( $request['response'] ) ) { $success = false; } if( empty( $request['response']['code'] ) || 200 !== (int) $request['response']['code'] ) { $success = false; } if( empty( $request['response']['message'] ) || 'OK' !== $request['response']['message'] ) { $success = false; } if( isset( $body['ACK'] ) && 'success' === strtolower( $body['ACK'] ) ) { $success = true; } else { $success = false; if( isset( $body['L_LONGMESSAGE0'] ) ) { $error_msg = $body['L_LONGMESSAGE0']; } } } if( ! $success ) { wp_die( sprintf( __( 'There was a problem cancelling the subscription, please contact customer support. Error: %s', 'rcp' ), $error_msg ), array( 'response' => 400 ) ); } } } if( $success ) { $member->cancel(); } return $success; }
/** * Process an update card form request * * @access private * @since 2.1 */ function rcp_stripe_update_billing_card($member_id = 0, $member_obj) { if (empty($member_id)) { return; } if (!is_a($member_obj, 'RCP_Member')) { return; } if (!rcp_is_stripe_subscriber($member_id)) { return; } if (empty($_POST['stripeToken'])) { wp_die(__('Missing Stripe token', 'rcp'), __('Error', 'rcp'), array('response' => 400)); } $customer_id = $member_obj->get_payment_profile_id(); global $rcp_options; if (isset($rcp_options['sandbox'])) { $secret_key = trim($rcp_options['stripe_test_secret']); } else { $secret_key = trim($rcp_options['stripe_live_secret']); } if (!class_exists('Stripe\\Stripe')) { require_once RCP_PLUGIN_DIR . 'includes/libraries/stripe/init.php'; } \Stripe\Stripe::setApiKey($secret_key); try { $customer = \Stripe\Customer::retrieve($customer_id); $customer->card = $_POST['stripeToken']; // obtained with stripe.js $customer->save(); } catch (\Stripe\Error\Card $e) { $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')); exit; } 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')); } wp_redirect(add_query_arg('card', 'updated')); exit; }
/** * @param CustomerUser $user * @return Customer * @throws BillingNotFoundException */ public function getUserDetails(CustomerUser $user) { $sourceId = $user->getSourceId(); if (!$sourceId) { return null; } $cu = Customer::retrieve($sourceId); return $cu; }
/** * Get the billing address associated to the authenticated user. * * Used to populate the update billing address form on settings -> subscription tab. * * @return \Illuminate\Http\Response */ public function getBillingAddressForUser() { Stripe::setApiKey(config('services.stripe.secret')); try { $customer = StripeCustomer::retrieve(Auth::user()->stripe_id); $card = $customer->sources->retrieve($customer->default_source); return response()->json(["company" => isset($customer->metadata->company) ? $customer->metadata->company : "", "name" => $card->name, "street" => $card->address_line1, "zip" => $card->address_zip, "city" => $card->address_city, "country" => $card->address_country]); } catch (Exception $e) { abort(404); } }
public static function getAllCards($user) { $id = $user->get("stripeId"); $cards = \Stripe\Customer::retrieve($id)->sources->all(array('object' => 'card')); $cards_list = []; foreach ($cards->data as $c) { $data = ["num" => $c->last4, "card_id" => $c->id, "brand" => $c->brand]; array_push($cards_list, $data); } return $cards_list; }