Beispiel #1
0
 public function testRecipientDeleteCard()
 {
     $token = Stripe_Token::create(array("card" => array("number" => "4000056655665556", "exp_month" => 5, "exp_year" => date('Y') + 3, "cvc" => "314")));
     $recipient = $this->createTestRecipient();
     $createdCard = $recipient->cards->create(array("card" => $token->id));
     $recipient->save();
     $updatedRecipient = Stripe_Recipient::retrieve($recipient->id);
     $updatedCards = $updatedRecipient->cards->all();
     $this->assertEqual(count($updatedCards["data"]), 1);
     $deleteStatus = $updatedRecipient->cards->retrieve($createdCard->id)->delete();
     $this->assertEqual($deleteStatus->deleted, 1);
     $updatedRecipient->save();
     $postDeleteRecipient = Stripe_Recipient::retrieve($recipient->id);
     $postDeleteCards = $postDeleteRecipient->cards->all();
     $this->assertEqual(count($postDeleteCards["data"]), 0);
 }
Beispiel #2
0
 public function create_card_token($card_info)
 {
     if (isset($card_info['number'])) {
         $card_info = array('card' => $card_info);
     }
     try {
         $card = Stripe_Token::create($card_info);
         return $card;
     } catch (Exception $e) {
         $this->error = TRUE;
         $this->message = $e->getMessage();
         $this->code = $e->getCode();
         //return FALSE;
         return array('error' => TRUE, 'code' => $this->code, 'message' => $this->message);
     }
 }
