stripe error: No such PaymentMethod: 'pm_xxx' - laravel

really struggling to find the error where i missed. I am using Laravel (v8), Vue (v2) and Stripe(v3) for my e-commerce web-app. I implemented stripe in TEST mode successfully and it was working perfectly fine. And when I switched for live mode I am getting the following error: No such PaymentMethod: 'pm_1Yyl5xC4bpPAffpGV2p0ZL12'.
Front and backend scripts are as shown below.
async mounted(){
this.stripe = await loadStripe(process.env.MIX_STRIPE_KEY);
const elements = this.stripe.elements()
this.cardElement = elements.create('card', {
classes: {
base: 'bg-gray-100 rounded border border-gray-300 focus:border-indigo-500 text-base outline-none text-gray-700 p-3 leading-8 transition-colors duration-200 ease-in-out'
}
})
this.cardElement.mount('#card-element')
window.scrollTo(0, 0)
},
the method pay now method as follows:
async processPayment(){
//send the payment information to Laravel + Stripe
this.paymentProcessing = true
this.billingAddressValidations = {}
this.stripeErrors = null
const {paymentMethod, error} = await this.stripe.createPaymentMethod(
'card', this.cardElement, {
billing_details: {
name: this.card2.fullName,
},
}
)
if(error){
this.paymentProcessing = false
alert(error.message)
} else {
this.shippingAddress.payment_method_id = paymentMethod.id
this.shippingAddress.amount = this.cart.reduce((acc, item) => acc + this.itemPrice(item) * item.quantity, 0)
this.shippingAddress.cart = JSON.stringify(this.cart)
this.shippingAddress.isBillingAddress = this.isBillingAddress
this.shippingAddress.billingAddress = this.billingAddress
this.shippingAddress.orderDetails = this.orderDetails
const res = await this.apiCall('POST','/api/purchase', this.shippingAddress )
if(res.status === 200 || res.status === 201 ){
this.paymentProcessing = false
this.$store.commit('updateOrder', res.data)
await this.$store.dispatch('clearCart')
//this.orderConfirmation(response.data.transaction_id)
await this.$router.push({ name: 'order.summary' })
}
if(res.status === 206){
if(res.data.type === 'billing_address_error') {
this.billingAddressValidations = res.data
}
if(res.data.type === 'stripe_error') {
this.stripeErrors = res.data
}
this.paymentProcessing = false
}
}
},
and the Laravel/Cashier backend as follows:
public function purchase(Request $request)
{
$order_number = "JT2070215";
$user = User::firstOrCreate(
[
'email' => $request->input('email')
],
[
'password' => Hash::make(Str::random(12)),
'name' => $request->input('first_name') . ' ' . $request->input('last_name'),
'address' => $request->input('address'),
'city' => $request->input('city'),
'line2' => $request->input('line2'),
'zip_code' => $request->input('post_code'),
]
);
try {
$user->createOrGetStripeCustomer();
$user->addPaymentMethod($request->input('payment_method_id'));
$payment = $user->charge(
$request->input('amount'),
$request->input('payment_method_id'),[
'currency'=>'GBP',
'customer'=>$user->stripe_id
],
);
$payment = $payment->asStripePaymentIntent();
$order = $user->orders()
->create([
'transaction_id' => $payment->charges->data[0]->id,
'total' => $payment->charges->data[0]->amount,
'name' => $request->first_name." ".$request->last_name,
'email' => $request->email,
'address' => $request->address,
'city' => $request->city,
'country' => $request->country,
'post_code' => $request->postal_code,
'order_number'=>$order_number
]);
dispatch(new OrderConfirmationEmailJob($order->transaction_id));
return $order;
} catch (\Exception $e) {
return response()->json(['message' => $e->getMessage(), 'type'=>'stripe_error'], 206);
}
}

“No such...” errors are usually caused by either a mismatch in API keys (e.g. using a mixture of your test plus live keys) or by trying to access objects that exist on a different account (e.g. trying to perform an operation from your platform account on an object that was created on a connected account)

