error Call to a member function getChat() on null in package t telegram-bot-sdk - telegram-bot

I'm using the data from telegrams received Webhook but I am faced with this error
Webhook tested properly set.
In your opinion, what is the problem?
This is my code:
Route :
Route::post('setwebhook','BotController#setWebhook');
Route::post('updates','BotController#updates');
BotController :
public function setWebhook()
{
$res = Telegram::setWebhook([
'url' => 'https://example.com/telegram-sdk/public/updates'
]);
return $res;
}
public function updates()
{
$update = Telegram::getWebhookUpdates();
$chat_id = $update->getMessage()->getChat()->getId();
$text = $update->getMessage()->getText();
$name = $update->getMessage()->getChat()->getFirstName();
if ($text == '/start') {
Telegram::sendMessage([
'chat_id' => $chat_id,
'text' => 'Hello World'
]);
}
}

Related

How to generate token with JWT on Laravel 9

The problem is that it does not generate the TOKEN, throwing the following error
TypeError: Lcobucci\JWT\Token\Builder::relatedTo(): Argument #1 ($subject) must be of type string, null given
When I make the request through the post verb, it performs all the previous validation but when it comes to generating the token, the error occurs.
`
public function login(Request $request)
{
$credentials = $request->only('usuario', 'password');
$validator = Validator::make($request->all(), [
'usuario' => 'required',
'password' => 'required'
]);
if ($validator->fails()) {
return response()->json([
'message' => $validator->errors(),
'token' => null
], 404);
}
$user = usuarios::where('usuario', $request->usuario)->first();
if (!$user) {
return response()->json([
'message' => 'Usuario no registrado.',
'token' => null
], 401);
}
$isValid = Hash::check($request->password, $user->password);
if (!$isValid) {
return response()->json([
'message' => 'ContraseƱa incorrecta.'
]);
}
$token = JWTAuth::fromUser($user);
return response()->json([
'message' => 'Usuario logueado correctamente',
'token' => $token
]);
}
`
And my code mode is this
`
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
//AƱadimos la clase JWTSubject
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;
class usuarios extends Model implements JWTSubject
{
use HasFactory, HasApiTokens, Notifiable;
protected $table = 'usuarios';
protected $fillable = [
'tipo_usuario',
'acceso_pv',
'nombre',
'usuario',
'password',
];
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
public $timestamps = false;
}
`

Laravel 9 error route | The GET method is not supported

I am having a problem fetching a list of certain customers (authenticated users) via API. When I use this route in Postman I receive the following error.
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException:
The GET method is not supported for this route. Supported methods:
POST. in file
D:\api\vendor\laravel\framework\src\Illuminate\Routing\AbstractRouteCollection.php
on line 118
api.php
Route::post('/register', [UserAuthController::class, 'register']);
Route::post('/login', [UserAuthController::class, 'login'])
->name('login');
Route::apiResource('/customer', CustomerController::class)
->middleware('auth:api');
Controller
class CustomerController extends Controller
{
public function index()
{
$customers = Customer::all();
return response([ 'customers' =>
CustomerResource::collection($customers),
'message' => 'Successful'], 200);
}
public function store(Request $request)
{
$data = $request->all();
$validator = Validator::make($data, [
'first_name'=>'required|max:120',
'email'=>'required|email|unique:users',
'password'=>'required|min:6'
]);
if($validator->fails()){
return response(['error' => $validator->errors(),
'Validation Error']);
}
$customer = Customer::create($data);
return response([ 'customer' => new CustomerResource($customer),
'message' => 'Success'], 200);
}
public function show(Customer $customer)
{
return response([ 'customer' => new CustomerResource($customer),
'message' => 'Success'], 200);
}
public function update(Request $request, Customer $customer)
{
$customer->update($request->all());
return response([ 'employee' => new CustomerResource($customer),
'message' => 'Success'], 200);
}
public function destroy(Customer $customer)
{
$customer->delete();
return response(['message' => 'Customer deleted']);
}
}
I solved this problem by adding Accept|json/application in headers of Postman.

get data value from jsonResponse Laravel 8

I have two controller
the first one has a register method:
public function register(Request $request)
{
$generalTrait = new GeneralTrait;
$user = new User;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->type = $request->type;
$user->save();
return $generalTrait->returnData('user',$user);
}
and the second also has register method:
public function register(Request $request)
{
$generalTrait = new GeneralTrait;
$user = (new UserAuthController)->register($request);
$admin = Admin::create([
'admin_name' => $request->admin_name,
//'user_id' => $response->user->user_id,
'user_id' => $user_id
]);
//Admin created, return success response
return $generalTrait->returnSuccessMessage('Admin created successfully');
}
when I try to get data from (JsonResponse) $user I find this error:
ErrorException: Undefined property: Illuminate\Http\JsonResponse::$user
returnDate method in GeneralTrait return:
public function returnData($key, $value, $msg = ""){
return response()->json([
'status' => true,
'errNum' => "5000",
'msg' => $msg,
$key => $value
]);
}
I find same Error when I try to get the status from the $response
How can I fix it?
I fix it by replacing returnData with:
public function returnData($key, $value, $msg = ""){
return [
'status' => true,
'errNum' => "5000",
'msg' => $msg,
$key => $value
];}
so to get user_id from user I said:
'user_id' => ($response["user"])->user_id
I wish I knew what my mistake was, and how I could have fixed it some other way

Error: getting unknown property: yii\web\Application::generateid

