Expected response code "250/251/252" but got code "451", with message "451 Temporary local problem - please try later" - laravel

I am new in Laravel development. I am sending an email to agencies which is approved and email is not null and if agencies email is null then get customer email for send email, But I got this error https://flareapp.io/share/DPygyxQ5#F57
I have tried to figure out where is the issue using echo pre in every steps. I am using smtp for sending email.
If you think that is there issue in smtp so if user register itself then email is successfully sent to user.
Here is code
// Get agency details
$agencies = Agency::where('status', 2)->get();
$property = Property::where('property_id', $id)->first();
if($agencies->isNotEmpty())
{
foreach($agencies as $agency)
{
if($agency->email != null)
{
$agency_name = $agency->name;
$agency_email = $agency->email;
$property_slug = $property->slug;
$property_link = route('property.detail', $property_slug);
Mail::send('emails.user.agency.mail_to_agency_after_property_approve',
[
'agency_email' => $agency_email,
'agency_name' => $agency_name,
'property' => $property,
'property_link' => $property_link,
],
function($message) use ($agency_email)
{
$message->to($agency_email);
$message->subject('Fresh Property Listing Update');
});
}
else
{
$customer = Customer::select('customer_id', 'first_name', 'last_name', 'customer_email')->where('customer_id', $agency->customer_id)->first();
$agency_name = $customer->first_name.' '.$customer->last_name;
$agency_email = $customer->customer_email;
$property_slug = $property->slug;
$property_link = route('property.detail', $property_slug);
Mail::send('emails.user.agency.mail_to_agency_after_property_approve',
[
'agency_email' => $agency_email,
'agency_name' => $agency_name,
'property' => $property,
'property_link' => $property_link,
],
function($message) use ($agency_email)
{
$message->to($agency_email);
$message->subject('Fresh Property Listing Update');
});
}
}
}

Related

Laravel stripe (customers and invoice)

I created customer and product in stripe.
I create paymentIntent, invoiceItems and invoice for this customer. How i can connect invoice and payment?
My controller:
//check user in stripe
$stripeCustomer = $this->stripe->customers->search([
'query' => "email:'$user->email'",
]);
if (isset($stripeCustomer['data']) && !count($stripeCustomer['data']) ) {
//create new user
$stripeCustomer = $this->stripe->customers->create([
'email' => $user->email,
'name' => $user->name
]);
$stripeCustomerId = $stripeCustomer->id ?: 0;
} else {
$stripeCustomerId = $stripeCustomer['data'][0]->id;
}
$invoiceItems = $this->stripe->invoiceItems->create([
'customer' => $stripeCustomerId,
'price' => $product ? $product->stripe_price_id : null,
]);
//create draft invoice
$invoice = $this->stripe->invoices->create([
'customer' => $stripeCustomerId,
]);
//create payment
$paymentIntent = $this->stripe->paymentIntents->create([
'customer' => $stripeCustomerId,
'amount' => $invoiceItems->amount,
'currency' => Payment::CURRENCY_EUR,
'payment_method_types' => ['card']
]);
$clientSecret = $paymentIntent->client_secret;
After submitting form (number card, etc...) I am confirmPayment in view:
const { error } = await stripe.confirmPayment({
elements,
confirmParams: {
// Make sure to change this to your payment completion page
return_url: "{{route('payment-success'), [ 'token' => $token ])}}",
},
});
My paymentSuccess method:
public function paymentSuccess($token)
{
$data = json_decode(base64_decode($token));
//$data->paymentId
// maybe here i must pay invoice for my paymentId???
}
Invoices can be paid in two ways
Stripe automatically creates and then attempts to collect payment on
invoices for customers on subscriptions according to your
subscriptions settings. However, if you’d like to attempt payment on
an invoice out of the normal collection schedule or for some other
reason, you can do so as follows.
$this->stripe->invoices->finalizeInvoice(
$invoice->id,
[]
);
$this->stripe->invoices->pay(
$invoice->id,
[]
);
OR
You can manually send an invoice through email to your customer to
pay. You can do so as follow
$this->stripe->invoices->finalizeInvoice(
$invoice->id,
[]
);
$this->stripe->invoices->sendInvoice(
$invoice->id,
[]
);