Hi you are trying to pass the payment_token used in creating the payment method. In order for you to get the id, you will need to retrieve it from the just created payment method.
So this should work.
$paymentMethod = $user->addPaymentMethod($request->input('payment_method_id'));
$paymentId = $paymentMethod->id // use this for the charge

Related

Payment failed but order is Placed in Laravel with Stripe

I have integrated stripe payment in flutter app but After payment got failed even then order placed in Laravel database so please check, what I have done wrong.
Please check at save method, May be I am wrong and can't validate purchase response.
payment controller
public function makePayment(Request $request)
{
try{
$data = $request->input('cartItems');
$cartItems = json_decode($data, true);
$orderData = $request->input('order');
$selectPaymentOption = json_decode($orderData, true);
$totalAmount = 0.0;
foreach ($cartItems as $cartItem){
$order = new Order();
$order->order_date = Carbon::now()->toDateString();
$order->product_id = $cartItem['productId'];
$order->payment_type = $selectPaymentOption['paymentType'];
$order->user_id = $request->input('userId');
$order->quantity = $cartItem['productQuantity'];
$order->amount = ($cartItem['productPrice'] - $cartItem['productDiscount']);
$totalAmount+= $order->amount * $order->quantity;
$order->save();
}
if($selectPaymentOption['paymentType'] == 'Card'){
\Stripe\Stripe::setApiKey('sk_test_hJUgYYzeXtitxxxx71lK8nE00MELJJS8c');
$token = \Stripe\Token::create([
'card' => [
'number' => $request->input('cardNumber'),
'exp_month' => $request->input('expiryMonth'),
'exp_year' => $request->input('expiryYear'),
'cvc' => $request->input('cvcNumber')
]
]);
$charge = \Stripe\Charge::create([
'amount' => $totalAmount * 100,
'currency' => 'inr',
'source' => $token,
'receipt_email' => $request->input('email'),
]);
}
return response(['result' => true]);
} catch (\Exception $exception){
return response(['result' => $exception]);
}
}
and my Flutter's Post request is here.
I want to POST _makePayment method after complete payment successful.
void _makePayment(BuildContext context, Payment payment) async {
PaymentService _paymentService = PaymentService();
var paymentData = await _paymentService.makePayment(payment);
var result = json.decode(paymentData.body);
print(paymentData);
CartService _cartService = CartService();
this.widget.cartItems!.forEach((cartItem) {
_cartService.makeTheCartEmpty();
});
if (result['result'] == true) {
_showPaymentSuccessMessage(context);
Timer(Duration(seconds: 4), () {
Navigator.pop(context);
Navigator.push(
context, MaterialPageRoute(builder: (context) => HomeScreen()));
});
}
}
Referring to my comment above, this is the rough solution I suggested in your controller you have to switch the logic
public function makePayment(Request $request)
{
try{
$data = $request->input('cartItems');
$cartItems = json_decode($data, true);
$orderData = $request->input('order');
$selectPaymentOption = json_decode($orderData, true);
##Change your frontend logic to pass total amount as variable
$totalAmount = $request->totalAmount;
if($selectPaymentOption['paymentType'] == 'Card'){
##Never have any sk or pk in your controller, switch this to config('common.sk_test')
\Stripe\Stripe::setApiKey(config('common.sk_test'));
$token = \Stripe\Token::create([
'card' => [
'number' => $request->input('cardNumber'),
'exp_month' => $request->input('expiryMonth'),
'exp_year' => $request->input('expiryYear'),
'cvc' => $request->input('cvcNumber')
]
]);
$charge = \Stripe\Charge::create([
'amount' => $totalAmount * 100,
'currency' => 'inr',
'source' => $token,
'receipt_email' => $request->input('email'),
]);
}
##After the stripe transaction is finished you can foreach your cart and do what you need to your database
foreach ($cartItems as $cartItem){
$order = new Order();
$order->order_date = Carbon::now()->toDateString();
$order->product_id = $cartItem['productId'];
$order->payment_type = $selectPaymentOption['paymentType'];
$order->user_id = $request->input('userId');
$order->quantity = $cartItem['productQuantity'];
$order->amount = ($cartItem['productPrice'] - $cartItem['productDiscount']);
$order->save();
}
return response(['result' => true]);
} catch (\Exception $exception){
return response(['result' => $exception]);
}
}
For the config('common.sk_test') part of my answer, in you config folder you can create a new file where you have you custom app variables, so create a file for instance common.php and 'sk_test' that takes its value from you .env file

