Laravel 9.x new Symphony Mailer Transport dynamic change - laravel-9

Before Laravel switched to Symfony Mailer I was able to check custom SMTP server response the following way:
try {
$transport = new Swift_SmtpTransport($request->smtp_server, $request->smtp_port, $request->secure_connection);
$transport->setUsername($request->smtp_username);
$transport->setPassword($request->smtp_password);
$mailer = new Swift_Mailer($transport);
$mailer->getTransport()->start();
return array(
'success' => true,
'statusCode' => 200,
'message' => 'Success.'
);
} catch (Swift_TransportException $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage(),
], 500);
} catch (Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage(),
], 500);
}
I am currently struggling to figure out how exactly to set the DSN(apparently this is the way to go) configuration and execute a transport connection test. I have been searching around for some documentation but was unable to find anything specific.

I too struggled with this issue. For the time being, you can send an actual email and catch the error if it does not send like below. The issue is that Symfony transport does not have start() and stop() methods like Swift Mailer did. I added the following code in a validator closure to not allow a user to save SMTP records unless the records were valid.
try{
$transport_factory = new \Symfony\Component\Mailer\Transport\Smtp\EsmtpTransportFactory;
$transport = $transport_factory->create(new \Symfony\Component\Mailer\Transport\Dsn(
!empty(request()->input('mail_encryption')) && request()->input('mail_encryption') === 'tls' ? ((request()->input('mail_port') == 465) ? 'smtps' : 'smtp') : '',
request()->input('mail_host'),
request()->input('mail_username'),
request()->input('mail_password'),
request()->input('mail_port')
));
$mailer = new \Symfony\Component\Mailer\Mailer($transport);
$email = (new \Symfony\Component\Mime\Email())
->from('noreply#domain.com')
->to($user->email)
->subject('Test Email')
->text("Email Test was Successful");
$mailer->send($email);
} catch (\Symfony\Component\Mailer\Exception\TransportException $e) {
$fail($e->getMessage());
} catch (\Exception $e) {
$fail($e->getMessage());
}

Related

Lumen Google reCAPTCHA validation

I already seen some tuts and example about it and I have implemented it somehow.
Method in controller looks like this:
The logic used is just php and I would like to use more a lumen/laravel logic and not just simple vanilla php. Also I have tried and did not worked anhskohbo / no-captcha
public function create(Request $request)
{
try {
$this->validate($request, [
'reference' => 'required|string',
'first_name' => 'required|string|max:50',
'last_name' => 'required|string|max:50',
'birthdate' => 'required|before:today',
'gender' => 'required|string',
'email' => 'required|email|unique:candidates',
'g-recaptcha-response' => 'required',
]);
//Google recaptcha validation
if ($request->has('g-recaptcha-response')) {
$secretAPIkey = env("RECAPTCHA_KEY");
// reCAPTCHA response verification
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretAPIkey.'&response='.$request->input('captcha-response'));
$response = json_decode($verifyResponse);
if ($response->success) {
//Form submission
//Saving data from request in candidates
$candidate = Candidate::create($request->except('cv_path'));
$response = array(
"status" => "alert-success",
"message" => "Your mail have been sent."
);
} else {
$response = array(
"status" => "alert-danger",
"message" => "Robot verification failed, please try again."
);
}
}
} catch(Exception $e) {
return response()->json($e->getMessage());
}
return response()->json(['id' => $candidate->id, $response]);
}
Okey. Google has an package for this:reCAPTCHA PHP client library
just: composer require google/recaptcha "^1.2"
and in your method inside controller:
$recaptcha = new \ReCaptcha\ReCaptcha(config('app.captcha.secret_key'));
$response = $recaptcha->verify($request->input('g-recaptcha-response'), $_SERVER['REMOTE_ADDR']);
if ($response->isSuccess()) {
//Your logic goes here
} else {
$errors = $response->getErrorCodes();
}
config('app.captcha.site_key') means that I got the key from from config/app.php and there from .env file.
If you have not config folder, you should create it, also create app.php file same as in laravel.

Prestashop Webservice - Outuput specific details

