Getting token to create customer using Stripe - stripe-payments

I'm implementing Stripe in my ASP.NET Core app using Checkout.
I know how to get a token for charging a credit card using Checkout but where do I get the token to create a customer?
In the documentation, I see that I need to get a token to create a customer but not sure where that token comes from.
https://stripe.com/docs/api/dotnet#create_customer
As far as I know, a token can be used only once so it cannot be the same token I get before charging a credit card.

As I am referencing here from stripe document
When you collect a customer's payment information, a Stripe token is created. This token can only be used once, but that doesn't mean you have to request your customer's card details for every payment.
Stripe provides a Customer object that makes it easy to save this—and
other—information for later use. You can use Customer objects for
creating subscriptions or future one-off charges.
What you have to exactly do is Create a customer you have got while taking
card details from the customer and charge that customer.
Do it using following code snippet, in this way you will create a customer and charge using a single token
StripeConfiguration.SetApiKey(secret_key_of_your_account);
var token = model.Token; // Using ASP.NET MVC
var customers = new StripeCustomerService();
var charges = new StripeChargeService();
var customer = customers.Create(new StripeCustomerCreateOptions {
Email = "paying.user#example.com",
SourceToken = token
});
// YOUR CODE: Save the customer ID and other info in a database for later.
// YOUR CODE (LATER): When it's time to charge the customer again, retrieve the customer ID.
var charge = charges.Create(new StripeChargeCreateOptions {
Amount = 1500, // $15.00 this time
Currency = "usd",
CustomerId = customer.Id
});
read the referenced document for more details

\Stripe\Stripe::setApiKey("----");
\Stripe\Stripe::setApiKey(".................");
$token= \Stripe\Token::create(array(
"card" => array(
"number" => "4242424242424242",
"exp_month" => 1,
"exp_year" => 2019,
"cvc" => "314"
)
));
$request['stripe_token'] =$token['id'];
// When Contact person have not Stripe Customer id then we have to do the following process.
try {
$customer = \Stripe\Customer::create([
"description" => "Customer for ".$contactDetails['email'],
"source" => $request['stripe_token'] // obtained with Stripe.js
]);
// update its customerid in the contact table
// Create Customer then save its id in table and use the customer id when you are verifiying the customer token
$result= \Stripe\Charge::create(array(
"amount" => $request['amount'],
"currency" => $request['currency'],
"customer" => $customer
));
$status = $result['succeeded'];
if($result['status'] == "succeeded"){
$success = 'Your payment was successful.';
$all['payment_done'] = "1";
$FinalArray = array('status'=>'true','message'=>'Your payment done successful.','result'=>$all);
}else{
$FinalArray = array('status'=>'fail','message'=>'Your Token is not generated successfully','result'=>[]);
}
}
catch (Exception $e) {
$error = $e->getMessage();
$all['payment_done'] = "0";
$FinalArray = array('status'=>'false','message'=>'The Stripe token id is not correctly','result'=>$all);
}

Related

How to save card details using stripe?

How to save card details in stripe payment gateway and use card details for next payment for particular user who entered the card details before
thank you
Before saving card you need to create customer first like below
Right now I am giving you an example with PHP language.
Creating customer :
$customer = \Stripe\Customer::create([
'name' => 'Test User',
'email' => 'cardtestuser#gmail.com',
'description' => 'My First Test Customer',
]);
You can refer the link for more detail : https://stripe.com/docs/api/customers/create
It will return the object with customer id e.g : cust_**** that you need to keep with you for later used else you can get it from Stripe dashboard.
Now we need to generate token for the card that we need to add to the customer that recently created in stripe
$token = \Stripe\Token::create([
'card' => [
'number' => '4242424242424242',
'exp_month' => 3,
'exp_year' => 2021,
'cvc' => '314',
],
]);
Above code return the card token e.g tok_*** that you need to use to save card to the customer
Here is the code to create new card to customer
\Stripe\Customer::createSource(
$customer->id,
['source' => $token->id]
);
You can save customeId(cust_###) and cardId(card_###) in database or somewhere else so you can use it later while making payment from card
Hope this will help you

Stripe does not let a charge be associated with a customer with one-time source

As the title says, I am trying to make a payment using a one-time source (credit card) that is not being saved in the customer's profile. I still want to be able to record that charge on the customer's profile on Stripe.
According to the docs, this can be done by passing the customer's id in customer key in the payload sent to Stripe.customers.createCharge. However, on doing that, I receive an error stating the card is not linked with the customer (which obviously is not, and I don't want it to be).
Customer cus_*** does not have card with ID tok_visa
To get around this, temporarily I have applied the fix mentioned in this answer which basically involves creating a temporary card for the payment and then deleting it.
I was wondering how does the API not work when it is clearly documented otherwise, hope someone experienced with Stripe chimes in on the same.
Here is the code I'm trying to get to run:
await stripeService.charges.create({
source: token, // temporary token received from Checkout
customer: user.stripeCustomerId, // the Stripe customer ID from my database
amount,
currency: 'usd',
description: 'Test charge'
});
The single-use sources document that you link to explicitly only works with Sources, but tok_visa will create a Card object instead. I believe that's why you get the error.
If you try the code with a Source(it has an ID like 'src_xxx') that you obtain through Elements/Checkout on your frontend with, for example, createSource, it will succeed, I've just tested it. You can also test with this code :
const src = await stripe.sources.create({
type : "card",
token : "tok_visa"
});
const charge = await stripe.charges.create({
    source : src.id,
customer : "cus_xxxx",
    amount : 1000,
    currency : "usd"
});
I was able to achieve this by creating the source first followed by the charge where you specify the customerId and sourceId as below:
//Create the source first
var options = new SourceCreateOptions
{
Type = SourceType.Card,
Card = new CreditCardOptions
{
Number = Number,
ExpYear = ExpYear,
ExpMonth = ExpMonth,
Cvc = Cvc
},
Currency = "gbp"
};
var serviceSource = new SourceService();
Source source = serviceSource.Create(options);
//Now do the payment
var optionsCharge = new ChargeCreateOptions
{
Amount = 500,
Currency = "gbp",
Description = "Your description",
SourceId = source.Id,
CustomerId = "yourcustomerid"
};
var service = new ChargeService();
service.Create(optionsCharge);
result = "success";