how can I customize json responses of laravel api and show them in vuex

Trying different solutions, I am fooling around with
response()->json([ ])
To create responses that I can read in my vue / vuex application
The Laravel api function that stores a new Speler ( dutch for player ;)):
I have trouble sending the created, or found Speler-object, through the response to the vuex-store.
Tried to set the status to 202 when succesfully logged, yet the actual status sent is 200..
It is clear that I do not understand it well enough. Can anyone help and explain?
public function store(Request $request)
{
if (Game::where('id',$request['game_id'])->exists() ){
if (!Speler::where('name',$request['name'])->where('game_id',$request['game_id'])->exists()){
$newSpeler = Speler::create(
[
'name' => $request['name'],
'pass_code' => $request['pass_code'],
'game_id' => $request['game_id']
])->first());
return $newSpeler;
}
elseif ( Speler::where('name',$request['name'])->where('game_id',$request['game_id'])->where('pass_code', $request['pass_code'])->exists()){
$speler = Speler::where('name',$request['name'])->where('game_id',$request['game_id'])->where('pass_code', $request['pass_code']);
return response()->json(['speler'=> $speler, 202]);
}
return response()->json(['status' => 'This name is already used, pass-code is not correct', 409]);
}
return response()->json([ 'status' => 'The game-pin does not exist', 403 ]);
}
This is called form the vuex actions:
export const addSpeler = ({commit}, formData) => {
return new Promise((resolve, reject) => {
fetch(`api/speler`, {
method: 'post',
body:formData,
})
.then(res => {
if (res.status === 202){
resolve('De speler is succesfully logged on');
commit('SET_CURRENT_SPELER', res.data.speler);
}
else if (res.status === 201){
commit('SET_CURRENT_SPELER', res.data);
resolve('De speler is succesfully added')
}
else {
reject('De speler is not logged in. Name exists and does not match passcode');
}
})
.catch(err => {
reject(err.message)
});
})
}
and this is called from a vue method:
methods: {
addSpeler(){
this.errorMessage ='';
this.spelerAdded =false;
const formData = new FormData();
formData.append('name', this.name);
formData.append('pass_code',this.pass_code);
formData.append('game_id', this.currentGame.id);
this.$store.dispatch('addSpeler', formData )
.then(res => {
this.spelerAdded = true;
console.log(res.status);
})
.catch(err => {
this.errorMessage = err;
this.spelerAdded = false;
});
},
mutations.js:
export const SET_CURRENT_SPELER = (state, speler) => {
state.currentSpeler = speler;
}
state.js:
export default{
currentGame:{},
currentSpeler:{}
}
The comment by porloscerros answered the question perfectly :
the status goes as the second argument of the json method return response()->json(['speler'=> $speler], 202); (and not inside the array as you are doing). If you don't pass a second argument, the argument value is assigned to 200 by default json(mixed $data = [], int $status = 200, array $headers = [], int $options = 0)

Axios returns error status code 500 when there is data present

I am using Laravel 8, VueJS and Axios for my application then every time I try to fetch all records from my database it returns an error with status code 500. Even though when fetching the data using Postman/Insomnia it returns the data without an error.
I tried to empty the table where it fetches the data the error disappears and it returns empty data with status code 200.
Store Module:
import axios from 'axios'
export default {
namespaced: true,
state: {
courses: [],
teacher: '',
},
getters: {
allCourses(state) {
return state.courses
},
},
actions: {
async fetchAllCourses({ commit }) {
const response = await axios.get('teacher/course-management/list')
console.log(response.data.data)
commit('SET_COURSES', response.data.data)
}
},
mutations: {
SET_COURSES(state, courses) {
state.courses = courses
}
}
Controller:
public function fetchAllCourses() {
try {
$courses = Course::all()->sortBy('id');
$data = $courses->transform(function ($course) {
// ! Get teacher id
$teacherId = $this->user->teacher->id;
// ! Get teacher name by id
$teacherName = $this->getTeacherName($teacherId);
return [
'id' => $course->id,
'teacher_id' => $course->teacher_id,
'teacher' => $teacherName,
'section' => $course->section,
'code' => $course->code,
'status' => $course->status,
'image' => $course->image,
];
});
return $this->success('Request success', $data);
} catch (\Exception $e) {
return $this->error($e->getMessage(), $e->getCode());
}
}
Problem solved.
public function fetchAllCourses() {
try {
$courses = Course::all()->sortBy('id');
$data = $courses->transform(function ($course) {
return [
'id' => $course->id,
'teacher_id' => $course->teacher_id,
'teacher' => $this->getTeacherName($course->teacher_id),
'section' => $course->section,
'code' => $course->code,
'status' => $course->status,
'image' => $course->image,
];
});
return $this->success('Request success', $data);
} catch (\Exception $e) {
return $this->error($e->getMessage(), $e->getCode());
}
}

Subscription status in the DB not updated with Stripe

I'm approaching Stripe and Laravel for the first time. In my application I used the following code to manage payment rejections:
public function processSubscription(Request $request) {
$this->validate($request, [
'token' => 'required',
'plan' => 'required'
]);
try {
$stripeCustomer = Auth::user()->createOrGetStripeCustomer([
'description' => 'Example Example',
'email' => Auth::user()->email,
'name' => 'Example Example',
'phone' => '322234455556',
'address' => [
'city' => 'Alcatraz',
'line1' => 'Via Dalle Palle',
'postal_code' => '96011',
'state' => 'Italia'
]
]);
Auth::user()->newSubscription('default', $request->input('plan'))->create($request->token);
return redirect()->route('index')->with('success','Your subscription is active.');
} catch (IncompletePayment $exception) {
return redirect()->route(
'cashier.payment',
[$exception->payment->id, 'redirect' => route('index')]
);
}
//catch(\Stripe\Exception\CardException $e) {
//return back()->withErrors(['message' => 'Error creating subscription. ' . $e->getMessage()]);
//}
}
During a test payment, using the card:
4000 0000 0000 0341
A page is opened to confirm the customer's data again, this time by inserting a valid card (4242 4242 4242 4242), the payment is correctly executed and unfortunately nothing has changed by returning to the home page.
The status of the customer's subscription remains "incomplete".
I also attach the javascript code if anything could be useful.
const stripe = Stripe('{{ config('cashier.key') }}')
const elements = stripe.elements()
const cardElement = elements.create('card')
cardElement.mount('#card-element')
const form = document.getElementById('payment-form')
const cardBtn = document.getElementById('card-button')
//const cardHolderName = document.getElementById('card-holder-name')
form.addEventListener('submit', async (e) => {
e.preventDefault()
// Disable the submit button to prevent repeated clicks
document.getElementById('card-button').disabled = true
const { setupIntent, error } = await stripe.confirmCardSetup(
cardBtn.dataset.secret, {
payment_method: {
card: cardElement,
//billing_details: {
//name: document.getElementById('name').value
//}
}
}
)
if(error) {
document.getElementById('card-button').disabled = false
} else {
let token = document.createElement('input')
token.setAttribute('type', 'hidden')
token.setAttribute('name', 'token')
token.setAttribute('value', setupIntent.payment_method)
form.appendChild(token)
form.submit();
}
})
Why is the subscription status in the database not updated after the first payment fails, but the second payment does?

Laravel Http Client 419 unknown status

For testing reasons, I want to make the following Post Request with the Laravel HTTP Client:
$test = Http::post(route('users.leads.store', ['user' => $user->id]), [
"company_name" => "TESTCOMPANY",
"zip" => "49685",
"city" => "BÜHREN",
"street" => "MÜHLENKAMP 3",
"contact_name" => "FABIANLUKASSEN",
"phone1" => "017691443785",
"email" => "FABIANLUKASSEN#TESTEN.DE",
"website" => "www.fabianlukassen.de",
"category" => "Hotel",
"closed_until" => now(),
"appointment_end" => now()->addDays(1),
"appointment_comment" => "HALLO ICH BIN FABIAN",
"additional_contacts" => "",
"phone2" => "",
"sub_category" => "",
"expert_status" => 0
]);
I know that the route is working just fine. However, with debugging in phpStorm, I can see that the $test variable contains a 419 error (unknown status). Does anyone know what's wrong?
(I'm using laravel 8)
I agree with #ElektaKode that the issue is likely due to lack of csrf token.
In order to disable CSRF middleware while testing,
switch off CSRF token for this route at /app/Http/Midddleware/VerifyCsrfToken.php, by updating:
protected $except = [ 'your-route-url' ];
Then you can use api authentication to follow it up.
The simplest way to use api authentication, follow this doc,
The other ways are either using Laravel passport or using jwt for api.(both will consume more time to set up, as you are using for testing using api authentication is your go to method.)
Usually in Laravel, 419 Page Expired error comes from CSRF middleware meaning there was a failure while validating CSRF token. Add your CSRF token to your test request or consider disabling CSRF middleware while testing.
Post Request with Laravels HTTP Client
$test = Http::post(route('users.leads.store', ['user' => $user->id]), [
"company_name" => "TESTCOMPANY",
"place_id" => null,
"street" => "MÜHLENKAMP 3",
"zip" => "49685",
"city" => "BÜHREN",
"title" => null,
"contact_name" => "FABIANLUKASSEN",
"additional_contacts" => null,
"phone1" => "+49 163 3006603",
"phone2" => null,
"email" => "FABIANLUKASSEN#TESTEN.DE",
"category" => "Hotel",
"sub_category" => null,
"website" => "www.fabianlukassen.de",
"status" => 1,
"expert_status" => 0,
"coordinates" => null,
"expert_id" => 1,
"agent_id" => null,
"blocked" => 0,
"important_note" => null,
]);
Route
Route::apiResource('users.leads', UserLeadController::class);
Store Method in the UserLeadController
public function store(User $user, CreateLeadRequest $request)
{
//TODO: Relocate validation to request class
if(!UserLeadController::isPhone("test", $request->phone1)) {
abort(400, "Keine gültige Telefonnummer!");
return;
}
if(!UserLeadController::isPhoneNumberUnique("test", $request->phone1)) {
abort(400, "Die Telefonnummer existiert bereits!");
return;
}
/**
* The logged in User
* #var User $agent
*/
$agent = Auth::user();
$phoneUtil = PhoneNumberUtil::getInstance();
$lead = new Lead();
$lead->fill($request->except(['appointment_end', 'appointment_comment']));
// Leads created by experts will be blocked
if ($user->id === $agent->id) {
$lead->blocked = true;
}
$numberProto = $phoneUtil->parse($lead->phone1, 'DE');
$lead->phone1 = $phoneUtil->format($numberProto, PhoneNumberFormat::INTERNATIONAL);
try {
$lead->save();
} catch (QueryException $e) {
//$message = 'Lead besteht bereits.';
//return Response::json(['errors' => $message], 422);
abort(422, "Lead besteht bereits!");
return;
}
if ($request->closed_until) {
$lead->closed_until = Carbon::create($request->closed_until);
$event_end = $request->appointment_end
? Carbon::parse($request->appointment_end)
: Carbon::parse($request->closed_until)->addMinutes(90);
$lead->calendarEvents()->save(new CalendarEvent([
'body' => $request->appointment_comment ?? "Wurde von {$this->roleDescriptor($agent->roles)}" . $agent->name . " angelegt.",
'type' => CalendarEventType::CALLCENTER_APPOINTMENT,
'event_begin' => $lead->closed_until,
'event_end' => $event_end,
]));
$lead->status = LeadState::APPOINTMENT;
$lead->expert_status = LeadExpertAcceptance::ACCEPTED;
} else {
$lead->status = LeadState::OPEN;
}
if (isset($request->agent)) {
$lead->agent_id = $request->agent;
}
try {
$user->leads()->save($lead);
$lead->comments()->save(new Comment([
'body' => "Wurde von {$this->roleDescriptor($agent->roles)}" . $agent->name . " angelegt.",
'user_id' => $agent->id,
'commentable_type' => 'lead',
'commentable_id' => $lead->id,
'reason' => 'CREATED',
'date' => now('Europe/Berlin'),
]));
if ($request->closed_until) {
$lead->comments()->save(new Comment([
'body' => "Termin wurde von {$this->roleDescriptor($agent->roles)}" . $agent->name . " vereinbart.",
'user_id' => $agent->id,
'commentable_type' => 'lead',
'commentable_id' => $lead->id,
'reason' => 'APPOINTMENT',
'date' => now('Europe/Berlin')->addMinute(),
]));
}
} catch (QueryException $e) {
//not sure if this works
$message = $e->getMessage();
abort(400, $message);
return;
}
if (empty($message)) {
return Response::json(['message' => 'Lead saved', 'lead' => new LeadSingleResource($lead)]);
} else {
return Response::json(compact('message'), 500);
}
}
//TODO: relocate function to rule object
protected static function isPhoneNumberUnique($attribute, $value) {
$withSpace = PhoneFormatter::formatInternational($value);
$withoutSpace = preg_replace('/ /', '', $withSpace);
$protos = [$withSpace, $withoutSpace]; // Necessary because legacy (25.06.2020).
$booleanTest = Company::query()->whereIn('phone', $protos)->doesntExist()
|| Lead::query()->whereIn('phone1', $protos)->orWhereIn('phone2', $protos)->doesntExist();
return $booleanTest;
}
//TODO: relocate function to rule object
protected static function isPhone($attribute, $value) {
if (!$value) {
return false;
}
$phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
$test = $phoneUtil->isValidNumber($phoneUtil->parse($value, 'DE'));
return $test;
}
fillable variable in the Lead Model
protected $fillable = [
'company_name',
'place_id',
'street',
'zip',
'city',
'title',
'contact_name',
'additional_contacts',
'phone1',
'phone2',
'email',
'category',
'sub_category',
'website',
'status',
'expert_status',
'coordinates',
'expert_id',
'agent_id',
'blocked',
'important_note'
];
As mentioned before, I receive a 200 OK status. Also, in a Vue.js component, I have done the following axios post request, which also just works fine.
axios
.post(`/api/users/${this.user_id}/leads`, {
"company_name": this.companyName,
"zip": this.zipCode,
"city": this.city,
"street": this.streetAndHouseNumber,
"contact_name": this.contactPartner,
"phone1": this.contactPartnerPhoneNumber,
"email": this.contactPartnerEmail,
"website": this.website,
"category": this.category,
"closed_until": this.appointmentStart,
"appointment_end": this.appointmentEnd,
"appointment_comment": this.comment,
//not used but needed (don't know the purpose)
"additional_contacts": "",
"phone2": "",
"sub_category": "",
"expert_status":this.expert_status,
}).then(() => {
window.location.href = this.routeSuccess;
}).catch((error) => {
this.showErrorAlert = true;
this.errorAlertMessage = error.response.data.message;
});
}

Resources