Omnipay token billing not working with stripe - php

I am using ignited/laravel-omnipay package for omnipay in laravel.
I am trying to implement token billing using stripe as shown here https://github.com/thephpleague/omnipay#token-billing.
Customer are getting created successfully on stripe but i am not able to make payment with the returned customer id.
Here's my code
$token = Input::get('stripetoken');
$gateway = Omnipay::create('Stripe');
$gateway->setApiKey('My Key');
$gateway->setTestMode(true);
$cardresponse = $gateway->createCard(array('token' =>$token))->send();
if ($cardresponse->isSuccessful()) {
$card_id = $cardresponse->getCardReference();
$data = $cardresponse->getData();
$customerid = $data['id'];
$cardid = $data['default_source'];
}
$paymentresponse = $gateway->purchase(array('amount' => '10.00','currency' => 'USD', 'cardReference' => $card_id))->send();
echo $paymentresponse->getMessage();
I am getting following response.
No such token: cus_8FwPaLNKdWcfRW
And when i check my stripe dashboard then customer with this id exists and has a card assigned.
Thanks for helping.

Since you're creating a customer object, you need to update your charge creation request to pass the customer ID in the customer parameter rather than in the source parameter (which causes the error you're seeing).
I'm not familiar with Omnipay but I think this should work:
$paymentresponse = $gateway->purchase(array('amount' => '10.00','currency' => 'USD', 'customerReference' => $card_id))->send();

Related

Stripe : Add new card to already created customer

I have a stripe customer already added, I am figuring out to add new card to customer. I searched around but couldn't found anything confirmed to asnwer my following questions.
Do stripe have any form of their own to add new card ?
Is following is the correct way to add new card ?
$customer = \Stripe\Customer::retrieve(Auth::user()->stripe_key);
// Got the customer details successfully from the above call.
$card = $customer->cards->create(
array(
"card" =>
array(
"number"=> "4242424242424242",
"exp_month" => "12",
"exp_year" => "2016",
"cvc" => "123"
)
)
);
Stripe does not have a direct form specifically for adding a new card to a customer, however you can use Checkout or Elements to collect the customer's card details.
The process for adding a new card to a customer would be as follows:
Collect and tokenize the customer's card details using Checkout or Elements[0]. This will give you a Stripe token representing the card.
Send this token to your backend, where you can use something similar to the following code to save the card to the customer:
$token = $_POST['stripeToken']; #for example
$customer = \Stripe\Customer::retrieve(Auth::user()->stripe_key);
$customer->sources->create(array("source" => $token));
[0] - https://stripe.com/docs/checkout or https://stripe.com/docs/stripe-js/elements/quickstart
[1] - https://stripe.com/docs/api/php#create_card

Stripe Checkout - Subscription Issue with Recognized Stripe User

I have Stripe working great. Upon a customer's donation, a new Subscription is created, and it works great - except if Stripe recognizes the email and says, "Enter the verification code."
If the customer does that, for some reason, a new subscription is not created and the customer is not charged.
Here is my charge-monthly.php
<?php
require_once('init.php');
// Set your secret key: remember to change this to your live secret key in production
// See your keys here https://dashboard.stripe.com/account/apikeys
\Stripe\Stripe::setApiKey("sk_test_**************");
// Get the credit card details submitted by the form
$token = $_POST['stripeToken'];
$email = $_POST['stripeEmail'];
$amount = $_POST['amount'];
$finalamount = $amount * 100;
$dollars = ".00";
$plan = "/month";
$dash = " - ";
$monthlyplan = $amount .$dollars .$plan .$dash .$email;
//Create monthly plan
$plan = \Stripe\Plan::create(array(
"name" => $monthlyplan,
"id" => $monthlyplan,
"interval" => "month",
"currency" => "usd",
"amount" => $finalamount,
));
// Create a Customer
$customer = \Stripe\Customer::create(array(
"source" => $token,
"description" => "MONTHLY DONATION",
"plan" => $monthlyplan,
"email" => $email, )
);
?>
Any ideas why when Stripe recognizes the user and he is "logged in" it does not allow me to create a subscription?
In the Stripe log, I receive this 400 error:
{
"error": {
"type": "invalid_request_error",
"message": "Plan already exists."
}
}
But there definitely isn't a plan created... ah!
The reason your request is failing is because if a user comes back with the same email address and wants to sign up for the same plan, you already have an existing plan with that name,
$monthlyplan = $amount .$dollars .$plan .$dash .$email;
so your call to \Stripe\Plan::create will return an error and cause the rest of your calls to fail here.
You could add something like a unique id or time to your plan id.
http://php.net/manual/en/function.time.php
http://php.net/manual/en/function.uniqid.php
Some other ways that folks typically handle this are:
Create a single plan for $1, and then adjust the quantity when creating your subscription. So a monthly plan for $1 with quantity of 100, would charge $100 month.
Store the amount that a customer will pay within your application. Subscribe your customers to a $0/month plan. Use webhooks to listen for invoice.created events. Have your webhook handler add an Invoice Item every month for the balance.

