public function process_payment($order_id) { global $error; global $woocommerce; global $ss_wc_process; // for add_filter on process_payment call $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; } $card_number = sanitize_text_field(str_replace(' ', '', $_POST['stripe-card-number'])); $cvc = sanitize_text_field($_POST['stripe-card-cvc']); $expiry = sanitize_text_field($_POST['stripe-card-expiry']); $cardtype = $card_number ? $this->get_card_type($card_number) : ''; $current_user = wp_get_current_user(); $customerID = get_post_meta($current_user->ID, 'customer_id', true); if (!$card_number || !$expiry || !$cvc) { // add check for which field, and add that to the message wc_add_notice('Please fill out all credit card fields.', $notice_type = 'error'); return; } if (!in_array($cardtype, $this->stripe_cardtypes)) { wc_add_notice('Merchant does not support accepting in ' . $cardtype, $notice_type = 'error'); // return; return array('result' => 'success', 'redirect' => WC()->cart->get_checkout_url()); die; } try { $exp_date = explode("/", $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 = \Stripe\Token::create(array("card" => array('number' => $card_number, 'cvc' => $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))); // if create customer option is true, then create customer if no $customerID has been set - else, charge the card now if ($this->stripe_create_customer) { // check if user already has a customer ID // if they dont, create customer if (empty($customerID)) { // Create a Customer $customer = \Stripe\Customer::create(array('email' => $wc_order->billing_email, 'source' => $token, 'description' => $current_user->first_name . ' ' . $current_user->last_name)); // save customer_id for current user meta update_post_meta($current_user->ID, 'customer_id', $customer->id); // set fingerprint of token/card update_post_meta($current_user->ID, 'fingerprint', $token->card->fingerprint); } else { // add check here if card entered is different than whats tied to the customer, and if it is - add it or replace current card? then update customer on stripe with new card(s) // \Stripe\Stripe::setApiKey("sk_test_2DcoV11I0PQl4ygpFUuuQOMa"); // $customer = \Stripe\Customer::retrieve("cus_79WdM0loJvSuyF"); // $card = $customer->sources->retrieve($customer->default_source); // $token = \Stripe\Token::retrieve("tok_16vDXxDSe6V7KL4aZQuvqR8n"); // sp($token->card->fingerprint); // sp($card->fingerprint); // sp($card); // set fingerprint post meta on user from card/token if ($token->card->fingerprint != get_post_meta($current_user->ID, 'fingerprint', true)) { $cu = \Stripe\Customer::retrieve($customerID); // update customer card to the one just entered $cu->source = $token; $cu->save(); update_post_meta($current_user->ID, 'fingerprint', $token->card->fingerprint); } } } else { $charge = \Stripe\Charge::create(array('amount' => $amount, 'currency' => $this->stripe_storecurrency, 'card' => $token, '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(), '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 card valid, and if charge paid, add note of payment completion, empty cart, and redirect to order summary - else error notice if ($token != '') { // if creating a customer, set payment_complete to customerID and allow for filtering, else set to card charge id if ($this->stripe_create_customer) { // hookable filter to set status of order before payment is triggered on woocommerce_order_status_processing $ss_wc_process_payment = apply_filters('ss_process_payment', $ss_wc_process, $order_id); // checking against null values if no add_filter used to hook in // process charges immediately if no filter if ($ss_wc_process_payment || is_null($ss_wc_process_payment)) { $wc_order->payment_complete($customerID); } else { // set to on-hold rather than default pending status $wc_order->update_status('on-hold'); } } else { $wc_order->payment_complete($charge->id); } WC()->cart->empty_cart(); return array('result' => 'success', 'redirect' => $this->get_return_url($wc_order)); } } 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'); } }
protected function getTestToken() { return Token::create(['card' => ['number' => '4242424242424242', 'exp_month' => 5, 'exp_year' => 2020, 'cvc' => '123']], ['api_key' => getenv('STRIPE_SECRET')])->id; }
function card_token($data) { $this->set_api_key(); $token = \Stripe\Token::create(array("card" => array("number" => $data['cc']['number'], "exp_month" => $data['cc']['exp']['month'], "exp_year" => $data['cc']['exp']['year'], "cvc" => $data['cc']['cvc']))); return $token; }
function updateCustomer($custem_id) { try { $result = \Stripe\Token::create(array("card" => array("number" => "4242424242424242", "exp_month" => 10, "exp_year" => 2016, "cvc" => "314"))); $cu = \Stripe\Customer::retrieve($custem_id); $cu->source = $result->id; // obtained with Stripe.js $cu->save(); } catch (Exception $e) { $error = $e->getMessage(); echo $error; } }
public function getStripeToken() { Stripe::setApiKey(\Config::get('stripe.key')); try { $stripeToken = StripeToken::create(["card" => ["number" => "4000056655665556", "exp_month" => 12, "exp_year" => 2016, "cvc" => "314", "currency" => "usd"]]); return $stripeToken->id; } catch (StripeError\Base $e) { return $this->sendBackJsonError($e->getHttpStatus()); } }
/** * create token by using card information, you can also create via stripe.js * * @param array array of credit/debit card information * @return response in json format */ function createToken($myCard) { $this->setApiKey(); // below code for create a token $token = \Stripe\Token::create(array("card" => $myCard)); return $token; }
public function testUserToCustomerConvertion() { $mock = $this->getMockForTrait('Biller\\Behavior\\IsCustomer'); $mock->id = 1; $mock->email = '*****@*****.**'; $token = \Stripe\Token::create(['card' => ['number' => '4242424242424242', 'exp_month' => 5, 'exp_year' => date('Y') + 3, 'cvc' => '314']]); $this->assertInstanceOf('Stripe\\Customer', static::$mock->toCustomer($token->id)); }
/** * @param $stripeToken * @param $apiPrivKey * @return StripeTokenMock|Token */ function tokenRetrieve($stripeToken, $apiPrivKey) { if (self::$testMode) { return StripeTokenMock::retrieve($stripeToken, $apiPrivKey); } else { return Token::retrieve($stripeToken, $apiPrivKey); } }
/** * {@inheritDoc} */ public function execute($request) { /** @var $request CreateToken */ RequestNotSupportedException::assertSupports($this, $request); $model = ArrayObject::ensureArrayObject($request->getModel()); try { Stripe::setApiKey($this->keys->getSecretKey()); $token = Token::create($model->toUnsafeArrayWithoutLocal()); $model->replace($token->__toArray(true)); } catch (Error\Base $e) { $model->replace($e->getJsonBody()); } }
protected function collectOneTimePayment($token, $amount) { Stripe::setApiKey(config('services.stripe.secret')); $user = Auth::user(); $customer = Customer::create(['source' => $token, 'email' => $user->email, 'description' => 'Pre-launch customer']); Charge::create(['amount' => $amount, 'currency' => 'usd', 'customer' => $customer->id]); /* * Save the strip_id and card details to the DB. */ $tokenDetails = Token::retrieve($token); $user->stripe_id = $customer->id; $user->card_brand = $tokenDetails->card->brand; $user->card_last_four = $tokenDetails->card->last4; $user->save(); }
public function submitOrder($short_name) { $university = $this->university->where('short_name', $short_name)->first(); $firstName = $this->request->input('first_name', ''); $lastName = $this->request->input('last_name', ''); $emainAddress = $this->request->input('email_address', ''); $customer = $this->customer->where('first_name', $firstName)->where('last_name', $lastName)->where('email_address', $emainAddress)->first(); $customerId; if ($customer === null) { //This customer is new $this->customer->fill($this->request->all())->save(); $customerId = $this->customer->id; } else { $this->customer->find($customer->id)->fill($this->request->all())->save(); $customerId = $customer->id; } $totalPrice = $this->request->input('totalPrice', ''); $orderId = $this->order->insertGetId(['customer_id' => $customerId, 'payment' => $this->request->input('payment', ''), 'order_status' => "initialized", 'street_address1' => $this->request->input('street_address1', ''), 'street_address2' => $this->request->input('street_address2', ''), 'city' => $this->request->input('city', ''), 'post_code' => $this->request->input('post_code', ''), 'country' => $this->request->input('country', ''), 'created_at' => \Carbon\Carbon::now()->toDateTimeString(), 'total_price' => $totalPrice]); $itemsInCart = $this->cart->where('customer_id', $this->request->cookie('customer_id'))->get(); foreach ($itemsInCart as $item) { $this->orderitem->insert(['order_id' => $orderId, 'product_id' => $item->product_id, 'created_at' => \Carbon\Carbon::now()->toDateTimeString(), 'price' => $item->price]); $cart = $this->cart->find($item->id); $cart->order_id = $orderId; $cart->save(); } $temporaryCustomerId = $this->request->cookie('customer_id'); $allProductsInCart = $this->getAllProductsInCart($temporaryCustomerId); $allProductsInCart = $this->convertProductsForCheckout($allProductsInCart); \Stripe\Stripe::setApiKey("sk_test_I561ILtdEXsIVDoAc9169tcC"); $transactionInformation = \Stripe\Charge::all(); $transactionId = $transactionInformation->data[0]->id; $token = $this->request->input('stripeToken', ''); $tokenInformation = \Stripe\Token::retrieve($token); $chargeInformation = \Stripe\Charge::retrieve($transactionId); //dd($transactionInformation); try { $charge = \Stripe\Charge::create(array("amount" => bcmul($totalPrice, 100), "currency" => "aud", "source" => $token, "description" => "Example charge")); $type = $tokenInformation->type; $clientIp = $tokenInformation->client_ip; $createdTime = $chargeInformation->created; $country = $chargeInformation->source->country; $expMonth = $chargeInformation->source->exp_month; $expYear = $chargeInformation->source->exp_year; $brand = $chargeInformation->source->brand; $last4CardNumber = $chargeInformation->source->last4; $paymentResponse = json_encode(array('type' => $type, 'client_ip' => $clientIp, 'created' => $createdTime, 'country' => $country, 'expMonth' => $expMonth, 'expYear' => $expYear, 'brand' => $brand, 'last4CardNumber' => $last4CardNumber)); $transactionId = \Stripe\Charge::all()->data[0]->id; $order = $this->order->find($orderId); $order->transaction_id = $transactionId; $order->order_status = "paid"; $order->payment_response = $paymentResponse; $order->save(); $shippingFee = $this->request->input('shipping_fee', ''); $this->sendConfirmationMail($customerId, $allProductsInCart, $totalPrice, $shippingFee); foreach ($allProductsInCart as $productInCart) { $product = $this->product->find($productInCart['id']); $product->stock -= $productInCart['quantity']; $product->save(); if ($product->stock < 0) { $this->sendStockShortageNotification($product, $orderId); $order->order_status = "out_of_stock"; $order->save(); } } foreach ($itemsInCart as $item) { $this->cart->destroy($item->id); } return view('www.orderSubmitted', ['template' => $university->template, 'basket' => $this->getTheNumberOfItems(), 'products' => $allProductsInCart, 'totalPrice' => $totalPrice, 'shippingFee' => $shippingFee, 'headerLinks' => $this->headerPages, 'footerLinks' => $this->footerPages]); } catch (\Stripe\Error\Card $e) { $type = $tokenInformation->type; $clientIp = $tokenInformation->client_ip; $createdTime = $chargeInformation->created; $country = $chargeInformation->source->country; $expMonth = $chargeInformation->source->exp_month; $expYear = $chargeInformation->source->exp_year; $brand = $chargeInformation->source->brand; $last4CardNumber = $chargeInformation->source->last4; $failureCode = $chargeInformation->failure_code; $failureMessage = $chargeInformation->failure_message; $paymentResponse = json_encode(array('type' => $type, 'client_ip' => $clientIp, 'created' => $createdTime, 'country' => $country, 'expMonth' => $expMonth, 'expYear' => $expYear, 'brand' => $brand, 'last4CardNumber' => $last4CardNumber, 'failureCode' => $failureCode, 'failureMessage' => $failureMessage)); $order = $this->order->find($orderId); $order->order_status = "failed"; $order->payment_response = $paymentResponse; $order->save(); include 'countries.php'; $isShipping = false; foreach ($allProductsInCart as $productInCart) { if ($productInCart['is_shipping'] === "Yes" && $isShipping === false) { $isShipping = true; } } $domesticShippingFee = $this->setting->where('key', 'domesticShippingFee')->first(); $domesticShippingFee = json_decode($domesticShippingFee->json)->data; $overseasShippingFee = $this->setting->where('key', 'overseasShippingFee')->first(); $overseasShippingFee = json_decode($overseasShippingFee->json)->data; $message = "Unfortunately, the submission has been failed :" . $failureCode; return view('www.checkout', ['template' => $university->template, 'universityShortName' => $short_name, 'basket' => $this->getTheNumberOfItems(), 'products' => $allProductsInCart, 'totalPrice' => $totalPrice, 'countries' => $countries, 'is_shipping' => $isShipping, 'domesticShippingFee' => $domesticShippingFee, 'overseasShippingFee' => $overseasShippingFee, 'message' => $message, 'headerLinks' => $this->headerPages, 'footerLinks' => $this->footerPages]); } }
/** * Update customer's credit card. * * @param string $token */ public function updateCard($token) { $customer = $this->asStripeCustomer(); $token = Token::retrieve($token, ['api_key' => $this->getStripeKey()]); // If the given token already has the card as their default source, we can just // bail out of the method now. We don't need to keep adding the same card to // the user's account each time we go through this particular method call. if ($token->card->id === $customer->default_source) { return; } $card = $customer->sources->create(['source' => $token]); $customer->default_source = $card->id; $customer->save(); // Next, we will get the default source for this user so we can update the last // four digits and the card brand on this user record in the database, which // is convenient when displaying on the front-end when updating the cards. $source = $customer->default_source ? $customer->sources->retrieve($customer->default_source) : null; $this->fillCardDetails($source); $this->save(); }
public function testUrls() { $this->assertEqual(Token::classUrl('Stripe_Token'), '/tokens'); $token = new Token('abcd/efgh'); $this->assertEqual($token->instanceUrl(), '/tokens/abcd%2Fefgh'); }
/** * Get the country code for the given Stripe token. * * @param string $token * @return string */ public function countryForToken($token) { return StripeToken::retrieve($token, config('services.stripe.secret'))->card->country; }