Mailgun API - Send URL as attachment in Send Email not working - laravel

I am trying to send url as attachment using Send Email api in Mailgun. But the attachment is not attached. I am using Laravel HTTP client
$params = [
'from' => $selected_options['mg_from_email'],
'to' => $selected_options['mg_to_email'],
'subject' => $selected_options['mg_subject'],
'text' => $selected_options['mg_text'],
'html' => $selected_options['email_body'],
];
$response = Http::asForm()->withOptions(['verify' => config('constants.verify_ssl')])->timeout(30)->withHeaders(
[
'Content-Type' => 'multipart/form-data',
'Authorization' => 'Basic ' . base64_encode('api:'.$api_key)
]
)->attach(
'attachment', file_get_contents('https://picsum.photos/200'), 'photo.jpg'
)->post(
$request_url,
$params,
);
Can anyone suggest what i am doing wrong here?
There is no error in response and the email is also sent successfully but the attachment is not there.

Related

Laravel EBay API Client Credential Grant Request Gives Error, Unsupported Grant Type

I am using Laravel 8 and the Http Client library. Here is my code:
public function mintNewApplicationAccessToken()
{
$response = Http::withHeaders([
'Accept' => 'application/json',
'Content-Type' => 'application/x-www-form-urlencoded',
'Authorization' => 'Basic ' . base64_encode(config('ebay.ebay_client_id_sandbox') . ":" . config('ebay.ebay_client_secret_sandbox')),
])->post(config('ebay.ebay_token_request_endpoint_url_sandbox'), [
'grant_type' => 'client_credentials',
'scope' => urlencode(config('ebay.ebay_client_credentials_scopes_sandbox')),
]);
dd($response->json());
}
I have double checked my client_id and client secret, I am using the Ebay sandbox at the moment, have checked the sandbox url is correct, I can't figure out what is wrong with my request? I get a 400 error back saying unsupported_grant_type and the error description says grant type in request is not supported by the authorization server. I have checked my scopes and everything seems in order?
I finally figured it out. As per the documentation on the Laravel website, I changed the code from:
public function mintNewApplicationAccessToken()
{
$response = Http::withHeaders([
'Accept' => 'application/json',
'Content-Type' => 'application/x-www-form-urlencoded',
'Authorization' => 'Basic ' . base64_encode(config('ebay.ebay_client_id_sandbox') . ":" . config('ebay.ebay_client_secret_sandbox')),
])->post(config('ebay.ebay_token_request_endpoint_url_sandbox'), [
'grant_type' => 'client_credentials',
'scope' => urlencode(config('ebay.ebay_client_credentials_scopes_sandbox')),
]);
dd($response->json());
}
To:
$auth = base64_encode(config('ebay.ebay_client_id_sandbox') . ':' . config('ebay.ebay_client_secret_sandbox'));
$response = Http::asForm()->withOptions([
'debug' => true,
])->withHeaders([
'Authorization' => 'Basic ' . $auth,
])->post(config('ebay.ebay_token_request_endpoint_url_sandbox'), [
'grant_type' => 'client_credentials',
'scope' => config('ebay.ebay_client_credentials_scopes_sandbox'),
]);
dd($response->json());
So. I added asForm to the code rather than the Content-Type line, and removed the url encode from the scopes.
What surprised me most was when I removed the url encode method from the scopes it started working? Very strange.
i have also same this problem and solution is that your account is not veriyfied or still waiting for aproval kindly contact support.

Laravel not making Guzzle HTTP POST request correctly

I am working on a megento integration and trying to get the admin access token by making a post request with form data. I tested the route out on Postman and it worked correctly:
However, when I tried to implement the same request in Laravel with Guzzle Http Client, it seem just cannot make the request properly as if the form data post body is not being recognized, and it keeps showing me errors saying the field values are required. Here is my request:
$client = new \GuzzleHttp\Client();
$response = $client->post($request['magento_domain'] . '/rest/V1/integration/admin/token', [
'form_params' => [
'username' => $magento_admin_username,
'password' => $magento_admin_password
], [
'Accept' => 'application/json',
'Content-Type' => 'application/json'
]
]);
and then this is the error I keep getting:
Update: I had also tried the request like this, it throws the same error:
$response = $client->post($request['magento_domain'] . '/rest/V1/integration/admin/token', [
'form_params' => [
'username' => $magento_admin_username,
'password' => $magento_admin_password
]
]);
I would appreciate any help!
The "Content-Type: application/json" request header is incorrect when sending a form-data body.
Just remove it, Guzzle automatically adds the correct Content-Type when using "form_params". Just JSON is wrong because the body is obviously not JSON.
I am using a JSON request in production successfully:
$res = $this->client->request('POST', 'https://.../rest/V1/integration/admin/token', [
'headers' => [
'Accept' => 'application/json',
'content-type' => 'application/json'
],
'json' => [
'username' => config('app.shopUser'),
'password' => config('app.shopPw')
]
]);
Or try using "multipart" instead of "form_params" - this should send a multipart/form-data request which is what Postman means with "form-data".
"form_params" is equivalent to "x-www-form-urlencoded".

