Unrecognized request URL (GET: /v1/customers/). If you are trying to list objects, remove the trailing slash - laravel

Please if anyone has any idea why I keep getting this error when I submitted the stripe subscription form should please help, this error got me stuck for a while now, just trying to create a subscription from the pricing page or subscription plan page, I have the plans stored in my database in a model called Plan. so what I want is for users to select a pricing plan monthly or yearly and it will take them to the payment page where they can make payment and activate a subscription. I am using Laravel Cashier with stripe.
Full error message
Unrecognized request URL (GET: /v1/customers/). If you are trying to list objects, remove the trailing slash. If you are trying to retrieve an object, make sure you passed a valid (non-empty) identifier in your code. Please see https://stripe.com/docs or we can help at https://support.stripe.com/.
The Plans Model
The Route
Route::group(['namespace' => 'Subscriptions'], function() {
Route::get('plans', 'SubscriptionPlanController#index')->name('plans');
Route::get('/payments', 'PaymentsController#index')->name('payments');
Route::post('/payments', 'PaymentsController#store')->name('payments.store');
});
The Plans page
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Subscription Plans') }}</div>
<div class="card-body">
#foreach($plans as $plan)
<div>
{{$plan->title}}
{{-- {{dd($plan->stripe_id)}} --}}
</div>
#endforeach
</div>
</div>
</div>
</div>
</div>
This is The Form
<form action="{{ route('payments.store')}}" method="POST" id="payment-form">
#csrf
<div class="form-content">
<input type="hidden" name="plan" id="subscription-plan" value="{{ request('plan') }}">
<div class="field">
<input type="text" autocorrect="off" spellcheck="false" id="card-holder-name" maxlength="25" />
<span class="focus-bar"></span>
<label for="cardholder">Card holder (Name on card)</label>
</div>
<div class="field mb-5" id="card-element">
<!-- Stripe Elements Placeholder -->
</div>
<button id="card-button" type="submit" data-secret="{{ $intent->client_secret }}">
<span>Pay</span></button>
</div>
</form>
This is the PaymentsController
public function index()
{
$user = auth()->user();
$data = [
'intent' => $user->createSetupIntent(),
];
return view('subscriptions.payments')->with($data);
}
public function store(Request $request)
{
$user = auth()->user();
$paymentMethod = $request->payment_method;
$plan = Plans::where('identifier', $request->plan)
->orWhere('identifier', 'basic_product')
->first();
$request->user()->newSubscription('default', $plan->stripe_id)->create($paymentMethod);
return response(['status' => 'success']);
}
This is the JavaScript
// Create a Stripe client.
const stripe = Stripe('pk_test_51H2OqqLzAo4pwMcyT4h405wpFRAn3FWhvByfvmVnW6tabrIsDoU1dBXJ0UaWexUJeacCJ9uKpb5OBmmA2KaCg4sd00ZZ5tj2q8');
// Create an instance of Elements.
const elements = stripe.elements();
// Custom styling can be passed to options when creating an Element.
// (Note that this demo uses a wider set of styles than the guide below.)
// const cardElement = elements.create('card', {style: style});
// Create an instance of the card Element.
const cardElement = elements.create('card');
// Add an instance of the card Element into the `card-element` <div>.
cardElement.mount('#card-element');
const cardHolderName = document.getElementById('card-holder-name');
const cardButton = document.getElementById('card-button');
const clientSecret = cardButton.dataset.secret;
const plan = document.getElementById('subscription-plan').value;
// Handle form submission.
var form = document.getElementById('payment-form');
form.addEventListener('submit', async (e) => {
e.preventDefault();
cardButton.disabled = true
const { setupIntent, error } = await stripe.confirmCardSetup(
cardButton.dataset.secret, {
payment_method: {
card: cardElement,
billing_details: {
name: cardHolderName.value
}
}
}
);
if (error) {
// Display "error.message" to the user...
} else {
var paymentMethod = setupIntent.payment_method;
var form = document.getElementById('payment-form');
var hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'payment_method');
hiddenInput.setAttribute('value', paymentMethod);
form.appendChild(hiddenInput);
// Submit the form
form.submit();
}
// });
});

I had this problem tonight. It turned out to be because "stripe_id" in the database was stored as a "" (blank) vs NULL.
In the stripe ManagesCustomer function, it does logic based on !is_null($this->stripe_id) to then assume that this has a stripe id if its an empty string.

