Pusher trigger() method is giving error 500 - laravel

So I was building chat functionality in laravel for a website using Pusher , everything was working fine till yesterday. But when I run the chat module again, I found out that trigger() method is giving error (Internal server error).
`
use App\Http\Controllers\Controller;
use App\Model\Chatting;
use App\Model\Seller;
use App\Model\Shop;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Events\Message;
use Pusher\Pusher;
class ChattingController extends Controller
{
public function seller_message_store(Request $request)
{
//return 'hello';
if ($request->message == '') {
Toastr::warning('Type Something!');
return response()->json('type something!');
} else {
$shop_id = Shop::where('seller_id', auth('seller')->id())->first()->id;
$message = $request->message;
$time = now();
DB::table('chattings')->insert([
'user_id' => $request->user_id, //user_id == seller_id
'seller_id' => auth('seller')->id(),
'shop_id' => $shop_id,
'message' => $request->message,
'sent_by_seller' => 1,
'seen_by_seller' => 0,
'created_at' => now(),
]);
//return auth('seller')->user()->seller_plan_id;
if(auth('seller')->user()->seller_plan_id>2){
// pusher
$options = array(
'cluster' => 'ap2',
'useTLS' => false
);
$pusher = new Pusher('app auth key','app secret','app_id',$options);
//return $request->user_id;
$data = ['from' => auth('seller')->id(), 'to' => $request->user_id,'message'=>$request->message]; // sending from and to user id when pressed enter
$pusher->trigger('channel-name', 'event', $data);//here is the issue
}
return response()->json(['message' => $message, 'time' => $time]);
}
}
}
`
If I comment out the trigger line, it gives no error.
It was working completely fine till yesterday.

The version 5.0 of pusher is broken and has given me errors in the past.
What you could do is, change
"pusher/pusher-php-server": "5.0"
to
"pusher/pusher-php-server": "^5.0"
And then run the command composer update

Related

How do I run a phpunit test on Redis pub/sub?

I'm building a messenger system with Redis publishing on the Laravel end and subscribing on a node server. I would like to test what is stored in the redis pub method using PHPUnit, but I have no idea where to start.
Controller
class MessageController extends Controller
{
public function store(Conversation $conversation, Request $request)
{
$user = Auth::user();
$message = Message::create([
'body' => $request->input('message'),
'conversation_id' => $conversation->id,
'sender_id' => $user->id,
'type' => 'user_message'
]);
$redis = Redis::connection();
$data = new MessageResource($message);
$redis->publish('message', $data);
}
}
Current Test
/** #test */
public function a_user_can_send_a_message()
{
$this->actingAs($user = User::factory()->create());
$message = Message::factory()->make(['sender_id' => $user->id]);
$conversation Conversation::factory()->create();
$response = $this->json('POST', '/api/message/'. $conversation->id, ['message' => $message->body])
->assertStatus(201);
$response->assertJsonStructure([
'data' => [
'body',
'sender',
]
]);
}
Essentially what I'm trying to see is if message has been published on Redis. I'm unsure how to do this, and I think you would probably need to clear the message from Redis after, would you not?
Your test should be like this:
public function test_a_user_can_send_a_message()
{
$redisSpy = Redis::spy();
$redisSpy->shouldReceive('connection')->andReturnSelf();
$this->actingAs($user = User::factory()->create());
$message = Message::factory()->make(['sender_id' => $user->id]);
$conversation = Conversation::factory()->create();
$this->postJson("/api/message/{$conversation->id}", ['message' => $message->body]);
$this->assertDatabaseCount('messages', 1);
$redisSpy->shouldHaveReceived('publish')
->with('message', new MessageResource(Message::first()));
}
As you can see, I have added Redis::spy(); this is going to allow is to "spy" what is called from Redis. You can still mock methods, and we have to do so, because you use Redis::connect(); and then $redis->publish(...), so we will return the spy when connect is called, that is why we do shouldReceive('connection')->andReturnSelf().
At the end of the code, we check that $redis->publish was called with parameters 'message' and a resource with the desired message. Both must match for this assertion to pass, else you will see a mock error.

Not getting data for authenticated user from database in Laravel for setting stripe

