/** * Create and send the request * * @param array $options array of options to be send in POST request * @return gateway_response response object * */ public function send($options, $type = '') { $result = ''; try { if ($type == 'subscription') { $result = Stripe_Customer::create($options); } elseif ($type == 'plan') { $result = Stripe_Plan::create($options); } elseif ($type == 'retrieve') { $result = Stripe_Plan::retrieve($options); } elseif ($type == 'customer') { $result = Stripe_Customer::create($options); } elseif ($type == 'invoice') { $result = Stripe_InvoiceItem::create($options); // Stripe_Customer::invoiceItems($options); } elseif ($type == 'cancel') { $cu = Stripe_Customer::retrieve($options['customer']); $result = $cu->cancelSubscription(); } else { $result = Stripe_Charge::create($options); } } catch (Exception $ex) { $result = $ex; } $response = new stripe_response($result); return $response; }
function run() { //Get the data from stripe $data_raw = file_get_contents("php://input"); $data = json_decode($data_raw); if (!$data) { CRM_Core_Error::Fatal("Stripe Callback: cannot json_decode data, exiting. <br /> {$data}"); } $test_mode = !$data->livemode; $stripe_key = CRM_Core_DAO::singleValueQuery("SELECT user_name FROM civicrm_payment_processor WHERE payment_processor_type = 'Stripe' AND is_test = '{$test_mode}'"); require_once "packages/stripe-php/lib/Stripe.php"; Stripe::setApiKey($stripe_key); //Retrieve Event from Stripe using ID even though we already have the values now. //This is for extra security precautions mentioned here: https://stripe.com/docs/webhooks $stripe_event_data = Stripe_Event::retrieve($data->id); $customer_id = $stripe_event_data->data->object->customer; switch ($stripe_event_data->type) { //Successful recurring payment case 'invoice.payment_succeeded': //Get the Stripe charge object try { $charge = Stripe_Charge::retrieve($stripe_event_data->data->object->charge); } catch (Exception $e) { CRM_Core_Error::Fatal("Failed to retrieve Stripe charge. Message: " . $e->getMessage()); break; } //Find the recurring contribution in CiviCRM by mapping it from Stripe $rel_info_query = CRM_Core_DAO::executeQuery("SELECT invoice_id, end_time FROM civicrm_stripe_subscriptions WHERE customer_id = '{$customer_id}'"); if (!empty($rel_info_query)) { $rel_info_query->fetch(); $invoice_id = $rel_info_query->invoice_id; $end_time = $rel_info_query->end_time; } else { CRM_Core_Error::Fatal("Error relating this customer ({$customer_id}) to the one in civicrm_stripe_subscriptions"); } //Compare against now + 24hrs to prevent charging 1 extra day. $time_compare = time() + 86400; //Fetch Civi's info about this recurring object $recur_contrib_query = CRM_Core_DAO::executeQuery("SELECT id, contact_id, currency, contribution_status_id, is_test, contribution_type_id, payment_instrument_id, campaign_id FROM civicrm_contribution_recur WHERE invoice_id = '{$invoice_id}'"); if (!empty($recur_contrib_query)) { $recur_contrib_query->fetch(); } else { CRM_Core_Error::Fatal("ERROR: Stripe triggered a Webhook on an invoice not found in civicrm_contribution_recur: " . $stripe_event_data); } //Build some params $stripe_customer = Stripe_Customer::retrieve($customer_id); $recieve_date = date("Y-m-d H:i:s", $charge->created); $total_amount = $charge->amount / 100; $fee_amount = $charge->fee / 100; $net_amount = $total_amount - $fee_amount; $transaction_id = $charge->id; $new_invoice_id = $stripe_event_data->data->object->id; if (empty($recur_contrib_query->campaign_id)) { $recur_contrib_query->campaign_id = 'NULL'; } $first_contrib_check = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_contribution WHERE invoice_id = '{$invoice_id}' AND contribution_status_id = '2'"); if (!empty($first_contrib_check)) { CRM_Core_DAO::executeQuery("UPDATE civicrm_contribution SET contribution_status_id = '1' WHERE id = '{$first_contrib_check}'"); return; } //Create this instance of the contribution for accounting in CiviCRM CRM_Core_DAO::executeQuery("\n \tINSERT INTO civicrm_contribution (\n \tcontact_id, contribution_type_id, payment_instrument_id, receive_date, \n \ttotal_amount, fee_amount, net_amount, trxn_id, invoice_id, currency,\n \tcontribution_recur_id, is_test, contribution_status_id, campaign_id\n \t) VALUES (\n \t'{$recur_contrib_query->contact_id}', '{$recur_contrib_query->contribution_type_id}', '{$recur_contrib_query->payment_instrument_id}', '{$recieve_date}', \n \t'{$total_amount}', '{$fee_amount}', '{$net_amount}', '{$transaction_id}', '{$new_invoice_id}', '{$recur_contrib_query->currency}', \n \t'{$recur_contrib_query->id}', '{$recur_contrib_query->is_test}', '1', {$recur_contrib_query->campaign_id}\n \t)"); if ($time_compare > $end_time) { $end_date = date("Y-m-d H:i:s", $end_time); //Final payment. Recurring contribution complete $stripe_customer->cancelSubscription(); CRM_Core_DAO::executeQuery("DELETE FROM civicrm_stripe_subscriptions WHERE invoice_id = '{$invoice_id}'"); CRM_Core_DAO::executeQuery("UPDATE civicrm_contribution_recur SET end_date = '{$end_date}', contribution_status_id = '1' WHERE invoice_id = '{$invoice_id}'"); return; } //Successful charge & more to come so set recurring contribution status to In Progress if ($recur_contrib_query->contribution_status_id != 5) { CRM_Core_DAO::executeQuery("UPDATE civicrm_contribution_recur SET contribution_status_id = 5 WHERE invoice_id = '{$invoice_id}'"); return; } break; //Failed recurring payment //Failed recurring payment case 'invoice.payment_failed': //Get the Stripe charge object try { $charge = Stripe_Charge::retrieve($stripe_event_data->data->object->charge); } catch (Exception $e) { CRM_Core_Error::Fatal("Failed to retrieve Stripe charge. Message: " . $e->getMessage()); break; } //Find the recurring contribution in CiviCRM by mapping it from Stripe $invoice_id = CRM_Core_DAO::singleValueQuery("SELECT invoice_id FROM civicrm_stripe_subscriptions WHERE customer_id = '{$customer_id}'"); if (empty($invoice_id)) { CRM_Core_Error::Fatal("Error relating this customer ({$customer_id}) to the one in civicrm_stripe_subscriptions"); } //Fetch Civi's info about this recurring object $recur_contrib_query = CRM_Core_DAO::executeQuery("SELECT id, contact_id, currency, contribution_status_id, is_test, contribution_type_id, payment_instrument_id, campaign_id FROM civicrm_contribution_recur WHERE invoice_id = '{$invoice_id}'"); if (!empty($recur_contrib_query)) { $recur_contrib_query->fetch(); } else { CRM_Core_Error::Fatal("ERROR: Stripe triggered a Webhook on an invoice not found in civicrm_contribution_recur: " . $stripe_event_data); } //Build some params $recieve_date = date("Y-m-d H:i:s", $charge->created); $total_amount = $charge->amount / 100; $fee_amount = $charge->fee / 100; $net_amount = $total_amount - $fee_amount; $transaction_id = $charge->id; if (empty($recur_contrib_query->campaign_id)) { $recur_contrib_query->campaign_id = 'NULL'; } //Create this instance of the contribution for accounting in CiviCRM CRM_Core_DAO::executeQuery("\n \tINSERT INTO civicrm_contribution (\n \tcontact_id, contribution_type_id, payment_instrument_id, receive_date, \n \ttotal_amount, fee_amount, net_amount, trxn_id, invoice_id, currency,\n \tcontribution_recur_id, is_test, contribution_status_id, campaign_id\n \t) VALUES (\n \t'{$recur_contrib_query->contact_id}', '{$recur_contrib_query->contribution_type_id}', '{$recur_contrib_query->payment_instrument_id}', '{$recieve_date}', \n \t'{$total_amount}', '{$fee_amount}', '{$net_amount}', '{$transaction_id}', '{$invoice_id}', '{$recur_contrib_query->currency}', \n \t'{$recur_contrib_query->id}', '{$recur_contrib_query->is_test}', '4', {$recur_contrib_query->campaign_id}\n \t)"); //Failed charge. Set to status to: Failed if ($recur_contrib_query->contribution_status_id != 4) { CRM_Core_DAO::executeQuery("UPDATE civicrm_contribution_recur SET contribution_status_id = 4 WHERE invoice_id = '{$invoice_id}'"); return; } else { //This has failed more than once. Now what? } break; //One-time donation and per invoice payment //One-time donation and per invoice payment case 'charge.succeeded': //Not implemented break; } parent::run(); }
function email_transfer_failed($transfer) { $customer = Stripe_Customer::retrieve($transfer->customer); $subject = 'Your transfer was failed'; $headers = 'From: "Brandbits Support" <*****@*****.**>'; mail($customer->email, $subject, message_body(), $headers); }
public static function updateSubscription($service, $customerId, $plan) { \Stripe::setApiKey($service['stripe']['secret_key']); $customer = \Stripe_Customer::retrieve($customerId); $customer->updateSubscription(array("plan" => $plan, "prorate" => true)); return ['id' => $customer->subscription->plan->id, 'name' => $customer->subscription->plan->name]; }
/** * Function to update the customerinformation with customer id * Cases when card expired or new card. * @param Tokne id users strip token id * @param user id * @param amount to charge * @param description */ public function UpdateExistingCustomer($customerId, $token, $name, $amount, $description = "") { $this->setAPIKey(); $cu = Stripe_Customer::retrieve($customerId); $rr = json_decode($cu, true); //echo'<pre>';print_r($rr);echo'</pre>';die(); $r = $rr['error']['message']; $error_code = $rr['error']['code']; $error_type = $rr['error']['type']; //echo $error_code.'------------'.$error_type.'<br />'; if (empty($error_type) && empty($error_code)) { $cu->card = $token; if (!empty($description)) { $cu->description = $description; } $cu->save(); $result = Stripe_Charge::create(array("amount" => "{$amount}", "currency" => "usd", "customer" => "{$customerId}")); if ($result['paid'] === true) { $result_array = array("success" => "1"); return $result_array; } else { return $result; } } else { $result_array = array("update" => "1"); return $result_array; } }
public function testUpdateDescriptionNull() { $customer = self::createTestCustomer(array('description' => 'foo bar')); $customer->description = NULL; $customer->save(); $updatedCustomer = Stripe_Customer::retrieve($customer->id); $this->assertEqual(NULL, $updatedCustomer->description); }
public function testInvalidObject() { self::authorizeFromEnv(); try { Stripe_Customer::retrieve('invalid'); } catch (Stripe_InvalidRequestError $e) { $this->assertEqual(404, $e->getHttpStatus()); } }
public function testSave() { $customer = self::createTestCustomer(); $customer->email = '*****@*****.**'; $customer->save(); $this->assertEqual($customer->email, '*****@*****.**'); $customer2 = Stripe_Customer::retrieve($customer->id); $this->assertEqual($customer->email, $customer2->email); }
/** * Get a customer * @param string $customer_id * @return Stripe_Customer|false */ public function getCustomer($customer_id = '') { try { return Stripe_Customer::retrieve($customer_id); } catch (Exception $ex) { $this->log($ex); return false; } }
public function testSave() { authorizeFromEnv(); $c = Stripe_Customer::create(); $c->email = '*****@*****.**'; $c->bogus = 'bogus'; $c->save(); $this->assertEqual($c->email, '*****@*****.**'); $this->assertNull($c['bogus']); $c2 = Stripe_Customer::retrieve($c->id); $this->assertEqual($c->email, $c2->email); }
/** * Get a single record by creating a WHERE clause with * a value for your primary key * * @param string $primary_value The value of your primary key * @return object */ public function get($customer_id) { try { $ch = Stripe_Customer::retrieve($customer_id); return $ch; } catch (Exception $e) { $this->error = TRUE; $this->message = $e->getMessage(); $this->code = $e->getCode(); return FALSE; } }
public function testUpdateAllMetadata() { $customer = self::createTestCustomer(); $customer->metadata['shoe size'] = '7'; $customer->metadata['shirt size'] = 'XS'; $customer->save(); $customer->metadata = array('shirt size' => 'XL'); $customer->save(); $updatedCustomer = Stripe_Customer::retrieve($customer->id); $this->assertEqual('XL', $updatedCustomer->metadata['shirt size']); $this->assertFalse(isset($updatedCustomer->metadata['shoe size'])); }
public function testDeletion() { authorizeFromEnv(); $id = 'test-coupon-' . self::randomString(); $coupon = Stripe_Coupon::create(array('percent_off' => 25, 'duration' => 'repeating', 'duration_in_months' => 5, 'id' => $id)); $customer = self::createTestCustomer(array('coupon' => $id)); $this->assertTrue(isset($customer->discount)); $this->assertTrue(isset($customer->discount->coupon)); $this->assertEqual($id, $customer->discount->coupon->id); $customer->deleteDiscount(); $this->assertFalse(isset($customer->discount)); $customer = Stripe_Customer::retrieve($customer->id); $this->assertFalse(isset($customer->discount)); }
public function return_credit_cards() { try { $this->sktest_setapikey(); $stripe_id = get_user_meta(get_current_user_id(), 'stripe_customer_id', true); $customerret = Stripe_Customer::retrieve($stripe_id); } catch (Stripe_Error $e) { $body = $e->getJsonBody(); $err = $body['error']; print $error[‘message’]; } $idtest = $customerret->id; echo $idtest; }
function wpestate_cancel_stripe() { global $current_user; require_once get_template_directory() . '/libs/stripe/lib/Stripe.php'; get_currentuserinfo(); $userID = $current_user->ID; $stripe_customer_id = get_user_meta($userID, 'stripe', true); $subscription_id = get_user_meta($userID, 'stripe_subscription_id', true); $stripe_secret_key = esc_html(get_option('wp_estate_stripe_secret_key', '')); $stripe_publishable_key = esc_html(get_option('wp_estate_stripe_publishable_key', '')); $stripe = array("secret_key" => $stripe_secret_key, "publishable_key" => $stripe_publishable_key); Stripe::setApiKey($stripe['secret_key']); $processor_link = wpestate_get_stripe_link(); $submission_curency_status = esc_html(get_option('wp_estate_submission_curency', '')); $cu = Stripe_Customer::retrieve($stripe_customer_id); $cu->subscriptions->retrieve($subscription_id)->cancel(array("at_period_end" => true)); update_user_meta($current_user->ID, 'stripe_subscription_id', ''); }
/** * @method POST */ function post() { // parse request parse_str($this->request->data, $request); $plan = $request['plan']; // get an authuser $authUser = new AuthUser(); if (isset($authUser->UserUniqId)) { // check if authorized try { $site = Site::GetBySiteUniqId($authUser->SiteUniqId); Stripe::setApiKey(STRIPE_API_KEY); $customer = Stripe_Customer::retrieve($site['CustomerId']); // retrieve default subscription if (isset($customer->subscriptions->data[0])) { $subscription = $customer->subscriptions->data[0]; // updates the subscription if ($subscription != NULL) { $subscription->plan = $plan; $subscription->save(); } // update the session AuthUser::UpdateSubscription(); } // return a json response return new Tonic\Response(Tonic\Response::OK); } catch (Exception $e) { $response = new Tonic\Response(Tonic\Response::BADREQUEST); $response->body = $e->getMessage(); return $response; } } else { return new Tonic\Response(Tonic\Response::UNAUTHORIZED); } }
<?php /** * Created by PhpStorm. * User: debasis_kar * Date: 11/12/2015 * Time: 1:03 PM */ try { require_once 'Stripe/lib/Stripe.php'; Stripe::setApiKey("sk_test_jttNGqAeuCpVoftWPWenb6OO"); $customer = Stripe_Customer::retrieve(CUSTOMER_ID); $subscription = $customer->subscriptions->retrieve(SUBSCRIPTION_ID); $subscription->plan = PLAN_ID; $subscription->save(); } catch (Stripe_CardError $e) { }
function chargeCustomer() { $resp['code'] = ''; $resp['message'] = ''; try { $cu = Stripe_Customer::retrieve($this->stripeId); $card = $cu->cards->data[0]->id; Stripe_Charge::create(array("amount" => $this->amount, "currency" => "usd", "customer" => $this->stripeId, "description" => "Charge for C3HealthLink.com")); $resp['code'] = 'OK'; $resp['message'] = ''; return $resp; } catch (Stripe_CardError $e) { $body = $e->getJsonBody(); $resp = $body['error']; return $resp; } catch (Stripe_InvalidRequestError $e) { // Invalid parameters were supplied to Stripe's API $body = $e->getJsonBody(); $resp = $body['error']; return $resp; } catch (Stripe_AuthenticationError $e) { // Authentication with Stripe's API failed // (maybe you changed API keys recently) $body = $e->getJsonBody(); $resp = $body['error']; return $resp; } catch (Stripe_ApiConnectionError $e) { // Network communication with Stripe failed $body = $e->getJsonBody(); $resp = $body['error']; return $resp; } catch (Stripe_Error $e) { // Display a very generic error to the user, and maybe send // yourself an email $body = $e->getJsonBody(); $resp = $body['error']; return $resp; } catch (Exception $e) { // Something else happened, completely unrelated to Stripe $body = $e->getJsonBody(); $resp = $body['error']; return $resp; } // if nothing is returned above, return null. should never happen. return null; $resp['code'] = 'OK'; logit(INFO, "Charge Customer| charge: {$this->amount}, percent_off: {$this->percent_off}, stripe id: {$this->stripeId}, urec: {$this->uRec}"); return $resp; }
function getCustomer(&$order, $force = false) { global $current_user; //already have it? if(!empty($this->customer) && !$force) return $this->customer; //transaction id? if(!empty($order->subscription_transaction_id)) $customer_id = $order->subscription_transaction_id; else { //try based on user id if(!empty($order->user_id)) $user_id = $order->user_id; //if no id passed, check the current user if(empty($user_id) && !empty($current_user->ID)) $user_id = $current_user->ID; //check for a stripe customer id if(!empty($user_id)) { $customer_id = get_user_meta($user_id, "pmpro_stripe_customerid", true); } } //check for an existing stripe customer if(!empty($customer_id)) { try { $this->customer = Stripe_Customer::retrieve($customer_id); //update the customer description and card if(!empty($order->stripeToken)) { $this->customer->description = trim($order->FirstName . " " . $order->LastName) . " (" . $order->Email . ")"; $this->customer->card = $order->stripeToken; $this->customer->save(); } return $this->customer; } catch (Exception $e) { //assume no customer found } } //no customer id, create one if(!empty($order->stripeToken)) { try { $this->customer = Stripe_Customer::create(array( "description" => trim($order->FirstName . " " . $order->LastName) . " (" . $order->Email . ")", "card" => $order->stripeToken )); } catch (Exception $e) { $order->error = "Error creating customer record with Stripe: " . $e->getMessage(); $order->shorterror = $order->error; return false; } update_user_meta($user_id, "pmpro_stripe_customerid", $this->customer->id); return $this->customer; } return false; }
/** * Get a Stripe customer object. * * If $this->customer is set, it returns it. * It first checks if the order has a subscription_transaction_id. If so, that's the customer id. * If not, it checks for a user_id on the order and searches for a customer id in the user meta. * If a customer id is found, it checks for a customer through the Stripe API. * If a customer is found and there is a stripeToken on the order passed, it will update the customer. * If no customer is found and there is a stripeToken on the order passed, it will create a customer. * * @since 1.4 * @return Stripe_Customer|false */ function getCustomer(&$order = false, $force = false) { global $current_user; //already have it? if (!empty($this->customer) && !$force) { return $this->customer; } //figure out user_id and user if (!empty($order->user_id)) { $user_id = $order->user_id; } //if no id passed, check the current user if (empty($user_id) && !empty($current_user->ID)) { $user_id = $current_user->ID; } if (!empty($user_id)) { $user = get_userdata($user_id); } else { $user = NULL; } //transaction id? if (!empty($order->subscription_transaction_id) && strpos($order->subscription_transaction_id, "cus_") !== false) { $customer_id = $order->subscription_transaction_id; } else { //try based on user id if (!empty($user_id)) { $customer_id = get_user_meta($user_id, "pmpro_stripe_customerid", true); } } //get name and email values from order in case we update $name = trim($order->FirstName . " " . $order->LastName); if (empty($name) && !empty($user->ID)) { $name = trim($user->first_name . " " . $user->last_name); //still empty? if (empty($name)) { $name = $user->user_login; } } elseif (empty($name)) { $name = "No Name"; } $email = $order->Email; if (empty($email) && !empty($user->ID)) { $email = $user->user_email; } elseif (empty($email)) { $email = "No Email"; } //check for an existing stripe customer if (!empty($customer_id)) { try { $this->customer = Stripe_Customer::retrieve($customer_id); //update the customer description and card if (!empty($order->stripeToken)) { $this->customer->description = $name . " (" . $email . ")"; $this->customer->email = $email; $this->customer->card = $order->stripeToken; $this->customer->save(); } return $this->customer; } catch (Exception $e) { //assume no customer found } } //no customer id, create one if (!empty($order->stripeToken)) { try { $this->customer = Stripe_Customer::create(array("description" => $name . " (" . $email . ")", "email" => $order->Email, "card" => $order->stripeToken)); } catch (Exception $e) { $order->error = __("Error creating customer record with Stripe:", "pmpro") . " " . $e->getMessage(); $order->shorterror = $order->error; return false; } if (!empty($user_id)) { //user logged in/etc update_user_meta($user_id, "pmpro_stripe_customerid", $this->customer->id); } else { //user not registered yet, queue it up global $pmpro_stripe_customer_id; $pmpro_stripe_customer_id = $this->customer->id; function pmpro_user_register_stripe_customerid($user_id) { global $pmpro_stripe_customer_id; update_user_meta($user_id, "pmpro_stripe_customerid", $pmpro_stripe_customer_id); } add_action("user_register", "pmpro_user_register_stripe_customerid"); } return apply_filters('pmpro_stripe_create_customer', $this->customer); } return false; }
public function update_card() { $user = $this->session->userdata('user'); $customer = Stripe_Customer::retrieve($user->stripe_customer_id); $card_id = $this->session->userdata('stripe_card_id'); $card = $customer->cards->retrieve($card_id); $card->name = $_POST['cardholder_name'] == "" ? NULL : $_POST['cardholder_name']; $card->exp_month = $_POST['exp_month']; $card->exp_year = $_POST['exp_year']; $card->address_city = $_POST['address_city'] == "" ? NULL : $_POST['address_city']; $card->address_country = $_POST['address_country'] == "" ? NULL : $_POST['address_country']; $card->address_state = $_POST['address_state'] == "" ? NULL : $_POST['address_state']; $card->address_line1 = $_POST['address_line1'] == "" ? NULL : $_POST['address_line1']; $card->address_line2 = $_POST['address_line2'] == "" ? NULL : $_POST['address_line2']; $card->address_zip = $_POST['address_zip'] == "" ? NULL : $_POST['address_zip']; if ($card->save()) { echo "Success"; } }
<?php require_once 'session_check.php'; require_once "../Stripe/Stripe.php"; Stripe::setApiKey("sk_test_6jbgLGl89PNJJJOjUg536nxZ"); if (isset($_GET['plan'])) { try { $customer = Stripe_Customer::retrieve($user->stripe_id); $subscription = $customer->subscriptions->retrieve($user->subscription_id); $subscription->plan = $_GET['plan']; $subscription->save(); } catch (Stripe_CardError $e) { $error = $e->message; } changePlan($_GET['plan'], $user->id); } header('location: admin.php');
public function getCardInformation(User $user) { $customer_id = $user->getProfile() ? $user->getProfile()->getCustomerId() : null; if ($customer_id) { $customer = \Stripe_Customer::retrieve($customer_id); $cards = $customer->sources->all(array("object" => "card")); if ($cards && $cards->data) { return $cards->data[0]->__toArray(); } } return null; }
/** * Process a payment * * @param string $token Stripe Transaction ID (token) */ public function processPayment($token) { /* If 1.4 and no backward, then leave */ if (!$this->backward) { return; } include dirname(__FILE__) . '/lib/Stripe.php'; Stripe::setApiKey(Configuration::get('STRIPE_MODE') ? Configuration::get('STRIPE_PRIVATE_KEY_LIVE') : Configuration::get('STRIPE_PRIVATE_KEY_TEST')); /* Case 1: Charge an existing customer (or create it and charge it) */ /* Case 2: Just process the transaction, do not save Stripe customer's details */ if (Configuration::get('STRIPE_SAVE_TOKENS') && !Configuration::get('STRIPE_SAVE_TOKENS_ASK') || Configuration::get('STRIPE_SAVE_TOKENS') && Configuration::get('STRIPE_SAVE_TOKENS_ASK') && Tools::getIsset('stripe_save_token') && Tools::getValue('stripe_save_token')) { /* Get or Create a Stripe Customer */ $stripe_customer = Db::getInstance()->getRow(' SELECT id_stripe_customer, stripe_customer_id, token FROM ' . _DB_PREFIX_ . 'stripe_customer WHERE id_customer = ' . (int) $this->context->cookie->id_customer); if (!isset($stripe_customer['id_stripe_customer'])) { try { $stripe_customer_exists = false; $customer_stripe = Stripe_Customer::create(array('card' => $token, 'description' => $this->l('PrestaShop Customer ID:') . ' ' . (int) $this->context->cookie->id_customer)); $stripe_customer['stripe_customer_id'] = $customer_stripe->id; } catch (Exception $e) { /* If the Credit card is invalid */ $this->_errors['invalid_customer_card'] = true; if (class_exists('Logger')) { Logger::addLog($this->l('Stripe - Invalid Credit Card'), 1, null, 'Cart', (int) $this->context->cart->id, true); } } } else { $stripe_customer_exists = true; /* Update the credit card in the database */ if ($token && $token != $stripe_customer['token']) { try { $cu = Stripe_Customer::retrieve($stripe_customer['stripe_customer_id']); $cu->card = $token; $cu->save(); Db::getInstance()->Execute('UPDATE ' . _DB_PREFIX_ . 'stripe_customer SET token = \'' . pSQL($token) . '\' WHERE id_customer_stripe = ' . (int) $stripe_customer['id_stripe_customer']); } catch (Exception $e) { /* If the new Credit card is invalid, do not replace the old one - no warning or error message required */ $this->_errors['invalid_customer_card'] = true; if (class_exists('Logger')) { Logger::addLog($this->l('Stripe - Invalid Credit Card (replacing an old card)'), 1, null, 'Cart', (int) $this->context->cart->id, true); } } } } } try { $charge_details = array('amount' => $this->context->cart->getOrderTotal() * 100, 'currency' => $this->context->currency->iso_code, 'description' => $this->l('PrestaShop Customer ID:') . ' ' . (int) $this->context->cookie->id_customer . ' - ' . $this->l('PrestaShop Cart ID:') . ' ' . (int) $this->context->cart->id); /* If we have a Stripe's customer ID for this buyer, charge the customer instead of the card */ if (isset($stripe_customer['stripe_customer_id']) && !isset($this->_errors['invalid_customer_card'])) { $charge_details['customer'] = $stripe_customer['stripe_customer_id']; } else { $charge_details['card'] = $token; } $result_json = Tools::jsonDecode(Stripe_Charge::create($charge_details)); /* Save the Customer ID in PrestaShop to re-use it later */ if (isset($stripe_customer_exists) && !$stripe_customer_exists) { Db::getInstance()->Execute(' INSERT INTO ' . _DB_PREFIX_ . 'stripe_customer (id_stripe_customer, stripe_customer_id, token, id_customer, cc_last_digits, date_add) VALUES (NULL, \'' . pSQL($stripe_customer['stripe_customer_id']) . '\', \'' . pSQL($token) . '\', ' . (int) $this->context->cookie->id_customer . ', ' . (int) Tools::substr(Tools::getValue('StripLastDigits'), 0, 4) . ', NOW())'); } // catch the stripe error the correct way. } catch (Stripe_CardError $e) { $body = $e->getJsonBody(); $err = $body['error']; //$type = $err['type']; $message = $err['message']; //$code = $err['code']; //$charge = $err['charge']; if (class_exists('Logger')) { Logger::addLog($this->l('Stripe - Payment transaction failed') . ' ' . $message, 1, null, 'Cart', (int) $this->context->cart->id, true); } $this->context->cookie->__set("stripe_error", 'There was a problem with your payment'); $controller = Configuration::get('PS_ORDER_PROCESS_TYPE') ? 'order-opc.php' : 'order.php'; $location = $this->context->link->getPageLink($controller) . (strpos($controller, '?') !== false ? '&' : '?') . 'step=3#stripe_error'; header('Location: ' . $location); exit; } catch (Exception $e) { $message = $e->getMessage(); if (class_exists('Logger')) { Logger::addLog($this->l('Stripe - Payment transaction failed') . ' ' . $message, 1, null, 'Cart', (int) $this->context->cart->id, true); } /* If it's not a critical error, display the payment form again */ if ($e->getCode() != 'card_declined') { $this->context->cookie->__set("stripe_error", $e->getMessage()); $controller = Configuration::get('PS_ORDER_PROCESS_TYPE') ? 'order-opc.php' : 'order.php'; header('Location: ' . $this->context->link->getPageLink($controller) . (strpos($controller, '?') !== false ? '&' : '?') . 'step=3#stripe_error'); exit; } } /* Log Transaction details */ if (!isset($message)) { if (!isset($result_json->fee)) { $result_json->fee = 0; } $order_status = (int) Configuration::get('STRIPE_PAYMENT_ORDER_STATUS'); $message = $this->l('Stripe Transaction Details:') . "\n\n" . $this->l('Stripe Transaction ID:') . ' ' . $result_json->id . "\n" . $this->l('Amount:') . ' ' . $result_json->amount * 0.01 . "\n" . $this->l('Status:') . ' ' . ($result_json->paid == 'true' ? $this->l('Paid') : $this->l('Unpaid')) . "\n" . $this->l('Processed on:') . ' ' . strftime('%Y-%m-%d %H:%M:%S', $result_json->created) . "\n" . $this->l('Currency:') . ' ' . Tools::strtoupper($result_json->currency) . "\n" . $this->l('Credit card:') . ' ' . $result_json->card->type . ' (' . $this->l('Exp.:') . ' ' . $result_json->card->exp_month . '/' . $result_json->card->exp_year . ')' . "\n" . $this->l('Last 4 digits:') . ' ' . sprintf('%04d', $result_json->card->last4) . ' (' . $this->l('CVC Check:') . ' ' . ($result_json->card->cvc_check == 'pass' ? $this->l('OK') : $this->l('NOT OK')) . ')' . "\n" . $this->l('Processing Fee:') . ' ' . $result_json->fee * 0.01 . "\n" . $this->l('Mode:') . ' ' . ($result_json->livemode == 'true' ? $this->l('Live') : $this->l('Test')) . "\n"; /* In case of successful payment, the address / zip-code can however fail */ if (isset($result_json->card->address_line1_check) && $result_json->card->address_line1_check == 'fail') { $message .= "\n" . $this->l('Warning: Address line 1 check failed'); $order_status = (int) Configuration::get('STRIPE_PENDING_ORDER_STATUS'); } if (isset($result_json->card->address_zip_check) && $result_json->card->address_zip_check == 'fail') { $message .= "\n" . $this->l('Warning: Address zip-code check failed'); $order_status = (int) Configuration::get('STRIPE_PENDING_ORDER_STATUS'); } // warn if cvc check fails if (isset($result_json->card->cvc_check) && $result_json->card->cvc_check == 'fail') { $message .= "\n" . $this->l('Warning: CVC verification check failed'); $order_status = (int) Configuration::get('STRIPE_PENDING_ORDER_STATUS'); } } else { $order_status = (int) Configuration::get('PS_OS_ERROR'); } /* Create the PrestaShop order in database */ $this->validateOrder((int) $this->context->cart->id, (int) $order_status, $result_json->amount * 0.01, $this->displayName, $message, array(), null, false, $this->context->customer->secure_key); /** @since 1.5.0 Attach the Stripe Transaction ID to this Order */ if (version_compare(_PS_VERSION_, '1.5', '>=')) { $new_order = new Order((int) $this->currentOrder); if (Validate::isLoadedObject($new_order)) { $payment = $new_order->getOrderPaymentCollection(); if (isset($payment[0])) { $payment[0]->transaction_id = pSQL($result_json->id); $payment[0]->save(); } } } /* Store the transaction details */ if (isset($result_json->id)) { Db::getInstance()->Execute(' INSERT INTO ' . _DB_PREFIX_ . 'stripe_transaction (type, id_stripe_customer, id_cart, id_order, id_transaction, amount, status, currency, cc_type, cc_exp, cc_last_digits, cvc_check, fee, mode, date_add) VALUES (\'payment\', ' . (isset($stripe_customer['id_stripe_customer']) ? (int) $stripe_customer['id_stripe_customer'] : 0) . ', ' . (int) $this->context->cart->id . ', ' . (int) $this->currentOrder . ', \'' . pSQL($result_json->id) . '\', \'' . $result_json->amount * 0.01 . '\', \'' . ($result_json->paid == 'true' ? 'paid' : 'unpaid') . '\', \'' . pSQL($result_json->currency) . '\', \'' . pSQL($result_json->card->type) . '\', \'' . (int) $result_json->card->exp_month . '/' . (int) $result_json->card->exp_year . '\', ' . (int) $result_json->card->last4 . ', ' . ($result_json->card->cvc_check == 'pass' ? 1 : 0) . ', \'' . $result_json->fee * 0.01 . '\', \'' . ($result_json->livemode == 'true' ? 'live' : 'test') . '\', NOW())'); } /* Redirect the user to the order confirmation page / history */ if (_PS_VERSION_ < 1.5) { $redirect = __PS_BASE_URI__ . 'order-confirmation.php?id_cart=' . (int) $this->context->cart->id . '&id_module=' . (int) $this->id . '&id_order=' . (int) $this->currentOrder . '&key=' . $this->context->customer->secure_key; } else { $redirect = __PS_BASE_URI__ . 'index.php?controller=order-confirmation&id_cart=' . (int) $this->context->cart->id . '&id_module=' . (int) $this->id . '&id_order=' . (int) $this->currentOrder . '&key=' . $this->context->customer->secure_key; } header('Location: ' . $redirect); exit; }
/** * Shortcode for zeen101's Leaky Paywall * Prints out the zeen101's Leaky Paywall * * @since CHANGEME */ function do_leaky_paywall_profile($atts) { $settings = get_leaky_paywall_settings(); $mode = 'off' === $settings['test_mode'] ? 'live' : 'test'; $defaults = array(); // Merge defaults with passed atts // Extract (make each array element its own PHP var $args = shortcode_atts($defaults, $atts); extract($args); $results = ''; if (is_user_logged_in()) { $sites = array(''); global $blog_id; if (is_multisite_premium()) { if (!is_main_site($blog_id)) { $sites = array('_all', '_' . $blog_id); } else { $sites = array('_all', '_' . $blog_id, ''); } } $user = wp_get_current_user(); $results .= sprintf(__('<p>Welcome %s, you are currently logged in. <a href="%s">Click here to log out.</a></p>', 'issuem-leaky-paywall'), $user->user_login, wp_logout_url(get_page_link($settings['page_for_login']))); //Your Subscription $results .= '<h2>' . __('Your Subscription', 'issuem-leaky-paywall') . '</h2>'; $results .= apply_filters('leaky_paywall_profile_your_subscription_start', ''); $results .= '<table>'; $results .= '<thead>'; $results .= '<tr>'; $results .= ' <th>' . __('Status', 'issuem-leaky-paywall') . '</th>'; $results .= ' <th>' . __('Type', 'issuem-leaky-paywall') . '</th>'; $results .= ' <th>' . __('Payment Method', 'issuem-leaky-paywall') . '</th>'; $results .= ' <th>' . __('Expiration', 'issuem-leaky-paywall') . '</th>'; $results .= ' <th>' . __('Cancel?', 'issuem-leaky-paywall') . '</th>'; $results .= '</tr>'; $results .= '</thead>'; foreach ($sites as $site) { $status = get_user_meta($user->ID, '_issuem_leaky_paywall_' . $mode . '_payment_status' . $site, true); $level_id = get_user_meta($user->ID, '_issuem_leaky_paywall_' . $mode . '_level_id' . $site, true); $level_id = apply_filters('get_leaky_paywall_users_level_id', $level_id, $user, $mode, $site); $level_id = apply_filters('get_leaky_paywall_subscription_level_level_id', $level_id); if (false === $level_id || empty($settings['levels'][$level_id]['label'])) { $level_name = __('Undefined', 'issuem-leaky-paywall'); } else { $level_name = stripcslashes($settings['levels'][$level_id]['label']); } $payment_gateway = get_user_meta($user->ID, '_issuem_leaky_paywall_' . $mode . '_payment_gateway' . $site, true); $expires = get_user_meta($user->ID, '_issuem_leaky_paywall_' . $mode . '_expires' . $site, true); $expires = apply_filters('do_leaky_paywall_profile_shortcode_expiration_column', $expires, $user, $mode, $site, $level_id); if (empty($expires) || '0000-00-00 00:00:00' === $expires) { $expires = __('Never', 'issuem-leaky-paywall'); } else { $date_format = get_option('date_format'); $expires = mysql2date($date_format, $expires); } $plan = get_user_meta($user->ID, '_issuem_leaky_paywall_' . $mode . '_plan' . $site, true); if (!empty($plan) && 'Canceled' !== $plan && 'Never' !== $expires) { $expires = sprintf(__('Recurs on %s', 'issuem-leaky-paywall'), $expires); } $paid = leaky_paywall_has_user_paid($user->user_email, $site); if ('subscription' === $paid) { $subscriber_id = get_user_meta($user->ID, '_issuem_leaky_paywall_' . $mode . '_subscriber_id' . $site, true); $payment_gateway = get_user_meta($user->ID, '_issuem_leaky_paywall_' . $mode . '_payment_gateway' . $site, true); $cancel = sprintf(__('<a href="%s">cancel</a>', 'issuem-leaky-paywall'), '?cancel&payment_gateway=' . $payment_gateway . '&subscriber_id=' . $subscriber_id); } else { $cancel = ' '; } if (!empty($status) && !empty($level_name) && !empty($payment_gateway) && !empty($expires)) { $results .= '<tbody>'; $results .= ' <td>' . ucfirst($status) . '</td>'; $results .= ' <td>' . $level_name . '</td>'; $results .= ' <td>' . leaky_paywall_translate_payment_gateway_slug_to_name($payment_gateway) . '</td>'; $results .= ' <td>' . $expires . '</td>'; $results .= ' <td>' . $cancel . '</td>'; $results .= '</tbody>'; } } $results .= '</table>'; $results .= apply_filters('leaky_paywall_profile_your_subscription_end', ''); //Your Mobile Devices include_once ABSPATH . 'wp-admin/includes/plugin.php'; if (is_plugin_active('unipress-api/unipress-api.php')) { global $unipress_api; $results .= '<h2>' . __('Your Mobile Devices', 'issuem-leaky-paywall') . '</h2>'; $results .= '<p>' . __('To generate a token for the mobile app, click the "Add New Mobile Device" button below.', 'issuem-leaky-paywall') . '</p>'; $results .= apply_filters('leaky_paywall_profile_your_mobile_devices_start', ''); $results .= $unipress_api->leaky_paywall_subscriber_info_paid_subscriber_end(''); $results .= apply_filters('leaky_paywall_profile_your_mobile_devices_end', ''); } //Your Profile $results .= '<h2>' . __('Your Profile', 'issuem-leaky-paywall') . '</h2>'; if (!empty($_POST['leaky-paywall-profile-nonce'])) { if (wp_verify_nonce($_POST['leaky-paywall-profile-nonce'], 'leaky-paywall-profile')) { try { $userdata = get_userdata($user->ID); $args = array('ID' => $user->ID, 'user_login' => $userdata->user_login, 'display_name' => $userdata->display_name, 'user_email' => $userdata->user_email); if (!empty($_POST['username'])) { $args['user_login'] = $_POST['username']; } if (!empty($_POST['displayname'])) { $args['display_name'] = $_POST['displayname']; } if (!empty($_POST['email'])) { if (is_email($_POST['email'])) { $args['user_email'] = $_POST['email']; } else { throw new Exception(__('Invalid email address.', 'issuem-leaky-paywall')); } } if (!empty($_POST['password1']) && !empty($_POST['password2'])) { if ($_POST['password1'] === $_POST['password2']) { wp_set_password($_POST['password1'], $user->ID); } else { throw new Exception(__('Passwords do not match.', 'issuem-leaky-paywall')); } } $user_id = wp_update_user($args); if (is_wp_error($user_id)) { throw new Exception($user_id->get_error_message()); } else { $user = get_userdata($user_id); //Refresh the user object $results .= '<p class="save">' . __('Profile Changes Saved.', 'issuem-leaky-paywall') . '</p>'; } } catch (Exception $e) { $results .= '<p class="error">' . $e->getMessage() . '</p>'; } } } $results .= apply_filters('leaky_paywall_profile_your_profile_start', ''); $results .= '<form id="leaky-paywall-profile" action="" method="post">'; $results .= '<p>'; $results .= '<label class="leaky-paywall-field-label" for="leaky-paywall-username">' . __('Username', 'issuem-leaky-paywall') . '</label>'; $results .= '<input type="text" class="issuem-leaky-paywall-field-input" id="leaky-paywall-username" name="username" value="' . $user->user_login . '" disabled="disabled" readonly="readonly" />'; $results .= '</p>'; $results .= '<p>'; $results .= '<label class="leaky-paywall-field-label" for="leaky-paywall-display-name">' . __('Display Name', 'issuem-leaky-paywall') . '</label>'; $results .= '<input type="text" class="issuem-leaky-paywall-field-input" id="leaky-paywall-display-name" name="displayname" value="' . $user->display_name . '" />'; $results .= '</p>'; $results .= '<p>'; $results .= '<label class="leaky-paywall-field-label" for="leaky-paywall-email">' . __('Email', 'issuem-leaky-paywall') . '</label>'; $results .= '<input type="text" class="issuem-leaky-paywall-field-input" id="leaky-paywall-email" name="email" value="' . $user->user_email . '" />'; $results .= '</p>'; $results .= '<p>'; $results .= '<label class="leaky-paywall-field-label" for="leaky-paywall-password1">' . __('New Password', 'issuem-leaky-paywall') . '</label>'; $results .= '<input type="password" class="issuem-leaky-paywall-field-input" id="leaky-paywall-password1" name="password1" value="" />'; $results .= '</p>'; $results .= '<p>'; $results .= '<label class="leaky-paywall-field-label" for="leaky-paywall-gift-subscription-password2">' . __('New Password (again)', 'issuem-leaky-paywall') . '</label>'; $results .= '<input type="password" class="issuem-leaky-paywall-field-input" id="leaky-paywall-gift-subscription-password2" name="password2" value="" />'; $results .= '</p>'; $results .= wp_nonce_field('leaky-paywall-profile', 'leaky-paywall-profile-nonce', true, false); $results .= '<p class="submit"><input type="submit" id="submit" class="button button-primary" value="' . __('Update Profile Information', 'issuem-leaky-paywall') . '" /></p>'; $results .= '</form>'; $results .= apply_filters('leaky_paywall_profile_your_profile_end', ''); $results .= '<div class="issuem-leaky-paywall-subscriber-info">'; if (false !== ($expires = leaky_paywall_has_user_paid())) { //Your Payment Information if (!empty($_POST['leaky-paywall-profile-stripe-cc-update-nonce'])) { if (wp_verify_nonce($_POST['leaky-paywall-profile-stripe-cc-update-nonce'], 'leaky-paywall-profile-stripe-cc-update')) { try { $secret_key = 'test' === $mode ? $settings['test_secret_key'] : $settings['live_secret_key']; foreach ($sites as $site) { $subscriber_id = get_user_meta($user->ID, '_issuem_leaky_paywall_' . $mode . '_subscriber_id' . $site, true); if (!empty($subscriber_id)) { break; } } $cu = Stripe_Customer::retrieve($subscriber_id); if (!empty($cu)) { if (true === $cu->deleted) { throw new Exception(__('Unable to find valid Stripe customer ID to unsubscribe. Please contact support', 'issuem-leaky-paywall')); } } if (empty($_POST['stripe-cc-number'])) { throw new Exception(__('Credit Card Number Required', 'issuem-leaky-paywall')); } if (empty($_POST['stripe-cc-exp-month'])) { throw new Exception(__('Credit Card Expiration Month Required', 'issuem-leaky-paywall')); } if (empty($_POST['stripe-cc-exp-year'])) { throw new Exception(__('Credit Card Expiration Year Required', 'issuem-leaky-paywall')); } if (empty($_POST['stripe-cc-cvc'])) { throw new Exception(__('Credit Card Security Code (CVC) Required', 'issuem-leaky-paywall')); } if (empty($_POST['stripe-cc-name'])) { throw new Exception(__("Credit Card Cardholder's Name Required", 'issuem-leaky-paywall')); } $subscriptions = $cu->subscriptions->all('limit=1'); foreach ($subscriptions->data as $susbcription) { $sub = $cu->subscriptions->retrieve($susbcription->id); $sub->card = array('number' => $_POST['stripe-cc-number'], 'exp_month' => $_POST['stripe-cc-exp-month'], 'exp_year' => $_POST['stripe-cc-exp-year'], 'cvc' => $_POST['stripe-cc-cvc'], 'name' => $_POST['stripe-cc-name']); $sub->save(); } $results .= '<p>' . __('Your credit card has been successfully updated.', 'issuem-leaky-paywall') . '</p>'; } catch (Exception $e) { $results = '<h1>' . sprintf(__('Error updating Credit Card information: %s', 'issuem-leaky-paywall'), $e->getMessage()) . '</h1>'; } } } $results .= apply_filters('leaky_paywall_profile_your_payment_info_start', ''); $results .= apply_filters('leaky_paywall_subscriber_info_paid_subscriber_start', ''); foreach ($sites as $site) { $payment_gateway = get_user_meta($user->ID, '_issuem_leaky_paywall_' . $mode . '_payment_gateway' . $site, true); $subscriber_id = get_user_meta($user->ID, '_issuem_leaky_paywall_' . $mode . '_subscriber_id' . $site, true); $expires = leaky_paywall_has_user_paid($user->user_email, $site); if ('subscription' === $expires) { $payment_form = ''; switch ($payment_gateway) { case 'stripe': $payment_form .= '<h3>' . __('Update Credit Card', 'issuem-leaky-paywall') . '</h3>'; $payment_form .= '<form id="leaky-paywall-update-credit-card" action="" method="post">'; $payment_form .= '<p>'; $payment_form .= '<label class="lp-field-label" for="leaky-paywall-cc-number">' . __('Card Number', 'issuem-leaky-paywall') . '</label>'; $payment_form .= '<input type="text" class="issuem-leaky-paywall-field-input" id="leaky-paywall-cc-number" name="stripe-cc-number" value="" placeholder="4242 4242 4242 4242" />'; $payment_form .= '</p>'; $payment_form .= '<p>'; $payment_form .= '<label class="lp-field-label" for="leaky-paywall-cc-expiration">' . __('Expiration Date', 'issuem-leaky-paywall') . '</label>'; $payment_form .= '<input type="text" class="issuem-leaky-paywall-field-input" id="leaky-paywall-cc-exp-month" name="stripe-cc-exp-month" value="" placeholder="' . date_i18n('m', strtotime('+1 Month')) . '" />'; $payment_form .= ' / '; $payment_form .= '<input type="text" class="issuem-leaky-paywall-field-input" id="leaky-paywall-cc-exp-year" name="stripe-cc-exp-year" value="" placeholder="' . date_i18n('Y', strtotime('+1 Year')) . '" />'; $payment_form .= '</p>'; $payment_form .= '<p>'; $payment_form .= '<label class="lp-field-label" for="leaky-paywall-cc-cvc">' . __('Security Code (CVC)', 'issuem-leaky-paywall') . '</label>'; $payment_form .= '<input type="text" class="issuem-leaky-paywall-field-input" id="leaky-paywall-cc-cvc" name="stripe-cc-cvc" value="" placeholder="777" />'; $payment_form .= '</p>'; $payment_form .= '<p>'; $payment_form .= '<label class="lp-field-label" for="leaky-paywall-cc-name">' . __("Cardholder's Name", 'issuem-leaky-paywall') . '</label>'; $payment_form .= '<input type="text" class="issuem-leaky-paywall-field-input" id="leaky-paywall-cc-name" name="stripe-cc-name" value="" placeholder="John Doe" />'; $payment_form .= '</p>'; $payment_form .= wp_nonce_field('leaky-paywall-profile-stripe-cc-update', 'leaky-paywall-profile-stripe-cc-update-nonce', true, false); $payment_form .= '<p class="submit"><input type="submit" id="submit" class="button button-primary" value="' . __('Update Credit Card Information', 'issuem-leaky-paywall') . '" /></p>'; $payment_form .= '</form>'; break; case 'paypal-standard': case 'paypal_standard': $paypal_url = 'test' === $mode ? 'https://www.sandbox.paypal.com/' : 'https://www.paypal.com/'; $paypal_email = 'test' === $mode ? $settings['paypal_sand_email'] : $settings['paypal_live_email']; $payment_form .= '<p>' . __("You can update your payment details through PayPal's website.", 'issuem-leaky-paywall') . '</p>'; $payment_form .= '<p><a href="' . $paypal_url . '"><img src="https://www.paypalobjects.com/webstatic/en_US/btn/btn_pponly_142x27.png" border="0"></a></p>'; break; } $results .= '<h2>' . __('Your Payment Information', 'issuem-leaky-paywall') . '</h2>'; $results .= $payment_form; break; //We only want the first match } } } else { $results .= '<h2>' . __('Your Account is Not Currently Active', 'issuem-leaky-paywall') . '</h2>'; $results .= '<p>' . sprintf(__('To reactivate your account, please visit our <a href="%s">Subscription page</a>.', 'issuem-leaky-paywall'), get_page_link($settings['page_for_subscription'])) . '</p>'; } $results .= '</div>'; $results .= apply_filters('leaky_paywall_profile_your_payment_info_end', ''); } else { $results .= do_leaky_paywall_login(array()); } return $results; }
/** * @method GET */ function get() { // get an authuser $authUser = new AuthUser(); if (isset($authUser->UserUniqId)) { // check if authorized // get sites $list = Site::GetSites(); Stripe::setApiKey(STRIPE_API_KEY); // init $status = ''; $plan = ''; $planName = ''; $renewalReadable = ''; $customerId = ''; $sites = array(); foreach ($list as $site) { // iterate files if ($site['CustomerId'] != null && $site['CustomerId'] != '') { $customerId = $site['CustomerId']; // get customer $customer = Stripe_Customer::retrieve($site['CustomerId']); if ($customer->subscription) { $status = $customer->subscription->status; $plan = $customer->subscription->plan->id; $planName = $customer->subscription->plan->name; $local = new DateTimeZone($site['TimeZone']); $date = new DateTime(); $date->setTimestamp($customer->subscription->current_period_end); $date->setTimezone($local); $renewalReadable = $date->format('D, M d y h:i:s a'); } else { $status = 'unsubscribed'; $plan = ''; $planName = 'N/A'; $renewalReadable = 'N/A'; } } else { $customerId = $site['CustomerId']; $status = 'N/A'; $plan = ''; $planName = ''; $renewalReadable = ''; } $new_site = array('siteId' => $site['SiteId'], 'siteUniqId' => $site['SiteUniqId'], 'name' => $site['Name'], 'domain' => $site['Domain'], 'type' => $site['Type'], 'status' => $status, 'planId' => $plan, 'planName' => $planName, 'customerId' => $customerId, 'renewalReadable' => $renewalReadable); array_push($sites, $new_site); } // return a json response $response = new Tonic\Response(Tonic\Response::OK); $response->contentType = 'application/json'; $response->body = json_encode($sites); return $response; } else { // unauthorized access return new Tonic\Response(Tonic\Response::UNAUTHORIZED); } }
public function collect_payments($params) { include_once dirname(dirname(__FILE__)) . '/configs/config.inc.php'; $db_params = parse_ini_file(dirname(dirname(__FILE__)) . '/configs/application.ini'); $pdo = new PDO("mysql:dbname=" . $db_params['database.params.dbname'] . ";host=" . $db_params['database.params.host'], $db_params['database.params.username'], $db_params['database.params.password']); $payments = $pdo->prepare(' SELECT preapprovals.*, ' . LAUNCHCAMPAIGN . '.*, ' . USERS . '.emailid AS receiver_email FROM preapprovals LEFT JOIN ' . LAUNCHCAMPAIGN . ' ON preapprovals.preapprovals_campaign=' . LAUNCHCAMPAIGN . '.campaign_id LEFT JOIN ' . USERS . ' ON ' . USERS . '.user_id=' . LAUNCHCAMPAIGN . '.user_id WHERE preapprovals_campaign=? AND preapprovals_status!="collected" '); $payments->execute(array($params['campid'])); while ($payments_row = $payments->fetch(PDO::FETCH_ASSOC)) { $payments_arr[] = $payments_row; } $order = $pdo->prepare('INSERT INTO order_record VALUES(null,?, ?, ?, ?, ?, ?, ?, NOW(), ?, "")'); $payments_update = $pdo->prepare('UPDATE preapprovals SET preapprovals_status=? WHERE preapprovals_id=?'); $errors = 0; //print_r($payments_arr); Stripe::setApiKey(STRIPE_SECRET_KEY); for ($i = 0; $i < count($payments_arr); $i++) { if ($payments_arr[$i]["sold"] >= $payments_arr[$i]["goal"]) { try { $charge = Stripe_Charge::create(array('customer' => $payments_arr[$i]['preapprovals_key'], 'amount' => ($payments_arr[$i]['preapprovals_share_app'] + $payments_arr[$i]['preapprovals_share_user']) * 100, 'currency' => 'usd')); if ($charge->paid == 1) { $status = 'collected'; } else { $status = 'failure'; } $order_data = array($payments_arr[$i]['tee_image'], $payments_arr[$i]['preapprovals_name'], $payments_arr[$i]['url'], $payments_arr[$i]['preapprovals_qty'], $payments_arr[$i]['preapprovals_size'], $payments_arr[$i]['preapprovals_price'], $payments_arr[$i]['preapprovals_share_app'] + $payments_arr[$i]['preapprovals_share_user'], $payments_arr[$i]['preapprovals_email']); $order->execute($order_data); } catch (Exception $e) { $status = 'ERROR: ' . $e->response->error_description . "\n"; $errors++; } } else { try { $cu = Stripe_Customer::retrieve($payments_arr[$i]['preapprovals_key']); $cu->delete(); } catch (Exception $e) { } $status = 'canceled'; } $payments_update->execute(array($status, $payments_arr[$i]['preapprovals_id'])); } $payments_update->execute(array($status, $payments_arr[$i]['preapprovals_id'])); return array("attempts" => count($payments_arr), "errors" => $errors); }
public function cancel($entry, $feed) { $this->include_stripe_api(); try { $customer_id = gform_get_meta($entry['id'], 'stripe_customer_id'); $customer = Stripe_Customer::retrieve($customer_id); $customer->cancelSubscription(); return true; } catch (Stripe_Error $error) { return false; } }
/** * Get a Stripe customer object. * * If $this->customer is set, it returns it. * It first checks if the order has a subscription_transaction_id. If so, that's the customer id. * If not, it checks for a user_id on the order and searches for a customer id in the user meta. * If a customer id is found, it checks for a customer through the Stripe API. * If a customer is found and there is a stripeToken on the order passed, it will update the customer. * If no customer is found and there is a stripeToken on the order passed, it will create a customer. * * @since 1.4 * @return Stripe_Customer|false */ function getCustomer(&$order = false, $force = false) { global $current_user; //already have it? if (!empty($this->customer) && !$force) { return $this->customer; } //figure out user_id and user if (!empty($order->user_id)) { $user_id = $order->user_id; } //if no id passed, check the current user if (empty($user_id) && !empty($current_user->ID)) { $user_id = $current_user->ID; } if (!empty($user_id)) { $user = get_userdata($user_id); } else { $user = NULL; } //transaction id? if (!empty($order->subscription_transaction_id) && strpos($order->subscription_transaction_id, "cus_") !== false) { $customer_id = $order->subscription_transaction_id; } else { //try based on user id if (!empty($user_id)) { $customer_id = get_user_meta($user_id, "pmpro_stripe_customerid", true); } //look up by transaction id if (empty($customer_id) && !empty($user_id)) { //user id from this order or the user's last stripe order if (!empty($order->payment_transaction_id)) { $payment_transaction_id = $order->payment_transaction_id; } else { //find the user's last stripe order $last_order = new MemberOrder(); $last_order->getLastMemberOrder($user_id, array('success', 'cancelled'), NULL, 'stripe', $order->Gateway->gateway_environment); if (!empty($last_order->payment_transaction_id)) { $payment_transaction_id = $last_order->payment_transaction_id; } } //we have a transaction id to look up if (!empty($payment_transaction_id)) { if (strpos($payment_transaction_id, "ch_") !== false) { //charge, look it up $charge = Stripe_Charge::retrieve($payment_transaction_id); if (!empty($charge) && !empty($charge->customer)) { $customer_id = $charge->customer; } } else { if (strpos($payment_transaction_id, "in_") !== false) { //invoice look it up $invoice = Stripe_Invoice::retrieve($payment_transaction_id); if (!empty($invoice) && !empty($invoice->customer)) { $customer_id = $invoice->customer; } } } } //if we found it, save to user meta for future reference if (!empty($customer_id)) { update_user_meta($user_id, "pmpro_stripe_customerid", $customer_id); } } } //get name and email values from order in case we update if (!empty($order->FirstName) && !empty($order->LastName)) { $name = trim($order->FirstName . " " . $order->LastName); } elseif (!empty($order->FirstName)) { $name = $order->FirstName; } elseif (!empty($order->LastName)) { $name = $order->LastName; } if (empty($name) && !empty($user->ID)) { $name = trim($user->first_name . " " . $user->last_name); //still empty? if (empty($name)) { $name = $user->user_login; } } elseif (empty($name)) { $name = "No Name"; } if (!empty($order->Email)) { $email = $order->Email; } else { $email = ""; } if (empty($email) && !empty($user->ID) && !empty($user->user_email)) { $email = $user->user_email; } elseif (empty($email)) { $email = "No Email"; } //check for an existing stripe customer if (!empty($customer_id)) { try { $this->customer = Stripe_Customer::retrieve($customer_id); //update the customer description and card if (!empty($order->stripeToken)) { $this->customer->description = $name . " (" . $email . ")"; $this->customer->email = $email; $this->customer->card = $order->stripeToken; $this->customer->save(); } return $this->customer; } catch (Exception $e) { //assume no customer found } } //no customer id, create one if (!empty($order->stripeToken)) { try { $this->customer = Stripe_Customer::create(array("description" => $name . " (" . $email . ")", "email" => $order->Email, "card" => $order->stripeToken)); } catch (Exception $e) { $order->error = __("Error creating customer record with Stripe:", "pmpro") . " " . $e->getMessage(); $order->shorterror = $order->error; return false; } if (!empty($user_id)) { //user logged in/etc update_user_meta($user_id, "pmpro_stripe_customerid", $this->customer->id); } else { //user not registered yet, queue it up global $pmpro_stripe_customer_id; $pmpro_stripe_customer_id = $this->customer->id; if (!function_exists('pmpro_user_register_stripe_customerid')) { function pmpro_user_register_stripe_customerid($user_id) { global $pmpro_stripe_customer_id; update_user_meta($user_id, "pmpro_stripe_customerid", $pmpro_stripe_customer_id); } add_action("user_register", "pmpro_user_register_stripe_customerid"); } } return apply_filters('pmpro_stripe_create_customer', $this->customer); } return false; }
/** * Submit a payment using Stripe's PHP API: * https://stripe.com/docs/api?lang=php * * @param array $params assoc array of input parameters for this transaction * * @return array the result in a nice formatted array (or an error object) * @public */ function doDirectPayment(&$params) { //Include Stripe library & Set API credentials. require_once "stripe-php/lib/Stripe.php"; Stripe::setApiKey($this->_paymentProcessor['user_name']); //Stripe amount required in cents. $amount = $params['amount'] * 100; //It would require 3 digits after the decimal for one to make it this far, CiviCRM prevents this, but let's be redundant. $amount = number_format($amount, 0, '', ''); //Check for existing customer, create new otherwise. $email = $params['email']; $customer_query = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_stripe_customers WHERE email = '{$email}'"); //Use Stripe.js instead of raw card details. if (isset($params['stripe_token'])) { $card_details = $params['stripe_token']; } else { CRM_Core_Error::fatal(ts('Stripe.js token was not passed! Have you turned on the CiviCRM-Stripe CMS module?')); } /**** * If for some reason you cannot use Stripe.js and you are aware of PCI Compliance issues, here is the alternative to Stripe.js: ****/ //Prepare Card details in advance to use for new Stripe Customer object if we need. /* $cc_name = $params['first_name'] . " "; if (strlen($params['middle_name']) > 0) { $cc_name .= $params['middle_name'] . " "; } $cc_name .= $params['last_name']; $card_details = array( 'number' => $params['credit_card_number'], 'exp_month' => $params['month'], 'exp_year' => $params['year'], 'cvc' => $params['cvv2'], 'name' => $cc_name, 'address_line1' => $params['street_address'], 'address_state' => $params['state_province'], 'address_zip' => $params['postal_code'], ); */ //Create a new Customer in Stripe if (!isset($customer_query)) { $stripe_customer = Stripe_Customer::create(array('description' => 'Payment from CiviCRM', 'card' => $card_details, 'email' => $email)); //Store the relationship between CiviCRM's email address for the Contact & Stripe's Customer ID if (isset($stripe_customer)) { CRM_Core_DAO::executeQuery("INSERT INTO civicrm_stripe_customers (email, id) VALUES ('{$email}', '{$stripe_customer->id}')"); } else { CRM_Core_Error::fatal(ts('There was an error saving new customer within Stripe. Is Stripe down?')); } } else { $stripe_customer = Stripe_Customer::retrieve($customer_query); if (!empty($stripe_customer)) { $stripe_customer->card = $card_details; $stripe_customer->save(); } else { $stripe_customer = Stripe_Customer::create(array('description' => 'Donor from CiviCRM', 'card' => $card_details, 'email' => $email)); //Somehow a customer ID saved in the system no longer pairs with a Customer within Stripe. (Perhaps deleted using Stripe interface?) //Store the relationship between CiviCRM's email address for the Contact & Stripe's Customer ID if (isset($stripe_customer)) { CRM_Core_DAO::executeQuery("DELETE FROM civicrm_stripe_customers WHERE email = '{$email}'"); CRM_Core_DAO::executeQuery("INSERT INTO civicrm_stripe_customers (email, id) VALUES ('{$email}', '{$stripe_customer->id}')"); } else { CRM_Core_Error::fatal(ts('There was an error saving new customer within Stripe. Is Stripe down?')); } } } //Prepare the charge array, minus Customer/Card details. $stripe_charge = array('amount' => $amount, 'currency' => 'usd', 'description' => '# CiviCRM Donation Page # ' . $params['description'] . ' # Invoice ID # ' . $params['invoiceID']); //Use Stripe Customer if we have a valid one. Otherwise just use the card. if (!empty($stripe_customer->id)) { $stripe_charge['customer'] = $stripe_customer->id; } else { $stripe_charge['card'] = $card_details; } //Handle recurring payments in doRecurPayment(). if (CRM_Utils_Array::value('is_recur', $params) && $params['contributionRecurID']) { return $this->doRecurPayment($params, $amount, $stripe_customer); } //Fire away! $stripe_response = Stripe_Charge::create($stripe_charge); $params['trxn_id'] = $stripe_response->id; return $params; }