Related

Update credit card in Stripe

I tried some solutions but I couldn't create a correct form to update the credit card.
I have created a special page to manage the credit card update.
Also, I would like to understand when for an automatic subscription renewal you have a credit card that has expired or otherwise "fails", what happens? Does the subscription continue making X attempts?
Right now, my code is as follows:
Controller
public function setupPayment(){
return view('update-card', [
'intent' => Auth::user()->createSetupIntent()
]);
}
public function updateExistingCreditCard(Request $request){
$key = \config('services.stripe.secret');
$stripe = new \Stripe\StripeClient($key);
$this->validate($request, [
'address' => 'nullable',
'name' => 'nullable'
]);
$user = Cashier::findBillable(Auth::user()->stripe_id);
//$user = Auth::user()->asStripeCustomer();
if($user->hasDefaultPaymentMethod()){
$stripe->customers->updateSource(
$user->stripe_id,
$user->id,
['name' => 'Jenny Rosen']
);
return redirect()->back()->with('success','Update.');
}
return redirect()->back()->with('danger','Error.');
}
HTML
<form id="payment-form" action="{{ route('update.new.credit.card') }}" method="POST">
#csrf
<div class="row">
<div class="col-lg-6">
<div class="card">
<div class="card-header">
{{ __('Update Card') }}
</div>
<div class="card-body">
<input id="card-holder-name" type="text">
<!-- Stripe Elements Placeholder -->
<div id="card-element"></div>
<button id="card-button" data-secret="{{ $intent->client_secret }}">
Update Payment Method
</button>
</div>
</div>
</div>
</div>
</form>
const stripe = Stripe('{{ config('cashier.key') }}');
const elements = stripe.elements();
const cardElement = elements.create('card');
cardElement.mount('#card-element');
const cardHolderName = document.getElementById('card-holder-name');
const cardButton = document.getElementById('card-button');
const clientSecret = cardButton.dataset.secret;
cardButton.addEventListener('click', async (e) => {
const { setupIntent, error } = await stripe.confirmCardSetup(
clientSecret, {
payment_method: {
card: cardElement,
billing_details: {
name: cardHolderName.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();
}
});
UPDATE
In this new code, by inserting the metadata fields, they are correctly updated, so I guess the code is right. I am probably wrong with the parameters passed to update the card and make it default to the customer.
$stripeCustomer = Auth::user()->asStripeCustomer();
$paymentMethod = $stripe->customers->retrieve($stripeCustomer->id)->invoice_settings->default_payment_method;
if(Auth::user()->hasDefaultPaymentMethod()){
$stripe->customers->update($stripeCustomer->id, [
['invoice_settings' => ['default_payment_method' => $paymentMethod]]
]);
return redirect()->back()->with('success','Update.');
}

how to access axios response in blade - laravel view

How to access axios result from vue component in blade file? I tried accessing {{value}} within 'app' div also. But the error still remains. I want to generate partial views based on the value of axios response.
IssueComponent.vue
<template>
<div>
<div class="form-group">
<label>Enter Accession No</label>
<input
type="text"
name="accession_no"
placeholder="Accession No"
class="form-control"
v-on:keyup.enter="getData()"
v-model="query"
/>
</div>
<div>
<button class="btn btn-info" #click.prevent="getData()">Check</button>
</div>
</template>
<script>
export default {
data() {
return {
query: "",
value: []
};
},
methods: {
getData: function() {
var self = this;
axios
.get("/issue-getdata", { params: { q: self.query } })
.then(function(response) {
self.value = response.data;
})
.catch(function(error) {
console.log(error);
})
.then(function() {
});
}
}
};
</script>
create.blade.php
<form action="/issue" method="POST">
<div id="app">
<issue-component></issue-component>
</div>
{{value}} ///////// Undefined constant error
<button type="submit" class="button-btn btn-success">Submit</button>
#csrf
</form>
Controller Method
public function getData(Request $request){
$input = $request->q;
$acsNo = preg_replace("/[^0-9]/", "", $input);
$acsNoIssued = Issue::where('accession_no', '=', $acsNo)->where('is_returned', null)->orwhere('is_returned', 0)->first();
return response()->json($acsNoIssued);
}
The Error
Facade\Ignition\Exceptions\ViewException
Use of undefined constant value - assumed 'value' (this will throw an Error in a future version of PHP) (View: D:\ProgrammingSSD\laragon\www\ulclibrary\resources\views\issues\create.blade.php)
You can't. Blade is rendered server side. By the time your vue component makes the request, that {{ $value }} is already parsed and is now a static part of your view.
What you could do is save the state (the information) in VUE, and read it using another VUE component that will display the info (instead of blade).
Guide for states in vue
https://vuex.vuejs.org/guide/state.html
<form action="/issue" method="POST">
<div id="app">
<issue-component></issue-component>
</div>
<display-component-value></display-component-value> // Vue component that reads the state you want
<button type="submit" class="button-btn btn-success">Submit</button>
#csrf
</form>

Getting a vue form to go to the next page after submit in laravel

I'm using both laravel and vue and I'm trying to get my vue form to go to another page when I've submitted, but the problem is that once it's submitted it refreshes and goes back to the page it's on instead of the other page.
When I check my network tab in the dev tools, it posted to the right page but it doesn't show up in the browser
This is my vue
<template>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Example Component</div>
<div class="card-body">
I'm an Supplier Code Selection component.
<br>
<form #submit.prevent="submit">
<label for="parent-product">Parent Product</label>
<select name="parent-product" id="parent-product" class="form-control" v-model="selected_parent">
<option>Please select your code</option>
<option v-for="product in products" :value="product.id">
{{ product.supplier_code }}
</option>
<option v-for="child in children" :value="child.id">
{{ child.supplier_code }}
</option>
</select>
<input type="submit" class="btn btn-primary" value="Submit">
</form>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
props: [
'products',
'children',
'selected_parent'
],
mounted() {
console.log('Component mounted.')
},
methods: {
submit(){
var formData = new FormData();
console.log('this is the select box - '+this.selected_parent);
formData.append('parent-product', this.selected_parent);
return axios.post('/add-to-cart/'+this.selected_parent, formData);
},
},
}
</script>
My route
Route::any('/add-to-cart/{id}', 'PublicController#getAddToCart')->name('product.addToCart');
My controller function
public function getAddToCart(Request $request, $id)
{
$menus_child = Menu::where('menu_id', 0)->with('menusP')->get();
$contacts = Contact::all();
$product = Product::find($id);
$supplier_code = $request->supplier_code;
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$cart->add($product, $product->id, $supplier_code);
$request->session()->put('cart', $cart);
return view('public.shopping-cart', ['products' => $cart->items, 'totalPrice' => $cart->totalPrice, 'menus_child' => $menus_child, 'contacts' => $contacts, 'supplier_code' => $supplier_code]);
}
You could just add a location if the axios call returns success. Ps. untested code.
methods: {
submit(){
var formData = new FormData();
console.log('this is the select box - '+this.selected_parent);
formData.append('parent-product', this.selected_parent);
return axios.post('/add-to-cart/'+this.selected_parent, formData)
.then(response => { location: '/'});
},
I found my issue. I forgot to change
return view('public.shopping-cart', compact('supplier_code'));
to
return ['redirect' => route('product.shoppingCart')];
in my laravel controller function

No error messages from 422 response on laravel form request from vue component

I'm trying to submit a form request using axios, have it validated, and return errors if the validation fails. The problem is, when I submit the form, no error messages are returned for me to show on the client side. Here's the HTTP request and vue component:
<div class="card">
<div class="card-header">
<h4>Information</h4>
</div>
<div class="card-body">
<p v-if='!isEditMode'><strong>Name:</strong> {{businessData.name}}</p>
<div class="form-group" v-if='isEditMode'>
<strong><label for="business-name">Name</label></strong>
<input class="form-control" name="business-name" v-model='businessData.name'>
</div>
<p v-if='!isEditMode'><strong>Description:</strong> {{businessData.description}}</p>
<div class="form-group" v-if='isEditMode'>
<strong><label for="business-description">Description</label></strong>
<textarea class="form-control normal" name="business-description"
placeholder="Enter your services, what you sell, and why your business is awesome"
v-model='businessData.description'></textarea>
</div>
</div>
</div>
<div class="card">
<h4 class="card-header">Address Information</h4>
<div class="card-body">
<p v-if="!isEditMode"><strong>Street Address: </strong> {{businessData.street}}</p>
<div class="form-group" v-if='isEditMode'>
<strong><label for="business-street">Street Address: </label></strong>
<input type="text" class="form-control" name="business-street" v-model='businessData.street' placeholder="1404 e. Local Food Ave">
</div>
<p v-if="!isEditMode"><strong>City: </strong> {{businessData.city}}</p>
<div class="form-group" v-if='isEditMode'>
<strong><label for="business-city">City: </label></strong>
<input class="form-control" type="text" name="business-city" v-model='businessData.city'>
</div>
<p v-if="!isEditMode"><strong>State: </strong> {{businessData.state}}</p>
<div class="form-group" v-if='isEditMode'>
<strong><label for="business-state">State: </label></strong>
<select class="form-control" name="business-state" id="state" v-model="businessData.state" >...</select>
</div>
<p v-if="!isEditMode"><strong>Zip: </strong> {{businessData.zip}}</p>
<div class="form-group" v-if='isEditMode'>
<strong><label for="business-zip">Zip: </label></strong>
<input class="form-control" type="text" maxlength="5" name="business-zip" v-model='businessData.zip'>
</div>
</div>
</div>
<div class="card">
<h4 class="card-header">Contact Information</h4>
<div class="card-body">
<p v-if="!isEditMode"><strong>Phone: </strong> {{businessData.phone}}</p>
<div class="form-group" v-if='isEditMode'>
<strong><label for="business-phone">Phone: </label></strong>
<input class="form-control" type="tel" name="business-phone" v-model='businessData.phone'>
</div>
<p v-if="!isEditMode"><strong>Email: </strong> {{businessData.email}}</p>
<div class="form-group" v-if='isEditMode'>
<strong><label for="business-Email">Email: </label></strong>
<input class="form-control" type="email" name="business-email" v-model='businessData.email'>
</div>
</div>
</div>
</div>
<script>
export default {
data () {
return {
isEditMode: false,
businessData: this.business,
userData: this.user,
errors: []
}
},
props: {
business: {},
user: {},
role: {}
},
//Todo - Institute client side validation that prevents submission of faulty data
methods: {
validateData(data) {
},
saveBusinessEdits () {
axios.put('/businesses/' + this.business.id , {updates: this.businessData})
.then(response => {
console.log(response.data)
// this.businessData = response.data;
this.isEditMode = false;
})
.catch (response => {
console.log(response.data)
this.isEditMode = false;
})
},
saveUserEdits () {
axios.put('/profile/' + this.user.id , {updates: this.userData})
.then(response => {
console.log(response.data)
this.userData = response.data;
this.isEditMode = false;
})
.catch (response => {
console.log(response)
this.isEditMode = false;
})
}
}
}
Route
Route::put('/businesses/{id}', 'BusinessesController#update');
BusinessController and update function
public function update(BusinessRequest $request, $id)
{
$business = Business::find($id)->update($request->updates);
$coordinates = GoogleMaps::geocodeAddress($business->street,$business->city,$business->state,$business->zip);
if ($coordinates['lat']) {
$business['latitude'] = $coordinates['lat'];
$business['longitude'] = $coordinates['lng'];
$business->save();
return response()->json($business,200);
} else {
return response()->json('invalid_address',406);
}
$business->save();
return response()->json($business,200);
}
and BusinessRequest class
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'business-name'=> 'required|string|max:255',
'business-description'=> 'required|string',
'business-phone' => 'nullable|phone|numeric',
'business-email' => 'nullable|email',
'business-street'=> 'required|string',
'business-city' => 'required|string',
'business-state' => 'required|string|max:2',
'business-zip' => 'required|min:5|max:5|numeric',
];
}
public function messages() {
return [
'business-zip.min:5' =>'your zip code must be a 5 characters long',
'business-email.email'=>'your email is invalid',
'business-phone.numeric'=>'your phone number is invalid',
];
}
}
I don't understand why, even if input valid data, it responds with a 422 response and absolutely no error messages. Since this is laravel 5.6, the 'web' middleware is automatic in all of the routes in the web.php file. So this isn't the problem. Could anyone help me normalize the validation behavior?
In Laravel a 422 status code means that the form validation has failed.
With axios, the objects that are passed to the then and catch methods are actually different. To see the response of the error you would actually need to have something like:
.catch (error => {
console.log(error.response)
this.isEditMode = false;
})
And then to get the errors (depending on your Laravel version) you would have something like:
console.log(error.response.data.errors)
Going forward it might be worth having a look at Spatie's form-backend-validation package
You can use Vue.js and axios to validate and display the errors. Have a route called /validate-data in a controller to validate the data.
app.js file:
import Vue from 'vue'
window.Vue = require('vue');
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
class Errors {
constructor() {
this.errors = {};
}
get(field) {
if (this.errors[field]) {
return this.errors[field][0];
}
}
record(errors) {
this.errors = errors;
}
clear(field) {
delete this.errors[field];
}
has(field) {
return this.errors.hasOwnProperty(field);
}
any() {
return Object.keys(this.errors).length > 0;
}
}
new Vue({
el: '#app',
data:{
errors: new Errors(),
model: {
business-name: '',
business-description: '',
business-phone: ''
},
},
methods: {
onComplete: function(){
axios.post('/validate-data', this.$data.model)
// .then(this.onSuccess)
.catch(error => this.errors.record(error.response.data.errors));
},
}
});
Make a route called /validate-data with a method in the controller, do a standard validate
$this->validate(request(), [
'business-name'=> 'required|string|max:255',
'business-description'=> 'required|string',
'business-phone' => 'nullable|phone|numeric',
'business-email' => 'nullable|email',
'business-street'=> 'required|string',
'business-city' => 'required|string',
'business-state' => 'required|string|max:2',
'business-zip' => 'required|min:5|max:5|numeric'
]
);
Then create your inputs in your view file, using v-model that corresponds to the vue.js data model fields. Underneath it, add a span with an error class (basic red error styling, for example) that only shows up if the errors exist. For example:
<input type="text" name="business-name" v-model="model.business-name" class="input">
<span class="error-text" v-if="errors.has('business-name')" v-text="errors.get('business-name')"></span>
Don't forget to include the app.js file in footer of your view file. Remember to include the tag, and run npm run watch to compile the vue code. This will allow you to validate all errors underneath their input fields.
Forgot to add, have a buttton that has #onclick="onComplete" to run the validate method.