I've been trying to get the saved customer id for stripe from database but with no luck.
It works everywhere else, I could get it and save it again if I wanted, but whenever I try to use it in payment intent to automatically renew a subscription, it gives me this error: Trying to get property 'stripecustomerid' of non-object.
this is the bit of the stripe code for recurring charge where the error happens:
public function renew($subscription)
{
\Stripe\Stripe::setApiKey('sk_test_XXXXXXXX');
header('Content-Type: application/json');
try {
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
$user = \Auth::user();
$payment_methods = \Stripe\PaymentMethod::all([
'customer' => $user->stripecustomerid,
'type' => 'card'
]);
$payment_intent = \Stripe\PaymentIntent::create([
'amount' => $subscription->plan->stripePrice(),
'currency' => 'usd',
'customer' => $user->stripecustomerid,
'payment_method' => $payment_methods->data[0]->id,
'off_session' => true,
'confirm' => true,
]);
echo json_encode([
'paymentIntent' => $payment_intent,
]);
}
catch (\Exception $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
}
and stripecustomerid is the name of the column where I saved the customer id.
I can print it in another function, and it works when I use GET, but it just doesn't work when the subscription tries to renew.

Stripe & Laravel how to upgrade or downgrade session subscription?

I have some issues using the Laravel Cashier for creating subscriptions.
First, from my backend I am creating a Package, which calls the following two Strip functions:
public function createStripeProduct(array $data)
{
$product = $this->stripe->products->create([
'name' => $data['title']." ".appName(),
]);
return $product->id;
}
public function createStripePrice(array $data)
{
$price = $this->stripe->prices->create([
'unit_amount' => $data['price'] * $this->multiple,
'currency' => $this->currency,
'recurring' => ['interval' => 'month'],
'product' => $data['stripe_prod_id'],
]);
return $price->id;
}
Then in my Controller, I am creating the session:
public function create(Request $request)
{
$key = config('services.stripe.secret');
$stripe = new Stripe\StripeClient($key);
$stripeCustomer = $user->createOrGetStripeCustomer();
$checkout_session = $stripe->checkout->sessions->create([
'customer' => $stripeCustomer['id'],
'success_url' => route('frontend.user.account'),
'cancel_url' => route('frontend.user.account'),
'payment_method_types' => ['card'],
'line_items' => [
[
'price' => $request->stripe_price_id,
'quantity' => 1,
],
],
'mode' => 'subscription',
'allow_promotion_codes' => true,
]);
return $checkout_session['id'];
}
Everything is working so far, but with the implementation, I can subscribe one use multiple times to the same or to a different Package.
How can I prevent this from happening and also how to implement a future upgrade/downgrade of the Package?
To answer your two questions:
1) I can subscribe one use multiple times to the same or to a different Package. How can I prevent this from happening
Your code is fetching a Stripe Customer object in createOrGetStripeCustomer(). You can list all Subscriptions on the Customer with https://stripe.com/docs/api/subscriptions/list#list_subscriptions-customer and then check if you want to create an additional CheckoutSession Subscription on that Customer.
2) how to implement a future upgrade/downgrade of the Package?
You would use the code snippets here: https://stripe.com/docs/billing/subscriptions/upgrade-downgrade#changing where you update the Subscription's SubscriptionItem with a new Price ID.
$sub = \Stripe\Subscription::update('sub_123', [
'cancel_at_period_end' => false,
'proration_behavior' => 'create_prorations',
'items' => [
[
'id' => $subscription->items->data[0]->id,
'price' => 'price_456', // the new Price to update to
],
],
]);

Users Controller does not exist