Retrieve the name and contents of attachments for an e-mail that has been sent

In Laravel, I'm looking for a way to retrieve the attachments (if any) for an e-mail that has been sent and then store that attachment on the filesystem.
I have created a new listener for the Illuminate\Mail\Events\MessageSent event and I'm currently fetching the attachment name, but I don't know how to fetch the contents of the attachment for later storage:
public function handle($event)
{
$subject = $event->message->getSubject();
$body = $event->message->getBody();
$recipient = array_keys($event->message->getTo())[0];
$attachments = [];
foreach ($event->message->getChildren() as $child) {
$attachments[] = [
'name' => str_replace('attachment; filename=', null, $child->getHeaders()->get('content-transfer-encoding')->getFieldBody()),
'contents' => '' // ?
];
}
}
Does anybody know how to do this?
Thanks.
You should filter message children by Swift_Attachment::class and you can get the attachment content with getBody(). You may have to call getBody() twice due to a swiftmailer issue.
Filename, content type and body are easily accessible from the swift attachment object.
foreach (collect($event->message->getChildren())->whereInstanceOf(Swift_Attachment::class) as $attachment) {
$attachment->getBody(); // issue workaround
$attachments[] = [
'name' => $attachment->getFilename(),
'contentType' => $attachment->getContentType(),
'contents' => $attachment->getBody(),
];
}

Laravel later method fires emails randomly

I am using laravel admin, and I am trying to send emails at a specific time. I pass this datetime data into the first argument of later method
"date" => Carbon #1576722840 {#543 ▼
date: 2019-12-19 02:34:00.0 UTC (+00:00) }
However, it doesnt work as I expected. it randomly sends emails.
$form->saved(function (Form $form) {
if ($form->model()->to === '4') {
$emails = EmailAddress::all();
} else {
$emails = EmailAddress::where('user_type', $form->model()->to)->get();
}
$data = ['id' => $form->model()->id, 'title' => $form->model()->title, 'from' => $form->model()->from, 'body' => $form->model()->body, 'date' => $form->model()->schedule_date, 'is_html' => $form->model()->is_html];
foreach ($emails as $email) {
$url = URL::signedRoute('unsubscribe',['email_address_id' => $email->id]);
Mail::to($email)->later($data['date'],new MagazineMail($data,$url));
}
});
return $form;
}
As I understood it, if I want to send a mail at a specific time, I should just pass a datetime into the first argement, so I have no idea why my code does not work.
I made sure my env file is correct and set QUEUE_CONNECTION=database.

Hybridauth - The authorization state [state=HA-SOME_STATE_DATA] of this page is either invalid or has already been consumed