How to use cashier package in laravel 5.2?

I am creating a user subscription plan, For this I am using cashier package in laravel 5.2. I am following the exact way in provided in the tutorial given in laravel document https://laravel.com/docs/5.2/billing. But I am getting the error
ErrorException in FacebookScraperController.php line 1767:
Undefined variable: creditCardToken
my controller code:
$user = User::find(2);
$res = $user->newSubscription('main', 'monthly')->create($creditCardToken);
dd($res);
What should I pass the value inside the $creditCardToken variable.
I tried to give the card details inside this variable. But getting error.
Please help me out.
You will need to pass the subscription plan here with the token generated at the time of card entry.
Here is the step you can follow.
create a view page:
<form action="/subscription" method="POST" id="payment-form">
<span class="payment-errors"></span>
<div class="form-row">
<label>
<span>Card Number</span>
<input type="text" size="20" data-stripe="number">
</label>
</div>
<div class="form-row">
<label>
<span>Expiration (MM/YY)</span>
<input type="text" size="2" data-stripe="exp_month">
</label>
<span> / </span>
<input type="text" size="2" data-stripe="exp_year">
</div>
<div class="form-row">
<label>
<span>CVC</span>
<input type="text" size="4" data-stripe="cvc">
</label>
</div>
<input type="submit" class="submit" value="Submit Payment">
</form>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script type="text/javascript">
Stripe.setPublishableKey('pk_test_TSGgkchoa9iQU4ZQ628a8Auz');
</script>
<script>
$(function() {
var $form = $('#payment-form');
$form.submit(function(event) {
// Disable the submit button to prevent repeated clicks:
$form.find('.submit').prop('disabled', true);
// Request a token from Stripe:
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from being submitted:
return false;
});
});
function stripeResponseHandler(status, response) {
// Grab the form:
var $form = $('#payment-form');
if (response.error) { // Problem!
// Show the errors on the form:
$form.find('.payment-errors').text(response.error.message);
$form.find('.submit').prop('disabled', false); // Re-enable submission
} else { // Token was created!
// Get the token ID:
var token = response.id;
// Insert the token ID into the form so it gets submitted to the server:
$form.append($('<input type="hidden" name="stripeToken">').val(token));
// Submit the form:
$form.get(0).submit();
}
};
</script>
and in your controller:
public function subscription(Request $request)
{
$user = User::find(1);
$creditCardToken = $request->stripeToken;
$res = $user->newSubscription('main', 'pro')
->trialDays(30)
->create($creditCardToken, [
'plan' => 'pro',
'email' => $user->email,
]);
}

Resources