How to add multiple cards in same customer in stripe payment gateway using php

i was implementing stripe payment in testing mode.Here i got an error like Same token is used again. is there any different way to add multiple cards.
or i need to call retrive function in a separate page so that conflict of same token never come again.And how should i set a card default.
public function createToken($data)
{
$TokenResult=Token::create(array(
"card" => array(
"name" => $data['name'],
"number" => $data['card_number'],
"exp_month" => $data['month'],
"exp_year" => $data['year'],
"cvc" => $data['cvc']
)));
//echo "<pre>";;
//print_r($TokenResult);
$this->token=$TokenResult['id'];//store token id into token variable
$this->chargeCard($this->token); //call chargecard function via passing token id
}
/*
* function to create customer
*/
public function createCustomer($data,$token=null)//pass form data and token id
{
$customer=Customer::create(array(
"email"=>$data['email'],
"description" => $data['name'],
"source" => $token // obtained with Stripe.js
));
$customerId=$customer['id'];
$this->retriveCustomer($customerId,$token);
}
/*
* function to retrive current customers for adding multiple cards to same customers*/
public function retriveCustomer($customerid,$token)
{
echo $this->token;
//die('here');
$retriveResult=Customer::retrieve($customerid);
$retriveResult->sources->create(array("source" =>$this->token));
return $retriveResult;
}
First, please note that unless you are PCI certified and allowed to directly manipulate card data, you should never have access to card numbers in your server-side code.
Card tokens should be created client-side, via Checkout or Elements. Your server should only deal with client-side created card tokens and never with PCI-sensitive information (card numbers and CVCs). This will greatly decrease the burden of PCI compliance and make you eligible for PCI SAQ A.
In PHP, this is how you'd add a card to an existing customer object:
$customer = \Stripe\Customer::retrieve("cus_...");
$card = $customer->sources->create(array(
"source" => $token // token created by Checkout or Elements
));
I think you dont need to create a token in case of adding new card. It helps while you update certain card. So the flow of addition will be same as you created for first card.
I dont know which stripe version you are using, I am using bit old:
$card_array = array(
'card' => array(
'number' => $number,
'exp_month' => $exp_month,
'exp_year' => $exp_year,
'cvc' => $cvc,
'name' => $name
)
);
$card_obj = $this->setData("\Stripe\Customer", "retrieve", $customer_id, TRUE);
$card = $card_obj->sources->create($card_array);
Stripe's docs don't explain a lot of the more nuanced procedures so you have to do a lot of testing.
Assuming you have a customer object $cu, with the token you get from checkout or whatever you use:
$card = $cu->sources->create(['source'=>$token]);
will add a card to the customer. It just adds the card to the list; subsequent calls will add cards to the list. Note that it does not check for duplicates, so the same card can be on the list multiple times. It will also not set the new card to the active card. To make a card the default (or active), use
$cu->default_source = $card
$cu->save();
Using the older card interface:
$cu->card = $token;
$cu->save();
The new card will replace the default card. It will NOT make the previously default card inactive; it will delete the current default and make the new card the active default. The card interface is the easiest if you're just allowing 1 card to be attached to a customer at a time.

Magento Credit card number mismatch with credit card type exception

