You know there is a first-party Laravel Cashier package that can handle this functionality for you?
Jun 27, 2023
5
Level 1
Stripe payment integration in laravel for buying subscription
I have a requirement to buy subscription that is present.
I do no know how to implement this.
I am implementing in the following way, although this code I have got from a website :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Stripe;
use Exception;
use Illuminate\Support\Facades\Validator;
use Stripe\Exception\CardException;
use Stripe\StripeClient;
class StripePaymentController extends Controller
{
const COMPONENT_CODE = 'RS_PAYMENT';
private $stripe;
public function __construct()
{
Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
$this->stripe = new \Stripe\StripeClient(env('STRIPE_SECRET'));
}
public function payment(Request $request)
{
$validator = Validator::make($request->all(), [
'fullName' => 'required',
'cardNumber' => 'required',
'month' => 'required',
'year' => 'required',
'cvv' => 'required'
]);
if ($validator->fails()) {
return $this->returnErrorResponse(self::COMPONENT_CODE, 101, array_column( $validator->errors()->messages() , 0), 422);
}
$token = $this->createToken($request);
if (!empty($token['error'])) {
return $this->returnErrorResponse(self::COMPONENT_CODE, 102, 'Invalid token', 422);
}
if (empty($token['id'])) {
return $this->returnErrorResponse(self::COMPONENT_CODE, 102, 'ID does not exist', 422);
}
$charge = $this->createCharge($token['id'], 2000);
if (!empty($charge) && $charge['status'] == 'succeeded') {
$returnArray['status'] = 'Success';
$returnArray['message'] = 'Payment Successful';
return response()->json($returnArray, 200);
} else {
return $this->returnErrorResponse(self::COMPONENT_CODE, 102, 'Payment failed', 422);
}
}
private function createToken($cardData)
{
$token = null;
try {
$token = $this->stripe->tokens->create([
'card' => [
'number' => $cardData['cardNumber'],
'exp_month' => $cardData['month'],
'exp_year' => $cardData['year'],
'cvc' => $cardData['cvv']
]
]);
} catch (CardException $e) {
$token['error'] = $e->getError()->message;
} catch (Exception $e) {
$token['error'] = $e->getMessage();
}
return $token;
}
private function createCharge($tokenId, $amount)
{
$charge = null;
try {
$charge = $this->stripe->charges->create([
'amount' => $amount,
'currency' => 'usd',
'source' => $tokenId,
'description' => 'My first payment'
]);
} catch (Exception $e) {
$charge['error'] = $e->getMessage();
}
return $charge;
}
}
Now I am testing with the following request:
{
"fullName":"TestName",
"cardNumber":"4242424242424242",
"month":12,
"year":2030,
"cvv":123
}
It shows the error: Invalid token as no token is being created.
Kindly help, where am I going completely wrong, or is there any other way that I can try.
Please or to participate in this conversation.