Laravel 5.5 cashier test subscriptions with short trial - laravel

I tested web site subscriptions users through stripe. Website uses php laravel 5.5 with cashier on linux server.
How to make a short grace period for tests?
I use this code:
$user->newSubscription('main', $request->get('subs_type'))
->trialUntil(Carbon::now()->addSeconds(330))
->create($request->get('stripeToken'), [
'email' => $user->email,
]);
instead of the usual
$user->newSubscription('main', $request->get('subs_type'))
->trialDays(1)
->create($request->get('stripeToken'), [
'email' => $user->email,
]);
But after the end of the short trial laravel cashier method onTrial() returns true. Since the method compares dates, not hours or minutes.
/**
* Determine if the subscription is within its trial period.
*
* #return bool
*/
public function onTrial()
{
if (! is_null($this->trial_ends_at)) {
return Carbon::today()->lt($this->trial_ends_at);
} else {
return false;
}
}
Are there any practices that will correct this.
Of course, I do not have to edit the source of laravel

Related

Stripe One Time payment or Single Payment is not working using laravel/cashier

I am trying to setup Stripe one time payment in an application but getting this error. I am using laravel package for stripe i.e laravel/cashier
As per Indian regulations, export transactions require a description. More info here: https://stripe.com/docs/india-exports
I have added the description as per regulations provided by stripe in code but still I am facing this issue.
This is the code I am using:
$user = auth()->user(); $paymentMethod = $request->payment_method; try { $user->createOrGetStripeCustomer(); $user->updateDefaultPaymentMethod($paymentMethod, [ 'currency' => 'INR', 'description' => 'Software development services', ]); $user->charge($request->fees*100, $paymentMethod, ['off_session' => true]); } catch (\Exception $exception) { dd($exception->getMessage()); }
First currency was in USD. I have changed currency from 
USD
to 
INR
 but still getting this.
Meanwhile in my stripe dashboard, Payment is in incomplete mode.
I have used all possible fix but it is not working.
Is there any way to fix this ?

Lumen : 1s, Laravel : 5s for a simple api call?