I am using Hybridauth with Codeigniter to implement social login buttons in my app. I just require Google, Facebook & LinkedIn social login button. I have successfully implemented the Google sign & sign up method but the same code does not work for Facebook & LinkedIn, Here is the error I am getting always this exception,
ops, we ran into an issue! The authorization state
[state=HA-RBNC6FHJ54VZAM1KTD7EI3SPYG08U2OLWQ9X] of this page is either
invalid or has already been consumed.Unable to get your data!Try after
some time.
My config file for hybriduath.
<?php
$config['hybridauth'] = [
//Location where to redirect users once they authenticate with a provider
'callback' => 'http://localhost/insurance-experts/auth/social_auth',
//Providers specifics
'providers' => [
'Google' => [
'enabled' => true,
'keys' => [
'id' => '...',
'secret' => '...',
],
'debug_mode' => true,
'debug_file' => APPPATH . 'logs/' . date('Y-m-d') . '.log',
], //To populate in a similar way to Twitter
'Facebook' => [
'enabled' => true,
'keys' => [
'id' => '...',
'secret' => '...'
],
'debug_mode' => true,
'debug_file' => APPPATH . 'logs/' . date('Y-m-d') . '.log',
],
'LinkedIn' => [
'enabled' => true,
'keys' => [
'id' => '...',
'secret' => '...'
],
'debug_mode' => true,
'debug_file' => APPPATH . 'logs/' . date('Y-m-d') . '.log',
],
]
];
Here is the implementation of hybridauth
public function social_auth()
{
$user_profile = NULL;
$auth_provider = $this->input->get('auth_provider');
// Check if it is redirected url with code & state params
if (!isset($_GET['code'])) {
$user_role = $this->input->get('role');
// Save it in the session to reuse it after auth redirect
// We'll need it in case user does not exist
$_SESSION['temp_user_role'] = $user_role;
}
switch ($auth_provider) {
case GOOGLE:
$auth_provider = GOOGLE;
break;
case FACEBOOK:
$auth_provider = FACEBOOK;
break;
case LINKEDIN:
$auth_provider = LINKEDIN;
break;
default:
$auth_provider = GOOGLE;
break;
}
// Load the hybridauth config file
$this->config->load('hybridauth');
//First step is to build a configuration array to pass to `Hybridauth\Hybridauth`
$config = $this->config->item('hybridauth');
try {
//Feed configuration array to Hybridauth
$hybridauth = new Hybridauth($config);
//Attempt to authenticate users with a provider by name
$adapter = $hybridauth->authenticate($auth_provider);
//Retrieve the user's profile
$user_profile = $adapter->getUserProfile();
//Disconnect the adapter
$adapter->disconnect();
} catch (\Exception $e) {
echo 'Oops, we ran into an issue! ' . $e->getMessage();
}
if (!empty($user_profile)) {
$email = $user_profile->email;
// Check if email exist in DB then sign in the user
$user_data = $this->User_model->find(['email' => $email], USERS);
if (!empty($user_data) && count($user_data) > 0) {
$user = $user_data[0];
$user_role = "";
// Cross check the user role
$user_groups = $this->ion_auth->get_users_groups($user->id)->result();
if (!empty($user_groups)) {
$group = $user_groups[0];
switch ($group->id) {
case ROLE_INDIVIDUAL:
$user_role = ROLE_INDIVIDUAL_STRING;
break;
case ROLE_COMPANY:
$user_role = ROLE_COMPANY_STRING;
break;
}
} else {
// Something went wrong, Force logout user
redirect('auth/logout');
}
if (empty($user_role)) {
redirect('auth/logout');
}
// Explicitly set the user role here
// coz it required in header's menubar
$user->role = $user_role;
$login_done = $this->ion_auth->set_session($user);
if ($login_done == TRUE) {
// Everything is OK, redirect the user to home page
redirect('/');
} else {
echo "We could not logged you in this moment!Please try after some time.";
}
} else {
$this->create_user_via_social_sign_up($user_profile);
}
} else {
echo "Unable to get your data!Try after some time.";
}
}
private function create_user_via_social_sign_up($user_profile)
{
$user_role = check_group($_SESSION['temp_user_role']);
if (empty($user_profile) or empty($user_role)) {
// Something went wrong, Force logout user
redirect('auth/logout');
}
$email = $user_profile->email;
// Generate a random password,
$password = substr(md5(rand()), 0, 7);
$extra_data = [
'active' => 1,
'is_approved' => 1
];
$this->db->trans_start();
// Directly register user via Model method as no need to send the activation email
$id = $this->ion_auth_model->register($email, $password, $email, $extra_data, [$user_role]);
$user_data = $this->User_model->find(['id' => $id], USERS);
$user = $user_data[0];
// Add the role in user object
$user->role = $user_role;
$redirectProfileUrl = base_url('Profile_setting/');
if ($this->ion_auth->set_session($user)) {
// Create empty records in tables
$this->User_model->create_user_entries($user->id, $user_role);
if ($this->db->trans_status() !== false) {
$this->db->trans_commit();
redirect($redirectProfileUrl);
} else {
// Something went wrong rollback all the transactions & inform the user
$this->db->trans_rollback();
echo "Our system is down right now!Please try after some time.";
}
}
}
Codeigniter version: 3.x
Hybridauth Version: 3

HybridAuth send tweet with image