I'm building a CMS in Laravel 5.8 with an in-built Authentication system. My app was working fine but suddenly it starts giving me an error as ReflectionException : Class App\Http\Controllers\Users does not exist on command php artisan route:list -v. However, if i define a new resource route, then that new route page works fine. It means, route file is getting saved but gives error while listing the routes.
I have not created any file named as Users but my user controller file name is UserController
Below is the structure of my application:
cms -> project folder
app
Http
Controllers
Auth
RegisterController.php
LoginController.php and other Auth files
backend
UserController.php and my other controller files
Below is my route file
Auth::routes();
Route::group(['as'=>'cms.' ,'prefix'=>'cms'],function(){
Route::get('/', 'backend\Dashboard#index')->name('dashboard');
Route::resource('/user-management', 'backend\UserController');
});
Below is my UserController file residing in backend folder
<?php
namespace App\Http\Controllers\backend;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redirect;
use Auth;
use App\Models\backend\Admin;
use App\Models\backend\Menu;
use App\Models\backend\Submenu;
use Config;
use illuminate\Support\Facades\Validator;
class UserController extends Controller
{
public function __construct()
{
$this->middleware('auth:admin');
}
public function AuthRouteAPI(Request $request)
{
return $request->user();
}
public function index()
{
// GET THE CURRENT LOGGED IN USE
$user = Auth::user();
// CODE FOR GETTING MENU LIST FOR CURRENT USER STARTS
$menutable = (new Menu)->getTable();
$arrUserMenu = $user->getUserMenus($menutable);
// CODE FOR GETTING MENU LIST FOR CURRENT USER ENDS
$cms_users = Admin::withTrashed()->get();
return view('backend.pages.users.index', ['arrUserMenu'=>$arrUserMenu, 'cms_users'=>$cms_users]);
}
public function create()
{
// GET THE CURRENT LOGGED IN USE
$user = Auth::user();
// CODE FOR GETTING MENU LIST FOR CURRENT USER STARTS
$menutable = (new Menu)->getTable();
$arrUserMenu = $user->getUserMenus($menutable);
// CODE FOR GETTING MENU LIST FOR CURRENT USER ENDS
return view('backend.pages.users.create', ['arrUserMenu'=>$arrUserMenu]);
}
public function store(Request $request)
{
$rules = [
'name' => 'required|min:'.Config::get('cms_const.USER_NAME_MIN_LEN').'|max:'.Config::get('cms_const.USER_NAME_MAX_LEN').'|regex:/(^[A-Za-z ]+$)+/',
'usrmail' => 'required|email|unique:cms_users,email|max:'.Config::get('cms_const.USER_EMAIL_MAX_LEN'),
'usrname' => 'required|min:'.Config::get('cms_const.USER_ID_MIN_LEN').'|max:'.Config::get('cms_const.USER_ID_MAX_LEN').'|regex:/(^[A-Za-z0-9._]+$)+/|unique:cms_users,username',
'usrpwd' => 'required|min:'.Config::get('cms_const.USER_PWD_MIN_LEN').'|max:'.Config::get('cms_const.USER_PWD_MAX_LEN').'|regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-_]).{7,}$/'
];
$msgs = [
'name.required' => 'Please enter name',
'name.min' => 'Name should not be less then '.Config::get('cms_const.USER_NAME_MIN_LEN').' characters',
'name.max' => 'Name should not be more then '.Config::get('cms_const.USER_NAME_MAX_LEN').' characters',
'name.regex' => 'Only alphabets are allowed in name',
'usrmail.required' => 'Please enter email',
'usrmail.email' => 'Invalid email',
'usrmail.unique' => 'Email already exist',
'usrmail.max' => 'Email should not be more then '.Config::get('cms_const.USER_EMAIL_MAX_LEN').' characters',
'usrname.required' => 'Please enter the user name',
'usrname.min' => 'User name should not be less then '.Config::get('cms_const.USER_ID_MIN_LEN').' characters',
'usrname.max' => 'User name should not be more then '.Config::get('cms_const.USER_ID_MAX_LEN').' characters',
'usrname.regex' => 'Only Alphabets, Numbers, Dot and Underscore allowed in user name',
'usrname.unique' => 'User name already exist',
'usrpwd.required' => 'Please enter the password',
'usrpwd.min' => 'Password should not be less then '.Config::get('cms_const.USER_PWD_MIN_LEN').' characters',
'usrpwd.max' => 'Password should not be more then '.Config::get('cms_const.USER_PWD_MAX_LEN').' characters',
'usrpwd.regex' => 'Invalid password format',
];
$this->validate($request, $rules, $msgs);
Admin::create([
'name' => $request->name,
'username' => $request->usrname,
'password' => bcrypt($request->usrpwd),
'email' => $request->usrmail,
]);
return redirect()->route('cms.user-management.index')->with('success','New user account created successfully.');
}
public function edit($id)
{
if(!$id)
{
return redirect()->route('cms.user-management.index');
die;
}
$arrRecord = Admin::find($id);
if(is_null($arrRecord))
{
return redirect()->route('cms.user-management.index')->withErrors(['error'=>'Record you are trying to edit does not exist']);
die;
}
// GET THE CURRENT LOGGED IN USE
$user = Auth::user();
// CODE FOR GETTING MENU LIST FOR CURRENT USER STARTS
$menutable = (new Menu)->getTable();
$arrUserMenu = $user->getUserMenus($menutable);
// CODE FOR GETTING MENU LIST FOR CURRENT USER ENDS
return view('backend.pages.users.edit', ['arrUserMenu'=>$arrUserMenu, 'arrRecord'=>$arrRecord]);
}
public function update(Request $request, $id)
{
$rules = [
'name' => 'required|min:'.Config::get('cms_const.USER_NAME_MIN_LEN').'|max:'.Config::get('cms_const.USER_NAME_MAX_LEN').'|regex:/(^[A-Za-z ]+$)+/',
'usrmail' => 'required|email|max:'.Config::get('cms_const.USER_EMAIL_MAX_LEN'),
'usrpwd' => 'nullable|min:'.Config::get('cms_const.USER_PWD_MIN_LEN').'|max:'.Config::get('cms_const.USER_PWD_MAX_LEN').'|regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-_]).{7,}$/'
];
$msgs = [
'name.required' => 'Please enter name',
'name.min' => 'Name should not be less then '.Config::get('cms_const.USER_NAME_MIN_LEN').' characters',
'name.max' => 'Name should not be more then '.Config::get('cms_const.USER_NAME_MAX_LEN').' characters',
'name.regex' => 'Only alphabets are allowed in name',
'usrmail.required' => 'Please enter email',
'usrmail.email' => 'Invalid email',
'usrmail.max' => 'Email should not be more then '.Config::get('cms_const.USER_EMAIL_MAX_LEN').' characters',
'usrpwd.min' => 'Password should not be less then '.Config::get('cms_const.USER_PWD_MIN_LEN').' characters',
'usrpwd.max' => 'Password should not be more then '.Config::get('cms_const.USER_PWD_MAX_LEN').' characters',
'usrpwd.regex' => 'Invalid password format',
];
$this->validate($request, $rules, $msgs);
$arrRecord = Admin::find($id);
if(is_null($arrRecord))
{
return redirect()->route('cms.user-management.index')->withErrors(['error'=>'Record you are trying to edit does not exist']);
die;
}
$arrRecord->name = $request->input('name');
$arrRecord->email = $request->input('usrmail');
if($request->input('usrpwd'))
{
$arrRecord->password = bcrypt($request->input('usrpwd'));
}
$arrRecord->save();
return redirect()->route('cms.user-management.index')->with('success','User account details updated successfully.');
}
public function destroy($id)
{
try
{
$user = Admin::findOrFail($id);
$user->delete();
return response()->json(['success'=>'Record successfully deleted', 'status'=>'Suspended']);
}
// catch(Exception $e) catch any exception
catch(ModelNotFoundException $e)
{
return response()->json(['error'=>'Record you are trying to delete does not exist']);
}
}
}
I have tried the below commands and they all run successfully but none resolved the error
php artisan clear-compiled
composer dump-autoload
php artisan optimize
php artisan route:cache
Don't know from where this Users controller class in being referenced.
Can anyone help me in this regard as I'm badly stuck in my development.
Much Regards,
Javed
#ClémentBaconnier the error is resolved now. I made the changes in api.php to Route::middleware('auth:api')->get('/user', 'backend\Users#AuthRouteAPI'); and now all my routes are listed. Thanks u soooo much for ur advice.