This is the code I have right now:
public static function listProducts() {
require_once('inc/config/config.php');
try {
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
$opt = array('resource' => 'products', 'display' => 'full');
$xml = $webService->get($opt);
$resources = $xml->products->children();
}
catch (PrestaShopWebserviceException $e) {
$trace = $e->getTrace();
if($trace[0]['args'][0] = 404) echo "BAD ID";
else if ($trace[0]['args'][0] = 401) echo "BAD AUTH KEY";
else echo 'OTHER ERROR';
}
$output = json_encode($resources, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
echo $output;
}
How can I output specific resources/details about my products?
Right now this outputs everything.
Thank you!
I can suggest you to use webservices documentation for 1.5 version, in 1.6 lack of details.
$opt = array(
'resource' =>'customers',
'display' => '[birthday]',
'filter[firstname]' => '[John]',
'filter[lastname]' => '[DOE]'
);
http://doc.prestashop.com/display/PS15/Chapter+8+-+Advanced+Use#Chapter8-AdvancedUse-SortingFilters

How to make the database connection to be utf-8 compliant in this setting?

This is my index.php file ( the database is MySQL ) :
<?php
use Phalcon\Loader;
use Phalcon\DI\FactoryDefault;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Application;
use Phalcon\Mvc\Url as UrlProvider;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
include("../app/config_const.php");
include("../app/config_inc.php");
include("../app/lib/PSR.php");
try {
// Register an autoloader
$loader = new Loader();
$loader->registerDirs(array(
'../app/controllers/',
'../app/models/'
))->register();
// Create a DI
$di = new FactoryDefault();
// Setup the database service
$di->set('db', function(){
$cnx = new DbAdapter(array(
"host" => "localhost",
"username" => "root",
"password" => "",
"dbname" => BDD
));
return $cnx;
});
// Setup the view component
$di->set('view', function(){
$view = new View();
$view->setViewsDir('../app/views/');
$view->registerEngines(array(
".phtml" => 'Phalcon\Mvc\View\Engine\Volt'
));
return $view;
});
// Setup a base URI so that all generated URIs include the "phalcon" folder
$di->set('url', function(){
$url = new UrlProvider();
$url->setBaseUri('/resto/');
return $url;
});
//Register the flash service with custom CSS classes
$di->set('flash', function(){
$flash = new \Phalcon\Flash\Direct(array(
'error' => 'alert alert-error',
'success' => 'alert alert-success',
'notice' => 'alert alert-info',
));
return $flash;
});
//Handle the request
$app = new Application($di);
echo $app->handle()->getContent();
} catch(\Exception $e) {
echo "Exception: ", $e->getMessage();
}
?>
How to make the database setting to be utf-8 compliant in this case ?
Add encoding parameter to DB adapter as well:
// Setup the database service
$di->set('db', function(){
$cnx = new DbAdapter(array(
"host" => "localhost",
"username" => "root",
"password" => "",
"dbname" => BDD,
"charset" => "utf8",
"options" => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
),
));
return $cnx;
});
Reference.
Also you can set encoding to your .htaccess file:
# your file could start with something like this
RewriteEngine On
RewriteBase /
# add next line
AddDefaultCharset utf-8
Ok I found the solution : I modified the ssp.class.php for the server processing :
static function sql_connect($sql_details) {
try {
$db = #new PDO("mysql:host={$sql_details['host']};dbname={$sql_details['db']}",
$sql_details['user'],$sql_details['pass'],array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'',
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$db->exec("set names utf8");
$db->exec("set character_set_client='utf8'");
$db->exec("set character_set_results='utf8'");
$db->exec("set collation_connection='utf8_bin'");
}
catch (PDOException $e) {
self::fatal("An error occurred while connecting to the database. ".
"The error reported by the server was: ".$e->getMessage());
}
return $db;
}

Twilio API in loop continue sending messages even if a phone is invalid

I have an array of phone numbers which I am looping over and sending a text message to.
Occasionally a number may be invalid and an error is thrown from Twilio. I know I can comment out the echo in the catch but if an exception is still thrown I need to my loop to continue. Should I remove the try catch entirely?
foreach($filterphones as $key => $value){
$account_sid = 'xxx';
$auth_token = 'xxx';
$client = new Services_Twilio($account_sid, $auth_token);
try {
$message = $client->account->messages->create(array(
'From' => "+16XXXXXXXXX",
'To' => $value,
'Body' => $body,
));
}catch (Services_Twilio_RestException $e) {
//echo $e->getMessage();
}
}

Facebook SDK 3.1 getUser most basic code not working

I had some really complicated code, and now I've made it ridiculously simple, and it doesn't work.
Currently it simply takes me back to the page with the login URL echoed out.
Code is here:
<?php
require 'facebook.php';
// Create our application instance
// (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'sd',
'secret' => 'sda',
));
// Get User ID
$user = $facebook->getUser();
if($user) {
echo $user;
} else {
$loginUrl = $facebook->getLoginUrl(array('redirect_uri'=>'http://www.facebook.com/pages/CharlesTestPage/225802194155435?sk=app_252946408094785','scope'=>'email'));
echo $loginUrl;
}
exit;
?>
Please. I have spent a whole paid work day on this now, and am at the point of crying, not only for myself but for my boss.
Cry.
Edit: OK, the weird thing is, if I have the redirect_uri set to the facebook tab, if it's not authenticated itself, then it constantly redirects in an infinite loop. However, if I remove the redire
This is what's working for me using PHP SDK 3.1.1. Try it and let us know if this works:
include('facebook.php');
session_start();
//facebook application
$config['appid' ] = "YOUR_APP_ID";
$config['secret'] = "YOUR_APP_SECRET";
$config['baseurl'] = "http://example.com/facebookappdirectory";
$config['appbaseurl'] = "http://apps.facebook.com/your-app-name";
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $config['appid'],
'secret' => $config['secret'],
'cookie' => true,
));
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email'
)
);
if ($user) {
try {
//get user basic description
$userInfo = $facebook->api("/$user");
$fb_access_token = $facebook->getAccessToken();
} catch (FacebookApiException $e) {
//you should use error_log($e); instead of printing the info on browser
error_log('APP ERROR: '.$e);
$user = null;
}
}
if (!$user) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
if (isset($_GET['code'])){
header("Location: " . $config['appbaseurl']);
exit;
}
Check for
if(isset($_GET['code'])){
$user = $facebook->getUser();
$access_token = $facebook->getAccessToken();
}
Facebook return userID only after the login and that code.