can anyone point me in the right direction I need to send a HTTP post when a customer registers and or makes a purchase from Magento to a third part server ?
It will be the basic information like name, address, postcode , email ect.
Not sure where to start ?
Many thanks
$client = new Varien_Http_Client('http://www.example.com/');
$client->setMethod(Varien_Http_Client::POST);
$client->setParameterPost('name', $name);
$client->setParameterPost('address', $address);
//more parameters
try{
$response = $client->request();
if ($response->isSuccessful()) {
echo $response->getBody();
}
} catch (Exception $e) {
}
Related
I have a webhook to receive updates that I am trying to configure. I need to get the bearer token from the header, but I am not able to retrieve it. Can someone shed some light on this issue? I am stumped!
receiving url is https://example.com/receive
$data = file_get_contents("php://input",true);
$events= json_decode($data, true);
If you're looking for an OAuth bearer token these are usually transferred in the request HTTP Authorization header. In PHP these can be a little tricky to read since different web servers have different approaches to reading the Authorization header.
There's a good example of how to read a bearer token in this answer. Copied here for convenience:
<?PHP
/**
* Get hearder Authorization
* */
function getAuthorizationHeader() {
$headers = null;
if (isset($_SERVER['Authorization'])) {
$headers = trim($_SERVER["Authorization"]);
} else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { //Nginx or fast CGI
$headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
} elseif (function_exists('apache_request_headers')) {
$requestHeaders = apache_request_headers();
// Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
$requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
if (isset($requestHeaders['Authorization'])) {
$headers = trim($requestHeaders['Authorization']);
}
}
return $headers;
}
/**
* get access token from header
* */
function getBearerToken() {
$headers = getAuthorizationHeader();
// HEADER: Get the access token from the header
if (!empty($headers)) {
if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
return $matches[1];
}
}
return null;
}
?>
How to check send status in swiftmailer with symfony?
I send mails this way:
$res = $this->get('mailer')->send($message)
Now $res has always status 1 even if I set wrong password in parameters. Email isn't send and status is 1 :/
I'd like to throw some kind of information if there is any problem with sending :/
You can use second argument in send()
$res = $this->get('mailer')->send($message, $errors)
try {
$this->get('mailer')->send($message);
}
catch (\Exception $exception) {
$errors = $exception->getMessage();
}
The $errors variable will contain the message if sending fails.
I created an action that handles redirection to respected areas depending on user's type and ROLE (trainee, company or university let's say). If user is not logged in, it redirects to homepage (anonymous area), and if logged in - to their profile pages. I use it in homepage and many other cases, for example, as sign up and login success redirection.
public function authorizationAction(Request $request)
{
$user = $this->getUser();
$authorizationChecker = $this->get('security.authorization_checker');
$request->cookies->remove('action');
if ($user) {
if ($user->getType() == 'company' && $authorizationChecker->isGranted('ROLE_COMPANY_GUEST')) {
/** #var Company $company */
$company = $user->getCompany();
if ($user->getState() == 'active' && $company->getState() == 'active') {
$response = $this->redirectToRoute('company');
} else {
$response = $this->redirectToRoute('company_profile');
}
} elseif ($user->getType() == 'university' && $authorizationChecker->isGranted('ROLE_UNIVERSITY_GUEST')) {
/** #var University $university */
$university = $user->getUniversity();
if ($user->getState() == 'active' && $university->getState() == 'active') {
$response = $this->redirectToRoute('university');
} else {
$response = $this->redirectToRoute('university_profile');
}
} elseif ($user->getType() == 'trainee' && $authorizationChecker->isGranted('ROLE_TRAINEE')) {
/** #var Trainee $trainee */
$trainee = $user->getTrainee();
if ($user->getState() == 'active' && $trainee->getState() == 'active') {
$response = $this->redirectToRoute('trainee');
} else {
$response = $this->redirectToRoute('trainee_profile');
}
} else {
$response = $this->redirectToRoute('homepage');
}
} else {
$response = $this->redirectToRoute('homepage');
}
return $response;
}
I have seen some examples recommending using symfony events (kernel.request) to handle it minimizing controller code. But in this case I will not be able to use this action as sign up and login success path.
I am not using FOS, because of lack of user customization. I prefer handling User my self.
Is my approach wrong and something to be worried about?
Some things that I am concerned:
Redirection count:
For example. I am logged in user and I go to homepage and am redirected to my action where I am checked whether I am logged in or not and depending on user type I am redirected to respected page.
public function indexAction(Request $request)
{
if ($this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
return $this->redirectToRoute('authorization');
}
// ...
}
Slowing website:
In the future I will be using this action in more pages and website will definatelly slow down everytime executing same code on each page.
I am not using FOS, because of lack of user customization. I prefer handling User my self.
Blockquote
You really shouldn't reinvent the wheel here but even if you want to your assessment that extending FOS is hard is wrong, take a look at this gist how many of us Symfony Devs extend FOS to enable social login via HWIOauthBundle. Extending it for other purposes is equally trivial.
Update Since OP's Comments Below
....
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use AppBundle\Form\Type\LoginType;
....
....
$login_form = $this->createForm(LoginType::class);
$login_form->handleRequest($request);
if (!$login_form->isValid()){
//throw error
}
$email = strip_tags($login_form->get('email')->getData());
$password = $login_form->get('password')->getData();
// Call the User Manager
$userManager = $this->get('fos_user.user_manager');
$user = $userManager->findUserByUsernameOrEmail($email);
if(!$user){
//throw error : User With Submitted Credentials Does Not Exist
}
$user_password = $user->getPassword();
$encoded_password = $this->get('security.password_encoder')->encodePassword($user, $password);
if($encoded_password != $user_password){
//throw error : Wrong Password, Please Check Your Details & Re-submit
}
// Successful query of username/email and password now we log in user
// Create new token
$token = new UsernamePasswordToken($user, $user->getPassword(), 'main', $user->getRoles());
// Login New User
$tokenStorage = $this->get('security.token_storage');
$tokenStorage->setToken($token);
// User now logged in
$user_id = $user->getId();
....
Redirection count:
In your case each redirection would cause at least 1 database query to verify user session, so yes many them could lead to a bad use and server experience. If you use FOSUserBundle with Doctrine's Second Level Cache, you can avoid this query everytime you call $this->getUser();
Slowing website:
This very small bit of code with hardly be you bottleneck at scale but for arguments sake let's assume it is. I would solve this problem by introducing client side sessions. A framework like Angular or my personal favorite Ember would allow you to store user sessions on the client so as not to even bother going back to your server all the time for such a menial task as checking authentication or roles. I would still advise you to keep some server side code for those cheeky users who want to poke holes in your code.
The Access Control section in the Symfony documentation might offer easier solutions to restrict access. In my time using Symfony I have always been able to use it for redirection and access control.
I am trying to set up a error handler on my controller to catch anything that might cause my page to malfunction. For example: in this scenario I am trying to catch any error that could possibly happen once my method calls a external API with a bad parameter but it doesn't seem to do anything except give me the typical ClientException in Middleware.php line 69:
Client error: 400 which isn't what I am exactly aiming for. Any advice will be greatly be appreciated or better ways of handling errors in Silex.
private function getSIS($url, $session, Application $app)
{
$message = "You don't have permission to access this!";
if($app['security']->isGranted('ROLE_SUPER_ADMIN'))
{
$client = new Client(['base_uri' => 'https://***********.ca/api/SIS/']);
if (!empty($session))
$response = $client->get($url, ['query' => 'session=' . $session]);
else
$response = $client->get($url);
return $response;
}
$app->error(function (\Exception $e, $code) {
switch($code) {
case 404:
$message = 'The requested page could not be found';
break;
default:
$message = 'We are sorry, but something went terribly wrong.';
}
return new Response($message);
});
return new Response($message);
}
The $app->error method might need to be placed outside the context of your controller actions. I'm not sure exactly how you have your application structured but maybe try placing the error block right before $app->run();
$app->error(function (\Exception $e, $code) use ($app) {
switch($code) {
case 404:
$message = 'The requested page could not be found';
break;
default:
$message = 'We are sorry, but something went terribly wrong.';
}
return new Response($message, $code);
});
$app->run();
I'm trying to get events from my Google Calendar using Service Account. I received Access Token:
{"access_token":"ya29.AHES6ZR9o2-cut-Gg","expires_in":3600,"created":1366631471}
Now this token is expired and when I trying to get events, I get an error:
The OAuth 2.0 access token has expired, and a refresh token is not available. Refresh tokens are not returned for responses that were auto-approved.
I tried to find way to get a new access token in API documentation, but did not find anything suitable. And now I have a question: How I must refresh my access token?
Code that I use to access the calendar:
session_start();
require_once '../../src/Google_Client.php';
require_once '../../src/contrib/Google_CalendarService.php';
define('SERVICE_ACCOUNT_NAME', 'numbers-and-letters#developer.gserviceaccount.com');
define('CLIENT_ID', 'numbers-and-letters.apps.googleusercontent.com');
define('KEY_FILE', '../../key.p12');
$client = new Google_Client();
$client->setApplicationName("app name");
$client->setUseObjects(true);
$client->setClientID(CLIENT_ID);
$key = file_get_contents(KEY_FILE);
if (isset($_SESSION['token']))
{
$client->setAccessToken($_SESSION['token']);
$client->setaccessType('offline');
}
else
{
$client->setAssertionCredentials(new Google_AssertionCredentials(
SERVICE_ACCOUNT_NAME,
array('https://www.googleapis.com/auth/calendar.readonly'),
$key
));
}
try
{
$cal = new Google_CalendarService($client);
$events = $cal->events->listEvents('numbers-and-letters#group.calendar.google.com');
print_r($events);
} catch (Exception $e) echo $e->getMessage();
if ($client->getAccessToken()) {
$_SESSION['token'] = $client->getAccessToken();
}
I solved! To refresh Access Token without Refresh Token you want to call Google_Client class's method revokeToken()
The recommended way to refresh token is:
if ($client->isAccessTokenExpired())
{
$client->getAuth()->refreshTokenWithAssertion();
}