stripe creating token with card id

I'm currently trying to create charges with the server side stripe api.
But i'm facing a problem; I'm using two ways to proceed with the paiement:
either the user can pay using the stripe element => I'm therefore using the generated token ('tok_somethingId') to effectuate the paiement
or, if the user already added some cards on is account he can select on of them in a list => The server then use the card id ('card_somethingId') and the customer id ('cus_smoethingId')
I was wondering if there was a way to generate a token with a card id and a customer id in order to use this token to create the charge instead of using the card id and the customer id to charge the user.
I already tried with https://stripe.com/docs/api/node#create_card_token but it doesn't seem to work.
stripe.tokens.create({
card: cardId,
customer: customerId
}, function(err, token) {
// do smthg here with the token
});
This give me this error message
If you are doing payment with stored card then no need to get token,
1- Create customer on stripe
$customer = \Stripe\Customer::create([
'email' => $customer_email,
]);
$response = ['status' => 'success', 'response' => $customer];
when you have created customer then you have customer_id
if(isset($response ['response']['id']))
$response ['customer_id'] = $response ['response']['id'];
2 - you can add card on stripe by the customer id and card token
$customer = \Stripe\Customer::retrieve($customer_id);
$creditCard = $customer->sources->create(array("source" => $cardToken));
$response = ['status' => 'success', 'response' => $creditCard];
Now you have card id like this
"id": "card_1D4plsDExLRkbD8k1UWdqwIr"
3- you can store multiple cards on customer and also can have retreive
$cards = \Stripe\Customer::retrieve($customer_id)->sources->all(array(
"object" => "card"
));
4 -you can payment via card card that is stored on customer account
$params = [
'currency' => 'USD',
'amount' => $total_amount * 100,
// converting dollars to cents
'description' => $description, //it may be blank
'customer' => $customer_id,
"card" => $card_id'
];
$transaction = \Stripe\Charge::create($params);
$response = ['status' => 'success', 'response' => $transaction['id']];
Here we are not using 'source' parameter because it is used when we are payment via card token.
You can not create a new token for an existing card as this would not make sense. The card is already saved on the customer and you can charge it.
The easiest solution here is likely to do the reverse and save the card on a customer when you get a token tok_XXXX. This way, you always charge a card by passing the customer parameter as the customer id cus_XXXX and the source parameter as the card id card_XXXX.
Otherwise, you need to handle this dynamically so that you know if you are getting a token (tok_XXXX) or a card id (card_XXXX) and pass different parameters based on that decision. Your front-end code should know which case you ended up in.
just pass the values in the body,
[{"key":"amount","value":"1000","description":""},{"key":"currency","value":"usd","description":""},{"key":"customer","value":"cus_ID","description":""},{"key":"description","value":"\"Charge for jenny.rosen#example.com\"","description":""},{"key":"card","value":"card_ID","description":""}]
this working for me

Create Token in stripe using existing card info and customer id

I am using stripe.js with php and I am having issue in creating token for existing/saved cards and for new card everything works fine. Is there any function to generate token based on cardId and customerId
It is neither necessary nor possible to create a new token from an existing Customer or Card object. Once a card has been stored on a Customer object, you can complete a charge using only your secret key and the Customer ID. From the docs:
// 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_BQokikJOvBiI2HlWgH4olfQ2");
// Token is created using Stripe.js or Checkout!
// Get the payment token ID submitted by the form:
$token = $_POST['stripeToken'];
// Create a Customer:
$customer = \Stripe\Customer::create(array(
"email" => "paying.user#example.com",
"source" => $token,
));
// Charge the Customer instead of the card:
$charge = \Stripe\Charge::create(array(
"amount" => 1000,
"currency" => "usd",
"customer" => $customer->id
));
// YOUR CODE: Save the customer ID and other info in a database for later.
// YOUR CODE (LATER): When it's time to charge the customer again, retrieve the customer ID.
$charge = \Stripe\Charge::create(array(
"amount" => 1500, // $15.00 this time
"currency" => "usd",
"customer" => $customer_id
));
If you have any other questions about how to implement a particular payment flow on Stripe I'd recommend getting in touch with Stripe support.

Stripe charge existing customer

I'm using embed stripe.js
Upon form completion, the form redirects to: www.mydomain.com/doc-whatever/?action=payment
This url param fires the serverside code. Abbreviated pseudo code:
$token = $_POST['stripeToken'];
//check if customer ID exists in the DB.
//returns the stripe customer id of client attached to the document.
//May or may not be logged in.
$customers_stripe_id = get_customer_stripe_id()
if ( ! $customers_stripe_id ) {
$customer = \Stripe\Customer::create(array(
'email' => 'customer#example.com',
'source' => $token
));
$customers_stripe_id = $customer_id;
}
$charge = \Stripe\Charge::create(array(
'customer' => $customers_stripe_id,
'amount' => 5000,
'currency' => 'usd'
));
This works just fine, however there is an obvious security issue here. One can simply navigate to www.mydomain.com/doc-whatever/?action=payment and if there is stripe customer id stored in the database, the card customer will be charged.
Your server-side code should be authorized then, so that for example only a logged in customer himself or an admin could fire that action.

Resources