I am using stripe credit card payment method for website on my magento store and developing a mobile application. I am developing the api's using native magento api. Problem occurred on create order api, everything till adding payment for stripe credit card works fine but when I hit the create order api it throws the exception.
"Credit card number mismatch with credit card type exception"
Below is api code, Please share your knowledge for this issue. Thanks in advance.
$proxy = new SoapClient($this->_client); //soap handle
$sessionId = $proxy->login($this->_apiuser, $this->_apikey);
$resultCustomerAddresses = $proxy->call($sessionId, "cart_customer.addresses", array($shoppingCartId, $arrAddresses));
if ($resultCustomerAddresses != TRUE)
{
return json_encode(array('status' => 0, 'result' => array(),'message' => 'Error in saving address'));
}
$resultShippingMethods = $proxy->call($sessionId, "cart_shipping.list", array($shoppingCartId));
$randShippingMethodIndex = rand(0, count($resultShippingMethods)-1 );
$shippingMethod = $resultShippingMethods[$randShippingMethodIndex]["code"];
$resultShippingMethod = $proxy->call($sessionId, "cart_shipping.method", array($shoppingCartId, $shipping_method));
//$resultTotalOrder = $proxy->call($sessionId,'cart.totals',array($shoppingCartId));
$paymentMethod = array(
"method" => $payment_method
);
$resultPaymentMethod = $proxy->call($sessionId, "cart_payment.method", array($shoppingCartId, $payment_method));
$licenseForOrderCreation = null;
$resultOrderCreation = $proxy->call($sessionId,"cart.order",array($shoppingCartId, null, $licenseForOrderCreation));
I had the same problem and successfully solved it, see this answer: https://stackoverflow.com/a/41948259/1052675
Basically, you supply the card information before you save the quote. It will validate the card against regex patterns and configured purchase limits and make sure you can use the payment method.
Then it will forget the payment information.
So before you tell it to submit the order, you need to supply the card info again.
My solution was a custom endpoint for simplicity on the front end app and it enabled me to keep the card info in memory to re-save between saving the quote and submitting the order.

Getting Last4 Digits of Card using Customer Object - Stripe API with PHP

I want to get the last 4 digits of a customers card using Stripe.
I have already stored the Customer using:
// Get the credit card details submitted by the form
$token = $_POST['stripeToken'];
// Create a Customer
$StripeCustomer = \Stripe\Customer::create(array(
"description" => "$username",
"card" => $token
));
Now I'd like to access and then store the card's last 4 digits. (For context, I want to show users which card they have stored using Stripe for future payments - this is not a subscription service).
I have searched for a solution but a lot of the posts are saving the last4 digits AFTER a charge, and pull the information from the charge like:
$last4 = null;
try {
$charge = Stripe_Charge::create(array(
"amount" => $grandTotal, // amount in cents, again
"currency" => "usd",
"card" => $token,
"description" => "Candy Kingdom Order")
);
$last4 = $charge->card->last4;
I would like to do the same BEFORE the charge , so I want to pull the last 4 from the Customer Object. The Stripe API documentation shows the attribute path for last4 from Customers,
customer->sources->data->last4
However, this does not seem to give me the correct last 4 digits.
$last4 = $StripeCustomer->sources->data->last4;
I think I am misunderstanding how to use attributes in the Stripe API. Could someone point me in the right direction?
$last4 = $StripeCustomer->sources->data[0]->last4;
sources->data is an array so you'd have to select the first card.
Side note: You're using the token twice, once to create the customer, and the second to create the charge, this will result in an error as the token can only be used once. You'd have to charge the customer instead of the token.
For any one else who lands here from search engines, here's a link to the Stripe docs on how to get the last 4 digits of a card saved to the customer https://stripe.com/docs/api/customers/object#customer_object-sources-data-last4
If you use Laravel Cashier, this code will be helpful for you.
$data = User::find(auth()->user()->id);
$payment = $data->defaultPaymentMethod();
$last4 = $payment->last4;
$brand = $payment->brand;
dd($payment);
You can get all information from this object.
This API has changed since this was first answered. For API version 2020-08-27 you need to use the ListPaymentsMethod API on the Customer object.
The path to access via JSON would look like this
$paymentMethods = $stripe->paymentMethods->all([
'customer' => 'cus_123',
'type' => 'card',
]);
$last4 = $paymentMethods->data[0]->card->last4

Categories