So I started a project not long ago for an API on Laravel, and I thought why not give Lumen a shot. But in the end, I want to use Sanctum, Socialite, etc... And I read pretty much everywhere that the performance difference is not that big nowadays anyway.
So I migrated my code from Lumen to Laravel, and after a few tweaks, everything works as before... Except that now a very simple API call takes 5s. Granted, it might be my setup - wsl2 isn't particularly fast. But still, the same call in Lumen was taking ~1000ms.
Route::post('register', [AuthController::class, 'register']);
Controller:
public function register(Request $request): JsonResponse {
$this->validate($request, [
'phone' => 'required|string|phone',
'phone_country' => 'required_with:phone',
]);
$phone = phone($request->get('phone'), [$request->get('phone_country')]);
try {
$user = User::createByPhone($phone);
return response()->json(['user' => $user->id, 'message' => 'SMS_SENT'], 201);
} catch (\Exception $e) {
return response()->json(['message' => 'User Registration Failed - ', 'error' => $e], 409);
}
}
Function in model:
public static function createByPhone($phone) {
return DB::transaction(function () use ($phone) {
$user = User::create();
$user->phoneNumbers()->create([
'did' => $phone
]);
return $user;
});
}
So, pretty simple stuff. Now, why is that taking so long? ~6000ms. Am I missing something?
(On a more general note, is there a way to cut from Laravel things that aren't needed for an API only?)
Thanks ahead.
I don't see anything really wrong with your code. I guess this has something to do with the speed wsl2 can read files. We had issues with windows machines and Laravel in Docker. We added Swoole to our project and this helped alot on WSL2.
Laravel now has a first party package called Octane to add Swoole to your project. You can try and install that to see if it helps.

How to increase session vue/cli 4.0.5 / vuex 3 / Laravel 6 Backend REST API app?

I make #vue/cli 4.0.5 / vuex 3 app with data reading from Laravel 6 Backend REST API app with passport
as auth and I want to set bigger time of logged session during development and for this in my
app/Http/Controllers/AuthController.php I changed time and session
protected function respondWithToken($token)
{
$loggedUser = $this->guard()->user();
$user_avatar_path = User::getUserAvatarPath($loggedUser->id, $loggedUser->avatar);
$filenameData = User::setUserAvatarProps($loggedUser->id, $loggedUser->avatar, true);
return response()->json([
'access_token' => $token,
'user' => $loggedUser,
'token_type' => 'bearer',
'user_avatar_path' => $user_avatar_path,
'filenameData' => $filenameData,
'expires_in' => $this->guard('api')->factory()->getTTL() * 660
]);
}
But seems this chages does not influence my app. Did I miss some options?
2) Also as I can see parameter expires_in starts its time from login time and that seems to me not what I want,
as I want this parameter works as time from last work in the app.
In other way any request to backend part I have to refresh this this parameter...
MODIFIED :
I read in “Passport Token Lifetimes” :
By default, Passport issues long-lived access tokens that expire after
one year
Looks like that not the issue, as I have default options(one year).
Are the some options on vuejs side, when I use vue-resource
Here https://github.com/pagekit/vue-resource/blob/master/docs/api.md
I see that vue-resource has timeout (number) option, but I am not sure how it is applicable?
I login request :
Vue.http.post(apiUrl + '/auth/login', userCredentials).then(response => {
...
?
MODIFIED #2:
I have in backend app:
"php": "^7.2",
"barryvdh/laravel-cors": "^0.11.4",
"laravel/framework": "^6.2",
"laravel/passport": "^8.1",
And on Vue/Cli part :
"store": "^2.0.12",
"vue": "^2.6.10",
"vue-js-modal": "^1.3.31",
"vue-resource": "^1.5.1",
"vue-router": "^3.1.3",
"vuex": "^3.1.2"
Actualy I want in backend app in config/app.php to set some parameter like
'personal_access_tokens_expire_in_hours' => 24, // Actually I think about value = 1
and to user it in 2 places :
in app/Providers/AuthServiceProvider.php :
public function boot()
{
$this->registerPolicies();
Passport::routes();
$personal_access_tokens_expire_in_hours = config('app.personal_access_tokens_expire_in_hours',24);
Passport::personalAccessTokensExpireIn(Carbon::now()->addHours($personal_access_tokens_expire_in_hours));
}
and in app/Http/Controllers/AuthController.php :
public function login(Request $request)
{
$credentials = request(['email', 'password']);
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
'remember_me' => 'boolean'
]);
if ( ! Auth::attempt($credentials)) {
return response()->json(['message' => 'Unauthorized'], 401);
}
$user = $request->user();
$user->last_logged= Carbon::now(config('app.timezone'));
$user->save();
$tokenResult = $user->createToken('Access Token');
$token = $tokenResult->token;
if ($request->remember_me) {
$personal_access_tokens_expire_in_hours = config('app.personal_access_tokens_expire_in_hours',24);
$token->expires_at = Carbon::now()->addHours($personal_access_tokens_expire_in_hours);
} // Though Ronak Dhoot wrote that $token->expires_at does not infleunce anything.
I added last_logged field to users and fill it on any login.
With default personalAccessTokensExpireIn value in 1 day I login in the system in the middle of my working day.
I turn off computer in the end of the day and opening it next morning I can enter my app with login I made
yesterday(24 hours has not passed yet). That seems not safe for me.
I would prefer personalAccessTokensExpireIn = 1 hour and refresh it ANY authorized request from my vue/cli app.
In which way that could be done? Working on vue/cli apps with baxkend api which way do you use?
I have some prior work with auth/jwt and in app/Http/Controllers/API/AuthController.php I found methods :
public function refresh() // THIS METHOD IS NOT CALLED ANYWHERE
{
return $this->respondWithToken($this->guard()->refresh());
}
protected function respondWithToken($token)
{
$loggedUser= $this->guard()->user();
$user_avatar_path= User::getUserAvatarPath($loggedUser->id, $loggedUser->avatar);
$filenameData = User::setUserAvatarProps($loggedUser->id, $loggedUser->avatar, true);
$usersGroups= User::getUsersGroupsByUserId($loggedUser->id, false);
return response()->json([
'access_token' => $token,
'user' => $loggedUser,
'token_type' => 'bearer',
'user_avatar_path' => $user_avatar_path,
'filenameData' => $filenameData,
'usersGroups' => $usersGroups,
'expires_in' => $this->guard('api')->factory()->getTTL() * 9360 // TOFIX
]);
}
Can refresh() be used in my passport issue somehow?
Thanks!
The createToken() method creates a Personal Access Token. By default, these tokens expire after 1 year (or 100 years, if created by laravel/passport <= 1.0.11). The expiration time for this type of token is not modified by the Passport::tokensExpireIn() or Passport::refreshTokensExpireIn() methods.
laravel/passport >= 7.0.4
Passport version 7.0.4 added a new method Passport::personalAccessTokensExpireIn() that allows you to update the expiration time for personal access tokens. If you are on this version or later, you can add this method call to your AuthServiceProvider::boot() method.
Passport::personalAccessTokensExpireIn(Carbon::now()->addDays(1));
laravel/passport < 7.0.4
If you are not yet on passport version 7.0.4, you can still modify the personal access token expiration time, but it is more manual. You will need to enable a new instance of the personal access grant with your desired expiration time. This can also be done in your AuthServiceProvider::boot() method.
$server = $this->app->make(\League\OAuth2\Server\AuthorizationServer::class);
$server->enableGrantType(new \Laravel\Passport\Bridge\PersonalAccessGrant(), new \DateInterval('P100Y'));
Note:
Modifying the expires_at field in the database will not do anything. The real expiration date is stored inside the token itself. Also, attempting to modify the exp claim inside the JWT token will not work, since the token is signed and any modification to it will invalidate it. So, all your existing tokens will have their original expiration times, and there is no way to change that. If needed, you will need to regenerate new tokens.
PS:
These methods should be called from the boot method of your AuthServiceProvider.

Update Method in Laravel

I'm new to Laravel. I am using laravel 5.4 and trying to validate and update data in a model. Code looks like this:
Route
Route::resource ('contribution-structure', 'ContributionStructureController');
ContributionStructureController
public function update(Request $request, $id)
{
//
$data = $this->validate($request, [
'employer_name' => 'required|min:3',
]);
$plansubmission = PlanSubmission::find($id);
$plansubmission->update($data);
}
The validation works but when I update I get an error saying:
Argument 1 passed to Illuminate\Database\Eloquent\Model::update() must
be of the type array, null given, called in
C:\xampp\htdocs\tapp\app\Http\Controllers\ContributionStructureController.php
on line 84 and defined
The validator doesn't return anything in versions earlier than Laravel 5.5. To get your code to work I would recommend updated to that latest version. Especially for new projects, you should always start with the latest stable version.
If you don't want to update you need to pull the data from the request after validating.
public function update(Request $request, $id)
{
$this->validate($request, [
'employer_name' => 'required|min:3',
]);
$data = $request->only('employer_name');
$plansubmission = PlanSubmission::find($id);
$plansubmission->update($data);
}
Today i told about the update method in php framework laravel there is an error message gives when we apply update method in laravel
when we build the update method to update the data of the database table we face some issues for example
The controller does not fetch the id
The Route problem which route is good PUT, get, Post, Patch
and the laravel version problem
first the controller issue
public function Delivery_charges_update(Request $request, $id)
{
// return $request->all();
$request->validate([
'start-km' => 'required',
'end-km' => 'required',
'amount' => 'required',
]);
$data = Deliverycharges::find($id);
$data->start_km = $request->get('start-km');
$data->end_km = $request->get('end-km');
$data->amount = $request->get('amount');
$data->update();
return redirect('/SuperAdmin/Delivery_charges');
}
then second the route issue you can make route by post method because it is best
Route::post('/Delivery_charges_update/{id}', 'SettingController#Delivery_charges_update');
then third the laravel version issue
so the latest version of laravel is 5.5
and this all issues solution is valid for this laravel version

Should processing logic of STRIPE be in the Laravel controller or in the validator?

I am a newcomer to laravel. I have a controller ProductController like this
public function buy(Request $request, User $user) {
\Stripe\Stripe::setApiKey("sk_test_xxxxxxxxxxxxxxxxxxxxxxxx");
$token = $_POST['stripeToken'];
$charge = \Stripe\Charge::create([
'amount' => 100,
'currency' => 'aud',
'description' => 'Example charge',
'source' => $token,
]);
if ($charge->status === "succeeded") {
//-- Processing... --//
}
I would like to ask the more appropriate design style, should I put the part of STTRIE in other places, such as the validator.
If yes, it is to make a rule and a request than verify it in the validator ?
Can someone tell me how to use the rule in the request?
Creating a Stripe charge is not request validation. It's an API call to Stripe. So, it should definitely not stay in the validator.
You can have this logic in a controller for small apps, but for medium/large scale apps with abstraction (e.g. if you want to have the option later to change the payment provider from Stripe to say Braintree), it should be in a service class.
Also, never use $_POST directly. Use $request->input instead. As a thumb rule, if you have 2 ways to do something in code, always use the way that implements higher level libraries (libraries > then framework > then core PHP).
To write the validation using Laravel 5.5+
public function buy(Request $request, User $user)
{
// first define your rules
$rules = [
'amount' => 'required|numeric'
];
$validatedData = $request->validate($rules);
// The purchase is valid...
}
For Laravel 5.0 - 5.4:
public function buy(Request $request, User $user)
{
// first define your rules
$rules = [
'amount' => 'required|numeric'
];
$validatedData = $this->validate($rules);
// The purchase is valid...
}
The typical responsibilities of a controller in my opinion:
Take in a request
Return a response
I think it is probably fine to have one conditional or validation check.

Resources