Not receiving Slack interactive payload

I have set up a notification with action buttons, but I do not receive the in interactive payload. I have configured the webhook URL here:
When I post to that URL in Postman everything is fine. But when I press the buttons I get no callback to that URL I get nothing(I'm logging all requests to that URL). I also get a warning triangle next to my buttons like this:
I get no other feedback and no Ideas where I should debug.
The massage with the buttons is published with Laravel's Slack notification channel plus this package for block support: https://github.com/nathanheffley/laravel-slack-blocks
This is the code for sending the notification, but I don't think it is relevant:
public function toSlack()
{
$model = $this->model;
$message = (new SlackMessage())
->error()
->content('New report!');
$message->attachment(function ($attachment) use ($model) {
$attachment->block(function ($block) {
$block
->type('actions')
->elements([
[
'type' => 'button',
'text' => [
'type' => 'plain_text',
'text' => 'Approve',
'emoji' => false,
],
'value' => 'click_me_123',
'action_id' => 'approve_x',
'style' => 'primary',
],
[
'type' => 'button',
'text' => [
'type' => 'plain_text',
'text' => 'Reject',
'emoji' => false,
],
'value' => 'click_me_1234',
'action_id' => 'reject_x',
'style' => 'danger',
],
]);
});
});
return $message;
}
Any ideas how I should proceed with debugging?
Today, I noticed that I got some more information if I hoovered the triangle, but I'm pretty sure that didn't work yesterday. I got the message "500 server error" there.
The problem was that the payload JOSN is sent as a form-data field and not in the POST request body like normal. Why do they send the payload like this? It makes no sense.

Sending automated email with dynamic content template

Well, I want to send an automated email every Friday using MailChimp/Mandrill.
Email Template :
Hi {{firstName}},
You weekly weekend pass is {{code}}.
Here, My email content is dynamically generated. So, before sending automated email, there should be some mechanism where I call the rest api from where I get the firstName and code. Then email is sent to different user.
{
[{
firstName: 'test',
code: 'Xewetwerx'
},
{
firstName: 'test2',
code: 'Xewetwrtd'
}]
}
I know we can write code in our backend server and call the API every Friday using cronjob(to send an email every Friday) but I don't want to use any cronjob.
Is it possible to make API call and send automated mail using MailChimp or mandrill ???
Outcome:
2 email should be sent with different code.
Mandrill implements scheduled emails through the sent_at parameter.
It's possible to send an email using a template and specify date and time when the message should be sent as a UTC timestamp in YYYY-MM-DD HH:MM:SS format. If you specify a time in the past, the message will be sent immediately. Note that for the sent_at feature you will need a paid (non free) account
If you choose PHP as the programming language for your backend,
you can use the official PHP API library.
example: (the code is not tested and could contain errors)
require_once '/path/to/MailchimpTransactional/vendor/autoload.php';
$mailchimp = new MailchimpTransactional\ApiClient();
$mailchimp->setApiKey('YOUR_API_KEY');
$msg = array(
'subject' => 'My subject',
'from_email' => 'ellery#example.com',
'to' => array(array('email' => 'recipient1#example.com', 'name' => 'Recipient 1'),array('email' => 'recipient2#example.com', 'name' => 'Recipient 2')),
'merge_vars' => array(array(
'rcpt' => 'recipient1#example.com',
'vars' =>
array(
array(
'name' => 'firstName',
'content' => 'test'),
array(
'name' => 'code',
'content' => 'Xewetwerx')
)),
array(
'rcpt' => 'recipient2#example.com',
'vars' =>
array(
array(
'name' => 'firstName',
'content' => 'test2'),
array(
'name' => 'code',
'content' => 'Xewetwrtd')
))));
$response = $mailchimp->messages->sendTemplate([
"template_name" => "template_name",
"template_content" => [[]],
"message" => $msg,
"send_at" => "2021-06-23 09:05:00" ,
]);
print_r($response);

Can’t submit data to API Platform

I have a controller through which I send data to my local environment of the api platform (which is running fine)
/**
* Creates a new Location entity.
*
*/
public function createAction(Request $request)
{
$this->get("suvya_breadcrumbs.factory")->update('New Hub');
$form = $this->createForm(HubType::class);
$form->handleRequest($request);
$new_url = $this->generateUrl('new_hub');
$redirect_url = $this->generateUrl('home');
if ($form->isSubmitted() && $form->isValid()) {
$client = new Client([
'base_uri' => 'http://127.0.0.1:8000',
]);
$response = $client->request('POST', '/hubs', [
'form_params'=> $form->getData(),
'headers' => [
'Accept' => 'application/ld+json',
'Content-Type'=> 'application/json',
'Authorization'=> 'eyJhbGciOiJSUzI1NiJ9.eyJyb2xlcyI6WyJST0xFX1VTRVIiXSwidXNlcm5hbWUiOiJhZG1pbiIsImlhdCI6MTUxNzg3NjE1NCwiZXhwIjoxNTE3ODc5NzU0fQ.gIG9lueJJZxzkOl8qblhHWwiJvW97m4gz1-1mYeM9SgMzMW35Wh6XamOOYiISDN99yJ6Ovo-wKk6whpE5UGMDVw_wGek003Dd6r-Y7Ql3kVLHksn2JFzhAN3GwlXFcOI4MIjmq5qBhkzv21pHymO0yn1SlzWBwb0O7WygywefMu5p09zGuvAiP9I2ShyQLZhjj8bB_odf3dI-Ql0ZbRmn_JDkDoPcm5U11i-3S1oMikBmFq0WtTcWo7vezt3QdA3bY4_bgaISINAiYRR-_cvjpBSqFSE6n1ZYtHvKFn-98wXXsBGxEAoZw6iQL4iRgOI8F_uaiCo0eRHC7q0_xQ_V_W0-5XDIQXWDwoiVaUXnjO6xo2Fldp7PLO1ueJz1e4wiOy2-TunZdc8UCtw2BdFIQtWatPLi_v_rsNvF2H-6hwa9UOKEi9Z4tH4KkuATbXAxxfkCbSOyY1SAWP0riooPQi_AI2J7L2Ly86eAuKo1Hix3EuEogo19GSyBz_cCWczyERQWM9gikuUs8E22SIAdxTl8ZLFaXgiZIibDvb8pqcN8izFjywWbF2CkyWC58WxrVd6Bfmfnm7k9T6oZqwIZ-TQR-SbRnUHN1hpWUjFCk-tHhgvh7osHXmxe3grzA8M3LPBpQGQiTeqBZFMjF4Tx8zW2tuiEn6TwhV14Lj24Vc'
]
]);
die();
}
return $this->render('SuvyaFabricsCloudBundle:Common:basic.html.twig', array(
'form' => $form->createView(),
'page_title'=> 'Hub aanmaken',
'action_path' => $new_url,
'cancel_path'=> $redirect_url,
'submit_button_title' => 'Opslaan',
));
}
But unfortunately i'm getting an error in my dev.log of the api environment:
[2018-02-06 02:32:37] request.INFO: Matched route "api_hubs_post_collection". {"route":"api_hubs_post_collection","route_parameters":{"_controller":"api_platform.action.post_collection","_format":null,"_api_resource_class":"AppBundle\\Entity\\Hub","_api_collection_operation_name":"post","_route":"api_hubs_post_collection"},"request_uri":"http://127.0.0.1:8000/hubs","method":"POST"} []
[2018-02-06 02:32:37] request.CRITICAL: Uncaught PHP Exception Symfony\Component\Serializer\Exception\UnexpectedValueException: "Syntax error" at /Users/myname/Sites/suvyalogistics-api/vendor/symfony/symfony/src/Symfony/Component/Serializer/Encoder/JsonDecode.php line 78 {"exception":"[object] (Symfony\\Component\\Serializer\\Exception\\UnexpectedValueException(code: 0): Syntax error at /Users/myname/Sites/suvyalogistics-api/vendor/symfony/symfony/src/Symfony/Component/Serializer/Encoder/JsonDecode.php:78)"} []
The output of form->getData():
array (size=4)
'postalCode' => string 'sdfdsf' (length=6)
'streetName' => string 'sdfsdf' (length=6)
'doorNumber' => string 'sdfsfd' (length=6)
'city' => string 'sdfsfd' (length=6)
Running the endpoint at the api platform with the same values goes fine as well.
Does anyone of you has an idea why this goes wrong?
You're sending a payload encoded in application/x-www-form-urlencoded (HTML form like) to the API Platform API, while, according to the headers you've set, it excepts data encoded in JSON.
To encode the data of the form in JSON, you can use the following Guzzle snippet:
$client = new Client([
'base_uri' => 'http://127.0.0.1:8000',
]);
$response = $client->request('POST', '/hubs', [
'json' => $form->getData(),
'headers' => [
'Accept' => 'application/ld+json',
'Authorization'=> '...'
]
]);
Alternatively, you can configure API Platform to accept form data, but I would not recommend going this way (it's better to only deal with JSON API-side).

Resources