Beispiel #3
0
 if ($customerId == "") {
     # Create a Customer if the customer is already not in database.
     $customer = Stripe_Customer::create(array("card" => $token, "description" => $_SESSION['FBID']));
     // Save the customer ID in your database so you can use it later
     saveStripeCustomerId($_SESSION['FBID'], $customer->id);
     error_log("Saving Customer [" . $_SESSION['FBID'] . "] [" . $customer->id . "]");
     $customerId = $customer->id;
 }
 if ($customerId != "") {
     // Save the Transaction details in your database so you can use it later
     ## The default card is the 1st card
     list($fullName, $email) = getFullName($_SESSION['FBID']);
     $sid = $_SESSION['FBID'];
     #autoSubscribe($email);
     ## Get current Card ID from Token
     $retrieve_token = Stripe_Token::retrieve($token);
     $card_id = $retrieve_token->card->id;
     error_log("token :: [" . $token . "]");
     error_log("card_id :: [" . $card_id . "]");
     ## To check whether the Card is already in Customer Base if not we will add this now.
     $customer_data = Stripe_Customer::retrieve($customerId);
     error_log(">>>>>>>>>>>>>CUSTOMER OBJECT>>>>>>>>>>>>>>>>>>");
     error_log(print_r($customer_data, true), 0);
     try {
         $getCard = $customer_data->sources->retrieve($card_id);
         error_log(">>>>>>>>>>>>>CARD_OBJECT>>>>>>>>>>>>>>>>>>");
         error_log(print_r($getCard, true), 0);
     } catch (Stripe_InvalidRequestError $e) {
         // Invalid Request Possibly this card is not available.
         error_log("This Card is not Available \n");
         $getCard->id = '';
Beispiel #4
0
 /**
  * Return the chosen payment details here for final confirmation. You probably don't need
  *	to post anything in the form as it should be in your $_SESSION var already.
  *
  * @param array $cart. Contains the cart contents for the current blog, global cart if $mp->global_cart is true
  * @param array $shipping_info. Contains shipping info and email in case you need it
  */
 function confirm_payment_form($cart, $shipping_info)
 {
     global $mp;
     $settings = get_option('mp_settings');
     //make sure token is set at this point
     if (!isset($_SESSION['stripeToken'])) {
         $mp->cart_checkout_error(__('The Stripe Token was not generated correctly. Please go back and try again.', 'mp'));
         return false;
     }
     //setup the Stripe API
     if (!class_exists('Stripe')) {
         require_once $mp->plugin_dir . "plugins-gateway/stripe-files/lib/Stripe.php";
     }
     Stripe::setApiKey($this->private_key);
     try {
         $token = Stripe_Token::retrieve($_SESSION['stripeToken']);
     } catch (Exception $e) {
         $mp->cart_checkout_error(sprintf(__('%s. Please go back and try again.', 'mp'), $e->getMessage()));
         return false;
     }
     $content = '';
     $content .= '<table class="mp_cart_billing">';
     $content .= '<thead><tr>';
     $content .= '<th>' . __('Billing Information:', 'mp') . '</th>';
     $content .= '<th align="right"><a href="' . mp_checkout_step_url('checkout') . '">' . __('&laquo; Edit', 'mp') . '</a></th>';
     $content .= '</tr></thead>';
     $content .= '<tbody>';
     $content .= '<tr>';
     $content .= '<td align="right">' . __('Payment method:', 'mp') . '</td>';
     $content .= '<td>' . sprintf(__('Your <strong>%1$s Card</strong> ending in <strong>%2$s</strong>. Expires <strong>%3$s</strong>', 'mp'), $token->card->type, $token->card->last4, $token->card->exp_month . '/' . $token->card->exp_year) . '</td>';
     $content .= '</tr>';
     $content .= '</tbody>';
     $content .= '</table>';
     return $content;
 }
Beispiel #5
0
 public function testCustomerDeleteCard()
 {
     $token = Stripe_Token::create(array("card" => array("number" => "4242424242424242", "exp_month" => 5, "exp_year" => date('Y') + 3, "cvc" => "314")));
     $customer = $this->createTestCustomer();
     $createdCard = $customer->cards->create(array("card" => $token->id));
     $customer->save();
     $updatedCustomer = Stripe_Customer::retrieve($customer->id);
     $updatedCards = $updatedCustomer->cards->all();
     $this->assertEqual(count($updatedCards["data"]), 2);
     $deleteStatus = $updatedCustomer->cards->retrieve($createdCard->id)->delete();
     $this->assertEqual($deleteStatus->deleted, 1);
     $updatedCustomer->save();
     $postDeleteCustomer = Stripe_Customer::retrieve($customer->id);
     $postDeleteCards = $postDeleteCustomer->cards->all();
     $this->assertEqual(count($postDeleteCards["data"]), 1);
 }
Beispiel #6
0
 public function testUrls()
 {
     $this->assertEqual(Stripe_Token::classUrl('Stripe_Token'), '/v1/tokens');
     $token = new Stripe_Token('abcd/efgh');
     $this->assertEqual($token->instanceUrl(), '/v1/tokens/abcd%2Fefgh');
 }
 /**
  * Process the payment
  */
 function process_payment($order_id)
 {
     global $woocommerce, $wpdb, $ignitewoo_vendors;
     $customer_id = 0;
     $stripe_token = isset($_POST['stripe_token']) ? woocommerce_clean($_POST['stripe_token']) : '';
     $order = new WC_Order($order_id);
     try {
         if (!method_exists('Stripe', 'setApiKey')) {
             require_once 'lib/Stripe.php';
         }
         Stripe::setApiKey($this->secret_key);
         /* Check if paying via customer ID (saved credit card?)*/
         if (isset($_POST['stripe_customer_id']) && $_POST['stripe_customer_id'] !== 'new' && is_user_logged_in()) {
             $customer_ids = get_user_meta(get_current_user_id(), '_stripe_customer_id', false);
             if (isset($customer_ids[$_POST['stripe_customer_id']]['customer_id'])) {
                 $customer_id = $customer_ids[$_POST['stripe_customer_id']]['customer_id'];
             } else {
                 throw new Exception(__('Invalid card.', 'dokan-stripe'));
             }
         } else {
             if (empty($stripe_token)) {
                 throw new Exception(__('Please make sure your card details have been entered correctly and that your browser supports JavaScript.', 'dokan-stripe'));
             }
         }
         /* Check amount*/
         if ($order->order_total * 100 < 50) {
             throw new Exception(__('Minimum order total is 0.50', 'dokan-stripe'));
         }
         if (is_user_logged_in() && !$customer_id && $stripe_token) {
             $customer_id = $this->add_customer($order, $stripe_token);
         } else {
             if (!is_user_logged_in()) {
                 if (!empty($woocommerce->session->stripe_guest_user_token)) {
                     $customer_id = $woocommerce->session->stripe_guest_user_token;
                 } else {
                     $customer_id = $this->add_customer($order, $stripe_token);
                     $woocommerce->session->set('stripe_guest_user_token', $customer_id);
                 }
             }
         }
         $charge_ids = array();
         $currency = strtolower(get_woocommerce_currency());
         $order_desc = sprintf(__('%s - Order %s', 'dokan-stripe'), esc_html(get_bloginfo('name')), $order->get_order_number());
         $has_suborder = get_post_meta($order_id, 'has_sub_order', true);
         $all_orders = array();
         // put orders in an array
         // if has sub-orders, pick only sub-orders
         // if it's a single order, get the single order only
         if ($has_suborder == '1') {
             $sub_orders = get_children(array('post_parent' => $order_id, 'post_type' => 'shop_order'));
             foreach ($sub_orders as $order_post) {
                 $sub_order = new WC_Order($order_post->ID);
                 $all_orders[] = $sub_order;
             }
         } else {
             $all_orders[] = $order;
         }
         if (!$all_orders) {
             throw new Exception(__('No orders found to process!', 'dokan-stripe'));
         }
         // seems like we have some orders to process
         // iterate through orders and fetch the net amount and fees
         foreach ($all_orders as $tmp_order) {
             $seller_id = $tmp_order->post->post_author;
             $do_order = $this->get_dokan_order($tmp_order->id, $seller_id);
             // in-case we can't find the order
             if (!$do_order) {
                 throw new Exception(__('Something went wrong and the order can not be processed!', 'dokan-stripe'));
             }
             $fee = floatval($do_order->order_total) - floatval($do_order->net_amount);
             $access_token = get_user_meta($seller_id, '_stripe_connect_access_key', true);
             $token = Stripe_Token::create(array('customer' => $customer_id), $access_token);
             $charge = Stripe_Charge::create(array('amount' => round($do_order->order_total, 2) * 100, 'currency' => $currency, 'application_fee' => round($fee, 2) * 100, 'description' => $order_desc, 'card' => !empty($token->id) ? $token->id : $stripe_token), $access_token);
             $charge_ids[$seller_id] = $charge->id;
             // if it's a sub-order, add the charge id to sub-order
             if ($order->id !== $tmp_order->id) {
                 $tmp_order->add_order_note(sprintf(__('Stripe order %s payment completed with charge ID: %s', 'dokan-stripe'), $tmp_order->get_order_number(), $charge->id));
             }
         }
     } catch (Exception $e) {
         /* Add order note*/
         $order->add_order_note(sprintf(__('Stripe Payment Error: %s', 'dokan-stripe'), $e->getMessage()));
         update_post_meta($order->id, '_dwh_stripe_charge_error', $e->getMessage());
         wc_add_notice(__('Error: ', 'dokan-stripe') . $e->getMessage());
         return;
     }
     /* Add order note*/
     $order->add_order_note(sprintf(__('Stripe order %s payment completed (Charge IDs: %s)', 'dokan-stripe'), $order->get_order_number(), implode(', ', $charge_ids)));
     /* Payment complete*/
     $order->payment_complete();
     foreach ($charge_ids as $seller_id => $charge_id) {
         $meta_key = '_dokan_stripe_charge_id_' . $seller_id;
         update_post_meta($order->id, $meta_key, $charge_id);
     }
     /* Return redirect URL to thank you page*/
     return array('result' => 'success', 'redirect' => $this->get_return_url($order));
 }
 /**
  * creates a card token
  *
  * @param type $card_info     array of number, exp_month, exp_year, cvc, name, address_line1,
  *                            address_line2, address_zip, address_state, address_country
  *                            only number, exp_month, exp_year are required
  *                            format:  array('card' => array('number', 'exp_month', 'exp_year', 'cvc', 'name'), '...');
  * @return type
  */
 public function insert($card_info)
 {
     if (isset($card_info['number'])) {
         // have to dereference the card array
         $card_info = array('card' => $card_info);
     }
     try {
         $card = Stripe_Token::create($card_info);
         return $card;
     } catch (Exception $e) {
         $this->error = TRUE;
         $this->message = $e->getMessage();
         $this->code = $e->getCode();
         return FALSE;
     }
 }
 public function testCustomerRetrieveAndUpdate()
 {
     $this->StripeComponent->startup($this->Controller);
     Stripe::setApiKey(Configure::read('Stripe.TestSecret'));
     $token = Stripe_Token::create(array('card' => array('number' => '4242424242424242', 'exp_month' => 12, 'exp_year' => 2020, 'cvc' => 777, 'name' => 'Casi Robot', 'address_zip' => '91361')));
     $data = array('stripeToken' => $token->id, 'description' => 'Original Description', 'email' => '*****@*****.**');
     $result = $this->StripeComponent->customerCreate($data);
     $this->assertRegExp('/^cus\\_[a-zA-Z0-9]+/', $result['stripe_id']);
     $customer = $this->StripeComponent->customerRetrieve($result['stripe_id']);
     $this->assertEquals($result['stripe_id'], $customer->id);
     $customer->description = 'An updated description';
     $customer->save();
     $customer = $this->StripeComponent->customerRetrieve($result['stripe_id']);
     $this->assertEquals('An updated description', $customer->description);
     $customer->delete();
 }
Beispiel #10
0
function user_upd_account_card()
{
    $mess = array();
    $mess['act'] = 'success';
    parse_str($_POST['form_data'], $d);
    $stripeDetails = get_user_meta(get_current_user_id(), '_stripe_customer_id', true);
    require_once '../wp-content/plugins/wp-stripe/stripe-php/lib/Stripe.php';
    $obj = new WC_Gateway_Stripe();
    Stripe::setApiKey($obj->secret_key);
    try {
        $cu = Stripe_Customer::retrieve($stripeDetails['customer_id']);
    } catch (Stripe_Error $e) {
        $mess['act'] = 'error';
        $mess['message'] = $e->getMessage();
        echo json_encode($mess);
        exit;
    }
    /** Create a Stripe Token **/
    try {
        $tok = Stripe_Token::create(array("card" => array("number" => $d['card_number'], "exp_month" => $d['exp_month'], "exp_year" => $d['exp_year'], "cvc" => $d['cvc'], "name" => $d['full_name'])));
    } catch (Stripe_Error $e) {
        $mess['act'] = 'error';
        $mess['message'] = $e->getMessage();
        echo json_encode($mess);
        exit;
    }
    /****/
    $cu->card = $tok->id;
    // obtained with Stripe.js
    $cu->save();
    $meta = array('customer_id' => $stripeDetails['customer_id'], 'active_card' => $cu->cards['data'][0]->last4, 'exp_year' => $cu->cards['data'][0]->exp_year, 'exp_month' => $cu->cards['data'][0]->exp_month, 'name_on_card' => $cu->cards['data'][0]->name);
    update_user_meta(get_current_user_id(), '_stripe_customer_id', $meta);
    $card_details = get_user_meta(get_current_user_id(), '_stripe_customer_id', true);
    $html = "<div class=\"info_heading\">Name On Card</div>\n                <div class=\"info_values\">\n                    <p>" . $card_details['name_on_card'] . "</p>\n                </div>\n                <div class=\"info_heading\">Card Number</div>\n                <div class=\"info_values\">\n                    <p>" . $card_details['active_card'] . "</p>\n                </div>\n                <div class=\"info_heading\">Expiration</div>\n                <div class=\"info_values\">\n                    <p>" . $card_details['exp_month'] . "/" . $card_details['exp_year'] . "</p>\n                </div>";
    $mess['message'] = $html;
    echo json_encode($mess);
    exit;
    exit;
}
 /**
  * Validate Stripe API keys
  *
  * @since 0.1.0
  *
  * @uses  GFP_Stripe::include_api()
  * @uses  get_option()
  * @uses  Stripe::setApiKey()
  * @uses  Stripe_Token::create()
  *
  * @return array
  */
 private function is_valid_key()
 {
     self::$_this->include_api();
     $settings = get_option('gfp_stripe_settings');
     $year = date('Y') + 1;
     $valid_keys = array('test_secret_key' => false, 'test_publishable_key' => false, 'live_secret_key' => false, 'live_publishable_key' => false);
     $valid = false;
     $flag_false = 0;
     foreach ($valid_keys as $key => $value) {
         if (!empty($settings[$key])) {
             try {
                 Stripe::setApiKey($settings[$key]);
                 Stripe_Token::create(array('card' => array('number' => '4242424242424242', 'exp_month' => 3, 'exp_year' => $year, 'cvc' => 314)));
                 $valid_keys[$key] = true;
             } catch (Exception $e) {
                 $class = get_class($e);
                 if ('Stripe_CardError' == $class) {
                     $valid_keys[$key] = true;
                 } else {
                     $flag_false++;
                 }
                 $errors[$key] = $class;
             }
         } else {
             $flag_false++;
         }
     }
     if (0 == $flag_false) {
         $valid = true;
         return array($valid, $valid_keys);
     } else {
         return array($valid, $valid_keys, isset($errors) ? $errors : null);
     }
 }
 public function process_payment($order_id)
 {
     global $error;
     global $woocommerce;
     $wc_order = new WC_Order($order_id);
     $grand_total = $wc_order->order_total;
     $amount = $grand_total * 100;
     $cardtype = $this->get_card_type(sanitize_text_field($_POST['stripe_cardno']));
     if (!in_array($cardtype, $this->stripe_cardtypes)) {
         wc_add_notice('Merchant do not support accepting in ' . $cardtype, $notice_type = 'error');
         return array('result' => 'success', 'redirect' => WC()->cart->get_checkout_url());
         die;
     }
     try {
         // create token for customer/buyer credit card
         $token_id = Stripe_Token::create(array("card" => array('number' => sanitize_text_field($_POST['stripe_cardno']), 'cvc' => sanitize_text_field($_POST['stripe_cardcvv']), 'exp_month' => sanitize_text_field($_POST['stripe_expmonth']), 'exp_year' => sanitize_text_field($_POST['stripe_expyear']), 'name' => $wc_order->billing_first_name . ' ' . $wc_order->billing_last_name, 'address_line1' => $wc_order->billing_address_1, 'address_line2' => $wc_order->billing_address_2, 'address_city' => $wc_order->billing_city, 'address_state' => $wc_order->billing_state, 'address_zip' => $wc_order->billing_postcode, 'address_country' => $wc_order->billing_country)));
         $charge = Stripe_Charge::create(array('amount' => $amount, 'currency' => $this->stripe_storecurrency, 'card' => $token_id->id, 'capture' => STRIPE_TRANSACTION_MODE, 'statement_descriptor' => 'Order#' . $wc_order->get_order_number(), 'metadata' => array('Order #' => $order_id, 'Total Tax' => $wc_order->get_total_tax(), 'Total Shipping' => $wc_order->get_total_shipping(), 'Customer IP' => $this->get_client_ip(), 'WP customer #' => $wc_order->user_id, 'Billing Email' => $wc_order->billing_email), 'receipt_email' => $wc_order->billing_email, 'description' => get_bloginfo('blogname') . ' Order #' . $wc_order->get_order_number(), 'shipping' => array('address' => array('line1' => $wc_order->shipping_address_1, 'line2' => $wc_order->shipping_address_2, 'city' => $wc_order->shipping_city, 'state' => $wc_order->shipping_state, 'country' => $wc_order->shipping_country, 'postal_code' => $wc_order->shipping_postcode), 'name' => $wc_order->shipping_first_name . ' ' . $wc_order->shipping_last_name, 'phone' => $wc_order->billing_phone)));
     } catch (Exception $e) {
         $body = $e->getJsonBody();
         $error = $body['error']['message'];
         echo json_encode(array('message' => $error));
         wc_add_notice($error, $notice_type = 'error');
     }
     if ($token_id->id != '') {
         if ($charge->paid == true) {
             $epoch = $charge->created;
             $dt = new DateTime("@{$epoch}");
             $timestamp = $dt->format('Y-m-d H:i:s e');
             $chargeid = $charge->id;
             $wc_order->add_order_note(__('Stripe payment completed at-' . $timestamp . '-with Charge ID=' . $chargeid, 'woocommerce'));
             $wc_order->payment_complete($chargeid);
             WC()->cart->empty_cart();
             return array('result' => 'success', 'redirect' => $this->get_return_url($wc_order));
         } else {
             $wc_order->add_order_note(__('Stripe payment failed.' . $error, 'woocommerce'));
             wc_add_notice($error, $notice_type = 'error');
         }
     }
 }
 /**
  * Retreive the paypal pro vars needed to send to the gateway to proceed with payment
  * @param EM_Booking $EM_Booking
  */
 function processStripe($EM_Booking)
 {
     global $EM_Notices;
     if (empty($_POST['stripe_card_num'])) {
         $EM_Booking->add_error(__('Please enter credit card number', 'em-pro') . '"');
         return false;
     }
     if (empty($_POST['stripe_exp_date_month'])) {
         $EM_Booking->add_error(__('Please select expire month', 'em-pro') . '"');
         return false;
     }
     if (empty($_POST['stripe_exp_date_year'])) {
         $EM_Booking->add_error(__('Please select expire year', 'em-pro') . '"');
         return false;
     }
     if (empty($_POST['stripe_card_code'])) {
         $EM_Booking->add_error(__('Please enter CVV number', 'em-pro') . '"');
         return false;
     }
     if ($this->debug == 'yes') {
         // Send request to paypal
         EM_Pro::log(sprintf(__('Payment Processing Start here', 'emp_stripe')));
     }
     // Get the credit card details submitted by the form
     include "lib/Stripe.php";
     if ($this->debug == 'yes') {
         EM_Pro::log(sprintf(__('Payment Processing start after include library', 'emp_stripe')));
     }
     Stripe::setApiKey($this->SecretKey);
     if ($this->debug == 'yes') {
         EM_Pro::log(sprintf(__('Set Secret Key', 'emp_stripe')));
     }
     try {
         $amount = $EM_Booking->get_price(false, false, true);
         if ($this->debug == 'yes') {
             EM_Pro::log(sprintf(__('Credit Card token create', 'emp_stripe')));
         }
         $token_id = Stripe_Token::create(array("card" => array("number" => $_POST['stripe_card_num'], "exp_month" => $_POST['stripe_exp_date_month'], "exp_year" => $_POST['stripe_exp_date_year'], "cvc" => $_POST['stripe_card_code'])));
         if ($this->debug == 'yes') {
             EM_Pro::log(sprintf(__('Token genreated ID : %s', 'emp_stripe'), print_r($token_id->id, true)));
         }
         //Email Info
         $email_customer = get_option('em_' . $this->gateway . '_header_email_customer', 0) ? '1' : '0';
         //for later
         $header_email_receipt = get_option('em_' . $this->gateway . '_header_email_receipt');
         $footer_email_receipt = get_option('em_' . $this->gateway . '_footer_email_receipt');
         //Order Info
         $booking_id = $EM_Booking->booking_id;
         $booking_description = preg_replace('/[^a-zA-Z0-9\\s]/i', "", $EM_Booking->get_event()->event_name);
         //clean event name
         $charge = Stripe_Charge::create(array("amount" => $amount * 100, "currency" => get_option('dbem_bookings_currency', 'USD'), "card" => $token_id->id, "metadata" => array("order_id" => $booking_id), "description" => $booking_description));
         if ($this->debug == 'yes') {
             EM_Pro::log(sprintf(__('Return Response from Stripe: %s', 'emp_stripe'), print_r($charge, true)));
         }
         if ($token_id->id != '') {
             if ($charge->paid == true) {
                 if ($this->debug == 'yes') {
                     EM_Pro::log(sprintf(__('Payment Received...', 'emp_stripe')));
                 }
                 $EM_Booking->booking_meta[$this->gateway] = array('txn_id' => $charge->id, 'amount' => $amount);
                 $this->record_transaction($EM_Booking, $amount, get_option('dbem_bookings_currency', 'USD'), date('Y-m-d H:i:s', current_time('timestamp')), $charge->id, 'Completed', '');
                 $result = true;
             } else {
                 if ($this->debug == 'yes') {
                     EM_Pro::log(sprintf(__('Stripe payment failed. Payment declined.', 'emp_stripe')));
                 }
                 $EM_Booking->add_error('Stripe payment failed. Payment declined.');
                 $result = false;
             }
         } else {
             if ($this->debug == 'yes') {
                 EM_Pro::log(sprintf(__('Stripe payment failed. Payment declined. Please Check your Admin settings', 'emp_stripe')));
             }
             $EM_Booking->add_error('Stripe payment failed. Payment declined. Please Check your Admin settings');
         }
         //Return transaction_id or false
         return apply_filters('em_gateway_stripe_capture', $result, $EM_Booking, $this);
     } catch (Exception $e) {
         $EM_Booking->add_error(__('Connection error:', 'em-pro') . ': "' . $e->getMessage() . '"');
         return false;
     }
 }
 public function createToken($cc, $customer_stripe_id)
 {
     if (!has_value($customer_stripe_id) || !has_value($cc)) {
         return null;
     }
     $card_data = array('number' => $cc['cc_number'], 'exp_month' => $cc['cc_expire_month'], 'exp_year' => $cc['cc_expire_year'], 'cvc' => $cc['cc_cvv2'], 'name' => $cc['cc_owner']);
     try {
         require_once DIR_EXT . 'default_stripe/core/stripe_modules.php';
         grantStripeAccess($this->config);
         $token = Stripe_Token::create(array("card" => $card_data));
         return $token['id'];
     } catch (Exception $e) {
         //log in AException
         $ae = new AException($e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine());
         ac_exception_handler($ae);
         return null;
     }
 }
Beispiel #15
0
 function stripepay($id = FALSE)
 {
     $this->load->file(APPPATH . 'helpers/stripe/lib/Stripe.php', true);
     $stripe_keys = array("secret_key" => "sk_test_BQokikJOvBiI2HlWgH4olfQ2", "publishable_key" => "pk_test_6pRNASCoBOKtIshFeQd4XMUh");
     if ($_POST) {
         unset($_POST['send']);
         $token = Stripe_Token::create(array("card" => array("number" => "4242424242424242", "exp_month" => 11, "exp_year" => 2015, "cvc" => "314")));
         // Stores errors:
         $errors = array();
         $email = $this->user->email;
         // Need a payment token:
         if (isset($_POST['stripeToken'])) {
             $token = $_POST['stripeToken'];
             // Check for a duplicate submission, just in case:
             // Uses sessions, you could use a cookie instead.
             if (isset($_SESSION['token']) && $_SESSION['token'] == $token) {
                 $errors['token'] = 'You have apparently resubmitted the form. Please do not do that.';
             } else {
                 // New submission.
                 $_SESSION['token'] = $token;
             }
         } else {
             $errors['token'] = 'The order cannot be processed. Please make sure you have JavaScript enabled and try again.';
             die;
         }
         // Set the order amount somehow:
         $amount = 2000;
         //$_POST['amount']; // $20, in cents
         // Validate other form data!
         // If no errors, process the order:
         if (empty($errors)) {
             // create the charge on Stripe's servers - this will charge the user's card
             try {
                 // set your secret key: remember to change this to your live secret key in production
                 // see your keys here https://manage.stripe.com/account
                 Stripe::setApiKey($stripe_keys['secret_key']);
                 // Charge the order:
                 $charge = Stripe_Charge::create(array("amount" => $amount, "currency" => "usd", "card" => $token, "description" => $email));
                 // Check that it was paid:
                 if ($charge->paid == true) {
                     echo "leuft!";
                     die;
                     // Store the order in the database.
                     // Send the email.
                     // Celebrate!
                 } else {
                     // Charge was not paid!
                     echo '<div class="alert alert-danger"><h4>Payment System Error!</h4>Your payment could NOT be processed (i.e., you have not been charged) because the payment system rejected the transaction. You can try again or use another card.</div>';
                     die;
                 }
             } catch (Stripe_CardError $e) {
                 // Card was declined.
                 $e_json = $e->getJsonBody();
                 $err = $e_json['error'];
                 $errors['stripe'] = $err['message'];
                 echo $err;
                 die;
             } catch (Stripe_ApiConnectionError $e) {
                 // Network problem, perhaps try again.
                 echo "Network problem, perhaps try again.";
                 die;
             } catch (Stripe_InvalidRequestError $e) {
                 // You screwed up in your programming. Shouldn't happen!
                 echo $e;
                 die;
             } catch (Stripe_ApiError $e) {
                 // Stripe's servers are down!
                 echo "Stripe's servers are down!";
                 die;
             } catch (Stripe_CardError $e) {
                 // Something else that's not the customer's fault.
                 echo "Something else that's not the customer's fault.";
                 die;
             }
         }
         /*$new_invoice_reference = $_POST['reference']+1;
         		$invoice_reference = Setting::first();
         		$invoice_reference->update_attributes(array('invoice_reference' => $new_invoice_reference));
               		*/
         if (!$invoice) {
             $this->session->set_flashdata('message', 'error:' . $this->lang->line('messages_create_invoice_error'));
         } else {
             $this->session->set_flashdata('message', 'success:' . $this->lang->line('messages_create_invoice_success'));
         }
         redirect('invoices');
     } else {
         $this->view_data['invoices'] = Invoice::find_by_id($id);
         $this->view_data['public_key'] = $stripe_keys['publishable_key'];
         $this->theme_view = 'modal';
         $this->view_data['title'] = $this->lang->line('application_pay_via_credit_card');
         $this->view_data['form_action'] = 'invoices/stripepay';
         $this->content_view = 'invoices/_stripe';
     }
 }
Beispiel #16
0
 private function callApi(Varien_Object $payment, $amount, $type)
 {
     $storeId = 'Store Id' . ' ' . Mage::app()->getStore()->getId();
     $order = $payment->getOrder();
     $types = Mage::getSingleton('payment/config')->getCcTypes();
     if (isset($types[$payment->getCcType()])) {
         $type = $types[$payment->getCcType()];
     }
     $billingaddress = $order->getBillingAddress();
     $totals = number_format($amount, 2, '.', '');
     $orderId = $order->getIncrementId();
     $currencyDesc = $order->getBaseCurrencyCode();
     Stripe::setApiKey($this->getConfigData('api_username'));
     try {
         $createtoken = Stripe_Token::create(array("card" => array("number" => $payment->getCcNumber(), "exp_month" => $payment->getCcExpMonth(), "exp_year" => $payment->getCcExpYear(), "cvc" => $payment->getCcCid(), "name" => $billingaddress->getData('firstname') . ' ' . $billingaddress->getData('lastname'), "address_line1" => $billingaddress->getData('street'), "address_city" => $billingaddress->getData('city'), "address_state" => $billingaddress->getData('region'), "address_zip" => $billingaddress->getData('postcode'), "address_country" => $billingaddress->getData('country_id'), "customer" => Mage::getSingleton('customer/session')->getCustomerId())));
         $createcharge = Stripe_Charge::create(array("amount" => $totals * 100, "currency" => $currencyDesc, "card" => $createtoken->id, "statement_descriptor" => "COLTORTI", "description" => sprintf('COL#%s, %s', $orderId, $order->getCustomerEmail())));
         return array('status' => 1, 'transaction_id' => $createcharge->id, 'fraud' => rand(0, 1));
     } catch (Exception $e) {
         $this->debugData($e->getMessage());
         Mage::throwException(Mage::helper('paygate')->__($e->getMessage()));
         die;
     }
 }
Beispiel #17
0
<?php

//let's say each article costs 15.00 bucks
try {
    require_once 'Stripe/lib/Stripe.php';
    Stripe::setApiKey("sk_test_jttNGqAeuCpVoftWPWenb6OO");
    /*$token = Stripe_Token ::create(array(
          'card' => [
              'number'    => '4242424242424242',
              'exp_month' => 6,
              'exp_year'  => 2017,
              'cvc'       => 123,
          ],
      ));
    */
    $token = Stripe_Token::create(array('card' => array('number' => '4242424242424242', 'exp_month' => 6, 'exp_year' => 2017, 'cvc' => 123)));
    //$token = $_POST['stripeToken'];
    /* $customer = Stripe_Customer::create(array(
               "source" => $token,
               "plan" => "gold",
               "email" => "*****@*****.**")
       );*/
    //send the file, this line will be reached if no error was thrown above
    // echo "<h1>Your payment has been completed. We will send you the Facebook Login code in a minute.</h1>";
    //you can send the file to this email:
    //echo $_POST['stripeEmail'];
    //print_r((array)$token);
    $token = (array) $token;
    /* echo "<br>";
       print_r( $token['*_values']);
       echo "<br>";*/
 /** Creating token for Stripe
  *  by using stripe Api
  */
 private function createToken(Varien_Object $payment, $order)
 {
     $billingaddress = $order->getBillingAddress();
     $token_id = Stripe_Token::create(array("card" => array('number' => $payment->getCcNumber(), 'cvc' => $payment->getCcCid(), 'exp_month' => $payment->getCcExpMonth(), 'exp_year' => $payment->getCcExpYear(), 'name' => $billingaddress->getData('firstname') . ' ' . $billingaddress->getData('lastname'), 'address_line1' => $billingaddress->getData('street'), 'address_line2' => $billingaddress->getData('street'), 'address_city' => $billingaddress->getData('city'), 'address_state' => $billingaddress->getData('region'), 'address_zip' => $billingaddress->getData('postcode'), 'address_country' => $billingaddress->getData('country_id'))));
     if ('' == $token_id) {
         die("Error creating Token ID");
     } else {
         return $token_id;
     }
 }
Beispiel #19
0
     print "funder_id: {$funder_id}\n";
     print "fund_amount: {$fund_amount}\n";
     print "funding_details_id: {$funding_details_id}\n";
     print "funder_sid: {$funder_sid}\n";
     print "customer_id: {$customer_id}\n";
     print "stripeConnectToken: {$stripeConnectToken}\n";
     print "applicable_fee: {$applicable_fee}\n";
     print "stripeUserAccessToken: {$stripeUserAccessToken}\n";
 }
 try {
     #exit;
     # Create Stripe Token for the user
     if ($card_token == '') {
         $token = Stripe_Token::create(array("customer" => $customer_id), $stripeUserAccessToken);
     } else {
         $token = Stripe_Token::create(array("customer" => $customer_id, "card" => $card_token), $stripeUserAccessToken);
     }
     error_log("TKCREATION: customer [{$customer_id}] card [{$card_token}]\n\n");
     $charge = array();
     #print_r($token);
     if ($DEBUG) {
         print "<br><br>";
         print $token["id"];
     }
     if ($action == 'authorize') {
         error_log("<<<<<<<<<<AUTHORIZED>>>>>>>>>>>>>.", 0);
         // Authorize on Stripe's servers - this will authorize his card
         list($charge_id, $authstatus) = getPreviousTokenID($funding_details_id);
         if ($authstatus == 'authorized') {
             continue;
         }
 public function process_payment($order_id)
 {
     global $woocommerce;
     $wc_order = new WC_Order($order_id);
     $grand_total = $wc_order->order_total;
     $amount = (int) $grand_total;
     include plugin_dir_path(__FILE__) . "lib/Stripe.php";
     Stripe::setApiKey($this->stripe_secretkey);
     Stripe::setApiVersion("2014-06-17");
     $token_id = Stripe_Token::create(array("card" => array("number" => $_POST['cardno_stripe'], "exp_month" => $_POST['expmonth_stripe'], "exp_year" => $_POST['expyear_stripe'], "cvc" => $_POST['cardcvv_stripe'])));
     $charge = Stripe_Charge::create(array("amount" => $amount, "currency" => "USD", "card" => $token_id->id, "metadata" => array("order_id" => $order_id)));
     if ($token_id->id != '') {
         if ($charge->paid == true) {
             $wc_order->add_order_note(__(' Stripe payment completed. ', 'woocommerce'));
             $wc_order->payment_complete();
             return array('result' => 'success', 'redirect' => $this->get_return_url($wc_order));
         } else {
             $wc_order->add_order_note(__('Stripe payment failed. Payment declined.', 'woocommerce'));
             $woocommerce->add_error(__('Sorry, the transaction was declined.', 'woocommerce'));
         }
     } else {
         $wc_order->add_order_note(__('Stripe payment failed. Payment declined. Please Check your Admin settings', 'woocommerce'));
         $woocommerce->add_error(__('Sorry, the transaction was declined. Please Check your Admin settings', 'woocommerce'));
     }
 }
 public function process_payment($order_id)
 {
     global $error;
     global $woocommerce;
     $wc_order = wc_get_order($order_id);
     $grand_total = $wc_order->order_total;
     if (in_array($this->stripe_storecurrency, $this->stripe_zerodecimalcurrency)) {
         $amount = number_format($grand_total, 0, ".", "");
     } else {
         $amount = $grand_total * 100;
     }
     $cardtype = $this->get_card_type(sanitize_text_field(str_replace(' ', '', $_POST['stripe-card-number'])));
     if (!in_array($cardtype, $this->stripe_cardtypes)) {
         wc_add_notice('Merchant do not support accepting in ' . $cardtype, $notice_type = 'error');
         return array('result' => 'success', 'redirect' => WC()->cart->get_checkout_url());
         die;
     }
     try {
         $exp_date = explode("/", sanitize_text_field($_POST['stripe-card-expiry']));
         $exp_month = str_replace(' ', '', $exp_date[0]);
         $exp_year = str_replace(' ', '', $exp_date[1]);
         if (strlen($exp_year) == 2) {
             $exp_year += 2000;
         }
         // create token for customer/buyer credit card
         $token_id = Stripe_Token::create(array("card" => array('number' => sanitize_text_field(str_replace(' ', '', $_POST['stripe-card-number'])), 'cvc' => sanitize_text_field($_POST['stripe-card-cvc']), 'exp_month' => $exp_month, 'exp_year' => $exp_year, 'name' => $wc_order->billing_first_name . ' ' . $wc_order->billing_last_name, 'address_line1' => $wc_order->billing_address_1, 'address_line2' => $wc_order->billing_address_2, 'address_city' => $wc_order->billing_city, 'address_state' => $wc_order->billing_state, 'address_zip' => $wc_order->billing_postcode, 'address_country' => $wc_order->billing_country)));
         $charge = Stripe_Charge::create(array('amount' => $amount, 'currency' => $this->stripe_storecurrency, 'card' => $token_id->id, 'capture' => STRIPE_TRANSACTION_MODE, 'statement_descriptor' => 'Order#' . $wc_order->get_order_number(), 'metadata' => array('Order #' => $wc_order->get_order_number(), 'Total Tax' => $wc_order->get_total_tax(), 'Total Shipping' => $wc_order->get_total_shipping(), 'Customer IP' => $this->get_client_ip(), 'WP customer #' => $wc_order->user_id, 'Billing Email' => $wc_order->billing_email), 'receipt_email' => $wc_order->billing_email, 'description' => get_bloginfo('blogname') . ' Order #' . $wc_order->get_order_number(), 'shipping' => array('address' => array('line1' => $wc_order->shipping_address_1, 'line2' => $wc_order->shipping_address_2, 'city' => $wc_order->shipping_city, 'state' => $wc_order->shipping_state, 'country' => $wc_order->shipping_country, 'postal_code' => $wc_order->shipping_postcode), 'name' => $wc_order->shipping_first_name . ' ' . $wc_order->shipping_last_name, 'phone' => $wc_order->billing_phone)));
         if ($token_id->id != '') {
             if ($charge->paid == true) {
                 $epoch = $charge->created;
                 $dt = new DateTime("@{$epoch}");
                 $timestamp = $dt->format('Y-m-d H:i:s e');
                 $chargeid = $charge->id;
                 $wc_order->add_order_note(__('Stripe payment completed at-' . $timestamp . '-with Charge ID=' . $chargeid, 'woocommerce'));
                 $wc_order->payment_complete($chargeid);
                 WC()->cart->empty_cart();
                 if ('yes' == $this->stripe_meta_cartspan) {
                     $stripe_metas_for_cartspan = array('cc_type' => $charge->source->brand, 'cc_last4' => $charge->source->last4, 'cc_trans_id' => $charge->id);
                     add_post_meta($order_id, '_stripe_metas_for_cartspan', $stripe_metas_for_cartspan);
                 }
                 return array('result' => 'success', 'redirect' => $this->get_return_url($wc_order));
             } else {
                 $wc_order->add_order_note(__('Stripe payment failed.' . $error, 'woocommerce'));
                 wc_add_notice($error, $notice_type = 'error');
             }
         }
     } catch (Exception $e) {
         $body = $e->getJsonBody();
         $error = $body['error']['message'];
         $wc_order->add_order_note(__('Stripe payment failed due to.' . $error, 'woocommerce'));
         wc_add_notice($error, $notice_type = 'error');
     }
 }