Symfony: Webhook End Point Problems - symfony

I am having trouble with Webhook Endpoints.
#[Route("/web_hook", name: 'web_hook')]
public function webhook(Request $request)
{
$data = json_decode($request->getContent(), true);
if ($data === null){
throw new \Exception('bad bad');
}
$txt = 'samle of some text text text';
$myfile = fopen("test.txt", "w") or die("Unable to open file!");
fwrite($myfile, $txt);
fwrite($myfile, $data->id);
fclose($myfile);
$response = new Response();
$response->setStatusCode(200);
return $response;
}
I am having 0 luck getting it to work, I am sending a POST request to it VIA Postman and it keeps coming back with error 500.
When I visit then URL it gives me this error
"Cannot autowire argument $request of "App\Controller\WebHookController::webhook()": it references class "Symfony\Component\HTTPFoundation\Request" but no such service exists.
"
I based this method off of
https://symfonycasts.com/screencast/stripe-level2/webhook-endpoint-setup.
any ideas on what im doing wrong would be greatly appreciated.

if you get error message like this
Cannot autowire argument $request of
"App\Controller\WebHookController::webhook()": it references class
"Symfony\Component\HTTPFoundation\Request" but no such service exists.
mean this service is not available. please try install http-foundation component first.
composer require symfony/http-foundation
and try to change use Symfony\Component\HTTPFoundation\Request to use Symfony\Component\HttpFoundation\Request

Related

Set telegram webhook in custom module on drupal 8

I created a module and implemented my Telegram bot code in /src/Controller/BotController.php. Now I want to set a webhook and use https://api.telegram.org/bot<token>/setwebhook?url=https://<my-site>/<my-module-path-in-"name.routing.yml">.
The webhook is set, but my code doesn't work and gives me a 500 error.
How can I fix this?
EDIT:
My code:
<?php
namespace Drupal\telegram\Controller;
use Drupal\Core\Controller\ControllerBase;
class TelegramController extends ControllerBase {
public function telegram() {
$update = file_get_contents("php://input");
$update = json_decode($update, TRUE);
$chatId = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];
if (isset($chatId) and isset($message)) {
sendMessage($chatId, $message);
$url = "https://api.telegram.org/bot504387877:AAFHnQe-AdscpSZN42yY-JYem5jwdJc131Q/sendMessage?chat_id=" . $chatId . "&text=" . $message;
}
file_get_contents($url);
$build['#theme'] = 'new';
return $build;
}
}
I think it may cause by unescaped URL, but you need to provide error message to determine.
If you just want to make it done, you can use this Android application. For instance, use getWebhookInfo to obtain error reason.

Fatal error: Class 'Client' not found in

I got an error while adding Twilio SMS APi to my website. My site is in wordpress and using Woo commerce.
Error : Fatal error: Class 'Client' not found in /var/www/html/++++/wp-content/themes/dokan-theme-v2.2.2-child/functions.php on line 4583
My code is below:
function wl8OrderPlacedTriggerSomething($order_id){
//do something...
//echo get_stylesheet_directory_uri(). '/twilio-php-master/Twilio/Rest/Client.php';
require_once( get_stylesheet_directory_uri(). '/twilio-php-master/Twilio/autoload.php');
require( get_stylesheet_directory_uri(). '/twilio-php-master/Twilio/Rest/Client.php');
// Use the REST API Client to make requests to the Twilio REST API
// use Twilio\Rest\Client;
// Your Account SID and Auth Token from twilio.com/console
$sid = 'xxxxxxxxxxxxxxxxxxxxxx';
$token = 'xxxxxxxxxxxxxxxx';
$client = new Client($sid, $token);
// Use the client to do fun stuff like send text messages!
$client->messages->create(
// the number you'd like to send the message to (xxxxxxx)
'xxxxxxxxx',
array(
// A Twilio phone number you purchased at twilio.com/console
'from' => '+xxxxxxx',
// the body of the text message you'd like to send
'body' => "Hey Jenny! Good luck on the bar exam!"
)
);
}
Please help me for the same.
Thank you,
Twilio developer evangelist here.
I think you may need to use the fully qualified namespace for the Client in this case. Try:
$client = new Twilio\Rest\Client($sid, $token);
Let me know if that helps.
Edit
OK, that didn't work. After reading around, I've found that it's not recommended to use require or require_once within a function. I'd recommend you require the autoload file outside of your function, use the namespace and then call the Client inside the function. Like this:
require_once( get_stylesheet_directory_uri(). '/twilio-php-master/Twilio/autoload.php');
use Twilio\Rest\Client;
function wl8OrderPlacedTriggerSomething($order_id){
$sid = 'xxxxxxxxxxxxxxxxxxxxxx';
$token = 'xxxxxxxxxxxxxxxx';
$client = new Client($sid, $token);
// and so on...
}
make sure that autoload.php and Client.php files are getting loaded properly.
its unable to load client call

How can I 'fix' ["request" service is deprecated] in Symfony2 version 2.8?

The profiler in phpStorm is reporting:
The "request" service is deprecated and will be removed in 3.0. Add a typehint for Symfony\Component\HttpFoundation\Request to your controller parameters to retrieve the request instead.
I thought I was already doing this by following this suggestion by using the following code to get the request and session:
$this->request = $this->get( 'request_stack' )->getCurrentRequest();
$this->session = $this->request->getSession();
Is the warning correct or am I doing this correctly and the warning can be ignored?
Thanks.
This warning can be ignored unless you are going to upgrade to Symfony 3.0 in a future.
If you want to get rid of it I would suggest to follow this warning's message and inject Request object into your actions:
public function yourAwesomeAction(Request $request)
{
$session = $request->getSession();
}
Use like that;
$this->container->get('request_stack')->getCurrentRequest();
You have to use this one :
$request = $this->get('request_stack')->getCurrentRequest();
You may want to read the route name via the request variable, so you can do it as follows :
$routeName = $request->get('_route');
Thanks