I'm using the HybridAuth library.
I'd like to be able to post message to my authenticated users twitter profile with images.
The setUserStatus method works well to automatically send a tweet.
I wrote the following method :
function setUserStatus( $status, $image )
{
//$parameters = array( 'status' => $status, 'media[]' => "#{$image}" );
$parameters = array( 'status' => $status, 'media[]' => file_get_contents($image) );
$response = $this->api->post( 'statuses/update_with_media.json', $parameters );
// check the last HTTP status code returned
if ( $this->api->http_code != 200 ){
throw new Exception( "Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) );
}
}
The message I get from twitter is :
Ooophs, we got an error: Update user status failed! Twitter returned an error. 403 Forbidden: The request is understood, but it has been refused.
How Can I get more precise info about error ?
Does anybody allready success in sending a picture attached to a tweet ?
Thanks !
Hugo
Thanks #Heena for making myself wake up on this question, I MADE IT ;)
function setUserStatus( $status )
{
if(is_array($status))
{
$message = $status["message"];
$image_path = $status["image_path"];
}
else
{
$message = $status;
$image_path = null;
}
$media_id = null;
# https://dev.twitter.com/rest/reference/get/help/configuration
$twitter_photo_size_limit = 3145728;
if($image_path!==null)
{
if(file_exists($image_path))
{
if(filesize($image_path) < $twitter_photo_size_limit)
{
# Backup base_url
$original_base_url = $this->api->api_base_url;
# Need to change base_url for uploading media
$this->api->api_base_url = "https://upload.twitter.com/1.1/";
# Call Twitter API media/upload.json
$parameters = array('media' => base64_encode(file_get_contents($image_path)) );
$response = $this->api->post( 'media/upload.json', $parameters );
error_log("Twitter upload response : ".print_r($response, true));
# Restore base_url
$this->api->api_base_url = $original_base_url;
# Retrieve media_id from response
if(isset($response->media_id))
{
$media_id = $response->media_id;
error_log("Twitter media_id : ".$media_id);
}
}
else
{
error_log("Twitter does not accept files larger than ".$twitter_photo_size_limit.". Check ".$image_path);
}
}
else
{
error_log("Can't send file ".$image_path." to Twitter cause does not exist ... ");
}
}
if($media_id!==null)
{
$parameters = array( 'status' => $message, 'media_ids' => $media_id );
}
else
{
$parameters = array( 'status' => $message);
}
$response = $this->api->post( 'statuses/update.json', $parameters );
// check the last HTTP status code returned
if ( $this->api->http_code != 200 ){
throw new Exception( "Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) );
}
}
To make it work you have to do like this :
$config = "/path_to_hybridauth_config.php";
$hybridauth = new Hybrid_Auth( $config );
$adapter = $hybridauth->authenticate( "Twitter" );
$twitter_status = array(
"message" => "Hi there! this is just a random update to test some stuff",
"image_path" => "/path_to_your_image.jpg"
);
$res = $adapter->setUserStatus( $twitter_status );
Enjoy !
I did not understand it for hybridauth then I used this library
https://github.com/J7mbo/twitter-api-php/archive/master.zip
Then I was successful using code below: (appears elsewhere in stack)
<?php
require_once('TwitterAPIExchange.php');
$settings= array(
'oauth_access_token' => '';
'oauth_access_secret' => '';
'consumer_key' => '';
'consumer_secret' => '';
// paste your keys above properly
)
$url_media = "https://api.twitter.com/1.1/statuses/update_with_media.json";
$requestMethod = "POST";
$tweetmsg = $_POST['post_description']; //POST data from upload form
$twimg = $_FILES['pictureFile']['tmp_name']; // POST data of file upload
$postfields = array(
'status' => $tweetmsg,
'media[]' => '#' . $twimg
);
try {
$twitter = new TwitterAPIExchange($settings);
$twitter->buildOauth($url_media, $requestMethod)
->setPostfields($postfields)
->performRequest();
echo "You just tweeted with an image";
} catch (Exception $ex) {
echo $ex->getMessage();
}
?>

Resources