TaskQueue.php Error - Laravel 5 & Forge

When running any Posts and Model::create function within Laravel I am being greeted with the below error;
FatalErrorException in TaskQueue.php line 13:
Interface 'GuzzleHttp\Promise\TaskQueueInterface' not found
This was working perfectly fine on my local machine but as soon as the website was put onto a server with Forge it has started to show this error.
It looks like the server is trying to use the Queue function with Laravel but my code doesn't ever make use of this;
public function postCreateCustomer(){
$input = Request::all();
$customer = Customers::create([
'customer_name' => $input['customer_name'],
'customer_url' => $input['customer_url']
]);
$password = str_random(8);
$pass = Hash::make($password);
$user = User::create([
'name' => $input['name'],
'email' => $input['email'],
'password' => $pass,
'user_type' => 3,
'active_customer' => $customer->id,
]);
Access::create([
'user_id' => $user->id,
'customer_id' => $customer->id
]);
$the_content = '<p>Hello '.$input['name'].' ('.$input['customer_name'].'),</p>
<p>Thank you for creating an account. </p>
<p>Your login details are listed below;</p>
<p><strong>Username</strong>: '.$input['email'].'<p>
<p><strong>Password</strong>: '.$password.'<p>';
$contactEmail = $input['email'];
Mail::send('emails.default', ['the_content' => $the_content, 'the_heading' => 'Customer Account Created'], function ($message) use ($contactEmail) {
$message->subject("Customer Account Created");
$message->to($contactEmail);
});
Session::flash('success_message', 'The new customer has been created.');
return Redirect::to('/customers');
}
I faced the same problem and I found that was caused by the class "TaskQueueInterface" had not be found.
The following is my solution:
open the folder: /vendor/guzzlehttp/promises/src
edit TaskQueue.php
modify "class TaskQueue implements TaskQueueInterface" to "class TaskQueue"
After doing the above, stay tuned for the official release.

Resources