Laravel Cashier - Create a new subscription with an existing customer object

I use Laravel Cashier with Stripe to manage my subscriptions. The user will provide information about his credit card at registration, but at the moment they will not be signed in a specific plan. Therefore, I can successfully use Stripe Checkout to create a Stripe client object and store the Stripe client ID in my database. But when the time comes for the user to enter the plan, I see no way to use the Stripe client ID to register them in the desired plan.

Of course, I can again request credit card information and get a Stripe token for use with Laravel Cashier, but I would like to avoid this, because the application already created a Stripe client object when they signed up, d just try to use an existing client object to charge your credit card, and not ask for your card number again.

To illustrate what I'm trying to do, here is a sample code from Laravel docs:

$user->newSubscription('main', 'monthly')->create($creditCardToken);

But what I would like to do is something like this (note the change to the create method:

$user->newSubscription('main', 'monthly')->create($user->stripe_id);

Any tips?

+4
source share
2 answers

If the user has a strip identifier, you do not need to specify a token

$user->newSubscription('main', 'monthly')->create();

SubscriptionBuilder .

+4

.

$user->setStripeKey(env("STRIPE_KEY"));

# card details
$card = [
'card_number' => 'xxxxxxxx',
'card_cvc' => 'xxx',
'exp_month' => 'xx',
'exp_year' => 'xxxx',
'name' => 'xxx',
];
# generate token
$token = $this->generateAccessToken($card);

private function generateAccessToken($card)
{

    $client = new \GuzzleHttp\Client();
    $url = 'https://api.stripe.com/v1/tokens';
    $pubKey = env("STRIPE_SECRET");
    $postBody = [
        'key' => $pubKey,
        'payment_user_agent' => 'stripe.js/Fbebcbe6',
        'card' => [
            'number' => $card['card_number'],
            'cvc' => $card['card_cvc'],
            'exp_month' => $card['exp_month'],
            'exp_year' => $card['exp_year'],
            'name' => $card['name']
        ]
    ];

    $response = $client->post($url, [
        'form_params' => $postBody
    ]);

    $response_obj = json_decode($response->getbody()->getContents());

    return $response_obj->id;
}
# main or primary
$subscription_obj = $user->newSubscription('subscription_name', 'stripe_plan_id')->create($token);
0

All Articles