Symfony2 PHPWord response

I am trying to generate a docx document on Symfony2, using the PHPWord bundle.
In my controller, I succeed in returning a docx file, but it is empty, I think it comes from my faulty response format.
public function indexAction($id)
{
$PHPWord = new PHPWord();
$section = $PHPWord->addSection();
$section->addText(htmlspecialchars(
'"Learn from yesterday, live for today, hope for tomorrow. '
. 'The important thing is not to stop questioning." '
. '(Albert Einstein)'
));
// Saving the document
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($PHPWord, 'Word2007');
return new Response($objWriter->save('helloWorld.docx'), 200, array('Content-Type' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'));
}
Try this class
<?php
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Settings;
use Symfony\Component\HttpFoundation\Response;
class WordResponse extends Response
{
/**
* WordResponse constructor.
* #param string $name The name of the word file
* #param PhpWord $word
*/
public function __construct($name, &$word)
{
parent::__construct();
// Set default zip library.
if( !class_exists('ZipArchive')){
Settings::setZipClass(Settings::PCLZIP);
}
$writer = IOFactory::createWriter($word, 'Word2007');
//Set headers.
$this->headers->set("Content-Disposition", 'attachment; filename="' . $name . '"');
$this->headers->set("Content-Type", 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
$this->headers->set("Content-Transfer-Encoding", 'binary');
$this->headers->set("Cache-Control", 'must-revalidate, post-check=0, pre-check=0');
$this->headers->set("Expires", '0');
$this->sendHeaders();
$writer->save('php://output');
}
}
Then in your controller do:
return new WordResponse($phpWord, "filename.docx");
Thanks a lot for your answer.
I achieve using the 2nd method, which is in my opinion the best.
I just have to return a response, otherwise the file was generated, but stuck in the web directory.
Using this response, everything was fine and a download prompt appeared, with the "full" file.
Here's my code :
$PHPWord = new PHPWord();
$section = $PHPWord->addSection();
$section->addText(htmlspecialchars(
'"Learn from yesterday, live for today, hope for tomorrow. '
. 'The important thing is not to stop questioning." '
. '(Albert Einstein)'
));
// Saving the document
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($PHPWord, 'Word2007');
$filename="MyAwesomeFile.docx";
$objWriter->save($filename, 'Word2007', true);
$path = $this->get('kernel')->getRootDir(). "/../web/" . $filename;
$content = file_get_contents($path);
$response = new Response();
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
$response->headers->set('Content-Disposition', 'attachment;filename="'.$filename);
$response->setContent($content);
return $response;
PHPWord->save() returns a true value so that would be why your file is not being downloaded. With your return new Response() you are setting the content of your response to true (the result of your save call) which is why your response is empty.
You have 2 (and probably more that I haven't thought of) options to generate and download this file..
1. Save your file to a temp folder and server from there
$filename = sprintf(
'%s%sDoc-Storage%s%s.%s',
sys_get_temp_dir(),
DIRECTORY_SEPARATOR,
DIRECTORY_SEPARATOR,
uniqid(),
'docx'
);
$objWriter->save($filename);
$response = new BinaryFileResponse($filename);
For more info on the BinaryFileResponse see the docs.
2. Ignore Symfony and serve directly via the PHPWord action
$objWriter->save($filename, 'Word2007', true);
exit();
The ->save method provides all of the actions to download the generated file internally (see the code) so all you need to do is set the format and the third parameter to true and it will handle all of the headers for you. Granted it won't be returning a Symfony response but you will be exiting out before you get to that exception.

Supress Error messages in Symfony/Twig?

How can I suppress error messages in a symfony controller / swift message, e.g. if the email of the user doesn't exist, something is wrong with the smpt server or the email address simply doesn't comply with RFC 2822.
For example, we got following CRITICAL error...
request.CRITICAL: Swift_RfcComplianceException: Address in mailbox given [ xxx#xxx.com ] does not comply with RFC 2822, 3.6.2. (uncaught exception) at $
... the user then get's a symfony error page "An Error occured" which I need to suppress in any case.
A simple #$this->get('mailer')->send($message); doesn't work here unfortunately ...
protected function generateEmail($name)
{
$user = $this->getDoctrine()
->getRepository('XXX')
->findOneBy(array('name' => $name));
if (!$user) {
exit();
}
else {
$message = \Swift_Message::newInstance()
->setSubject('xxx')
->setFrom(array('xxx#xxx.com' => 'xxx'))
->setTo($user->getEmail())
->setContentType('text/html')
->setBody(
$this->renderView(
'AcmeBundle:Template:mail/confirmed.html.twig'
)
)
;
$this->get('mailer')->send($message);
// a simple #$this->get('mailer')->send($message); doesn't work here
}
return true;
}
To simply suppress the error, wrap the send method in a try-catch block. Choose the exception type wisely. The following example just catches Swift_RfcComplicanceExceptions.
try {
$this->get('mailer')->send($message);
} catch (\Swift_RfcComplianceException $exception) {
// do something like proper error handling or log this error somewhere
}
I'd consider it advisably to apply some validation beforehand, so you can display a nice error to your user.
I'm not sure that a try catch block will work, because mails may be sent later in the request process : http://symfony.com/fr/doc/current/components/http_kernel/introduction.html#l-evenement-kernel-terminate
If you use the framework Full Stack edition, this is the default behavior.
I've also found some refs here : Unable to send e-mail from within custom Symfony2 command but can from elsewhere in app
You can change the Swiftmailer spool strategy in your config to send direct mails...

Resources