I have the below code in studentsController.php to add data to 2 tables from a form but im getting error. It is to add to students table, then add some data to the users table too. I feel i'm supposed to add something at the top via "use' keyword but I don't know.please help.
public function actionCreate() {
$model = new model();
$user = new Users();
if ($model->load(Yii::$app->request->post())) {
$model->id = Yii::$app->generateid->getGUID(); //this line caused the error
$model->save();
$studentId = $model->id;
if($user->load(Yii::$app->request->post()))
{
$user->id = $model->id;
$user->firstname = $model->firstname;
$user->lastname = $model->lastname;
$user->username = $model->phone;
$user->password = 'pass123'; //default password
$user->role = 'student';
$user->save(false);
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'user' => $user,
]);
}
}
You seem to miss generateid in your web.php
It should be something like this
GenerateIDs.php inside #app/components folder
<?php
namespace app\components;
class GenerateIDs extends \yii\base\Component
{
public function getGUID()
{
//do your stuff here
}
//....
}
then in your #app/config/web.php you have something like
<?php
return [
'components' => [
'generateid' => [
'class'=>'app\components\GenerateIDs',
// other configurations for the component
],
],
];
then you can use it in your app as you wish
public function actionCreate() {
$model = new model();
$user = new Users();
if ($model->load(Yii::$app->request->post())) {
$model->id = Yii::$app->generateid->getGUID(); //this line caused the error
$model->save();
$studentId = $model->id;
if($user->load(Yii::$app->request->post()))
{
$user->id = $model->id;
$user->firstname = $model->firstname;
$user->lastname = $model->lastname;
$user->username = $model->phone;
$user->password = 'pass123'; //default password
$user->role = 'student';
$user->save(false);
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'user' => $user,
]);
}
Please take a look at Yii2 guide on Components

call model in zend form using dependencies + zend framework 2

I am trying to fetch my category model in zend form for working out with select element with zend framework 2.
after lot of code searching I found I can either inject or pull dependencies.
Following code I did in my module.php
I want categoryTable.php(model) file in my CategoryForm.php
public function getServiceConfig()
{
return array(
'factories' => array(
'Category\Model\CategoryTable' => function($sm) {
$tableGateway = $sm->get('CategoryTableGateway');
$table = new CategoryTable($tableGateway);
//echo "<pre>";print_r($table);echo "</pre>";
return $table;
},
'CategoryTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Category());
return new TableGateway('Of_Restaurants_Category', $dbAdapter, null, $resultSetPrototype);
},
'Category\Form\CategoryForm' => function ($sm) {
$service = $sm->get('Category\Model\CategoryTable');
$form = new Form;
$form->setService($service);
return $form;
}
),
);
}
then I put following code in my controller.
$form = $this->getServiceLocator()->get("Category\Form\CategoryForm");
Then I Put following code in my CategoryForm.php
public function getCategoryTable()
{
if (!$this->categoryTable) {
$sm = $this->getServiceLocator();
$this->categoryTable = $sm->get('Category\Model\CategoryTable');
}
return $this->categoryTable;
}
And then I call it in same file like this way
public function __construct($name = null)
{
parent::__construct('category');
echo "<pre>";print_r($this->getCategoryTable());die;
.... other code
I found this error
Fatal error: Call to undefined method Category\Form\CategoryForm::getServiceLocator() in D:\wamp\www\zendapp\module\Category\src\Category\Form\CategoryForm.php on line 120
please help. and am I missing something?
I found the solution
Step :1
Here is my module.php code
public function getServiceConfig()
{
return array(
'invokables' => array(
'Category\Form\CategoryForm' => 'Category\Form\CategoryForm',
),
'factories' => array(
'Category\Model\CategoryTable' => function($sm) {
$tableGateway = $sm->get('CategoryTableGateway');
$table = new CategoryTable($tableGateway);
//echo "<pre>";print_r($table);echo "</pre>";
return $table;
},
'CategoryTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Category());
return new TableGateway('Of_Restaurants_Category', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
Step :2
Then in controller I made this change
// $form = new CategoryForm();
// Service locator now injected
$form = $this->getServiceLocator()->get('Category\Form\CategoryForm');
Step :3
Then In my categoryForm.php I made below changes
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
protected $serviceManager;
public function getCategoryTable()
{
if (!$this->categoryTable) {
$sm = $this->getServiceManager();
$this->categoryTable = $sm->get('Category\Model\CategoryTable');
}
return $this->categoryTable;
}
protected function getCatList()
{
$groups = $this->getCategoryTable()->fetchAll();
return $groups;
}
public function getServiceManager()
{
if ( is_null($this->serviceManager) ) {
throw new Exception('The ServiceManager has not been set.');
}
return $this->serviceManager;
}
public function setServiceManager(ServiceManager $serviceManager)
{
$this->serviceManager = $serviceManager;
// Call the init function of the form once the service manager is set
$this->init();
return $this;
}
public function __construct($name = null) // constructor I finished immediately
{
parent::__construct('category');
}
I add INIT() function to fetch servicemanager
public function init()
{
$this->setAttribute('method', 'post');
$options = array();
foreach ($this->getCatList() as $cat) {
$options[$cat->id] = $cat->title;
}
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'parent_id',
'options' => array(
'label' => 'Parent Category',
'empty_option' => 'Please choose Parent Category',
'value_options' => $options,
),
));
}
Hope this will help who are new ZF2.