Mailgun api response to validate mail - php

I have been using the mail API to validate emails, but it has not returned the response. I am doing something wrong?
curl_setopt_array($this->curl, array(
CURLOPT_URL => "https://api.mailgun.net/v4/address/validate?address=".$email,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS => "address=".$email,
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache"
"Authorization: Basic " . base64_encode("api:mikey")
),
));
$result=curl_exec ($this->curl);
error_log("result ". print_r($result, true));
$err = curl_error($this->curl);
curl_close($this->curl);
error_log("url: ".print_r($url, true));
error_log("error: ".print_r($err, true));
error_log("result: ".print_r($result, true));
return $result;

Well, I faced this same problem but using Guzzle 6.
You should put your account domain at the end of the API Base URL:
https://api.mailgun.net/v4/mysite.com
In Guzzle, these are my configurations (scripts in PHP):
$http_client = new Client([
'base_uri' => 'https://api.mailgun.net/v4/mysite.com',
'allow_redirects' => true,
'debug' => true, // for development purposes
'http_errors' => false
]);
This is the GET Request call:
$response = $http_client->request(
'get',
'address/validate',
[
'query' => ['address' => 'mail#mail.com']
'auth' => ['api', 'your_account_api_private_key'];
]
);

Related

PHP POSTMAN Follow Authorization header Meaning

I'm performing a POST request to a REST Service that requires an OAuth 2.0 authorization.
In Postman everything works perfectly fine since enabling the "Follow Authorization header" option so the auth header will be retained after a redirection.
However I dont know the equivalent to that attribute for a CURL request in PHP. So therefore I still get the following error: "Session expired or invalid".
Does anyone know how to successfully keep the auth header after a redirection in PHP cURL?
This is my php code:
$token = $this->getToken();
$url = "XXX";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer ' . $token,
'Content-Type: application/json'
,
curl_setopt($curl, CURLOPT_POSTFIELDS, array(
'client_id' => 'XXX',
'client_secret' => 'XXX',
'username' => 'XXX',
'password' => 'XXX',
'grant_type' => 'password',
'redirect_uri' => 'XXX'
)))
));
$response = curl_exec($curl);
var_dump('TOKEN: ' . $token);
var_dump($url);
var_dump(curl_getinfo($curl));
if (curl_errno($curl)) {
var_dump('Error:' . curl_error($curl));
} else {
var_dump("SUCCESS! ");
var_dump($response);
}
You cannot do this:
curl_setopt($curl, CURLOPT_POSTFIELDS, array(
'client_id' => 'XXX',
'client_secret' => 'XXX',
'username' => 'XXX',
'password' => 'XXX',
'grant_type' => 'password',
'redirect_uri' => 'XXX'
You already did this: URLOPT_POSTFIELDS => json_encode($data),
And you cannot use an array if you want to keep the Content-Type: application/json.
When you use an array for POSTFIELDS, curl will override the content type with Content-Type: application/x-www-form-urlencoded
I sometimes use file_get_content() with a context.
This is an easy way (without SSL) to get the headers and post data right.
Keeping mind that file_get_content() has some of the same idiosyncrasies as curl. The context has file_get_content() which populates the Body.
<?php
header("Content-Type: text/plain,UTF-8");
$jsn = file_get_contents('json.jsn');
$postdata = http_build_query(
array(
'json' => $jsn,
)
);
$opts = array('http' =>
array(
'method' => 'PUT',
'header' => 'Content-type: application/json',
'content' => $jsn //useing JSON rather than $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
echo $result;

I have a curl snippet that works, however I'm getting a 400 error with Guzzle, why?

Can anyone see what I might be doing wrong here? Curl works but Guzzle (v6.3) gets a 400 error.
The Curl was generated by Postman:
Curl:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://unnamed-website.com/api2/v2/charges?chargeId=273628584&paymentGate=inovio",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"app-token: toktoktoktoktotkoktoktokt",
"Content-type: application/json",
"Authorization: Basic MDFkNWJiMTllYTdlZjVjODYzYTVjYjI3ZjUzNWY4NmM6YzFhMzRlNWJkZGYyMzljZTFmZDcwZjNiZDk0Y2Q4ZjA="
),
));
$response = curl_exec($curl);
Output:
Guzzle:
$guzzle = new Client();
$request = $guzzle->get("https://unnamed-website.com/api2/v2/charges?chargeId=273628584&paymentGate=inovio",
[
'headers' => [
"app-token" => "toktoktoktoktotkoktoktokt",
"Content-type" => "application/json",
"Authorization" => "Basic MDFkNWJiMTllYTdlZjVjODYzYTVjYjI3ZjUzNWY4NmM6YzFhMzRlNWJkZGYyMzljZTFmZDcwZjNiZDk0Y2Q4ZjA="
]
]);
$response = $request->send();
Output:
Client error response
[status code] 400
[reason phrase] Bad Request
I've even tried adding thing like this:
$request = $guzzle->get("https://unnamed-website.com/api2/v2/charges?chargeId=273628584&paymentGate=inovio",
[
'curl' => [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
],
'headers' => [
"app-token" => "toktoktoktoktotkoktoktokt",
"Content-type" => "application/json",
"Authorization" => "Basic MDFkNWJiMTllYTdlZjVjODYzYTVjYjI3ZjUzNWY4NmM6YzFhMzRlNWJkZGYyMzljZTFmZDcwZjNiZDk0Y2Q4ZjA="
]
]);
Guzzle can be call as follows:
<?php
$client = new GuzzleHttp\Client();
$response = $client->request('GET',"https://unnamed-website.com/api2/v2/charges?chargeId=273628584&paymentGate=inovio",[
'headers' => [
"app-token" => "toktoktoktoktotkoktoktokt",
"Content-type" => "application/json",
"Authorization" => "Basic MDFkNWJiMTllYTdlZjVjODYzYTVjYjI3ZjUzNWY4NmM6YzFhMzRlNWJkZGYyMzljZTFmZDcwZjNiZDk0Y2Q4ZjA="
]
]);
$response = $request->send();
$result = json_decode($response->getBody()->getContents());
?>
My fellow developers dug into this when I posted it on slack and they found the problem. I was using use Guzzle\Http\Client; when I should have been using use GuzzleHttp\Client; ... the former being was available due to a lot of unmanaged vendor packages laying around inside a giant proprietary framework.

Sending HTTP Post Request to site with array in Body

I'm trying to make a POST request and send some values in the body of an API call. In the documentation of the API it says I need to make a POST request, using startUrls as an array with key and value.
<?php
$url = 'https://api.apify.com/v1/USERID/crawlers/CRAWLERID/execute?token=TOKENID';
$postData = array(
'startUrls' => array(array('key'=>'START', 'value'=>'https://instagram.com/instagram'))
);
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/json',
'body' => json_encode($postData)
)
));
$resp = file_get_contents($url, FALSE, $context);
print_r($resp);
?>
The JSON seems to be how it should, but the script is not sending the body properly to the website.
According to the documentation, there is no body option for the HTTP context. Try content instead:
<?php
$url = "https://api.apify.com/v1/USERID/crawlers/CRAWLERID/execute?token=TOKENID";
$postData = [
"startUrls" => [
["key"=>"START", "value" => "https://instagram.com/instagram"]
]
];
$context = stream_context_create([
"http" => [
"method" => "POST",
"header" => "Content-type: application/json",
"content" => json_encode($postData)
]
]);
$resp = file_get_contents($url, FALSE, $context);
print_r($resp);
The following code will work. I have set the headers and specified the content type.
$request = new HttpRequest();
$request->setUrl('$url = 'https://api.apify.com/v1/USERID/crawlers/CRAWLERID/execute?token=TOKENID');
$request->setMethod(HTTP_METH_POST);
$request->setHeaders(array(
'cache-control' => 'no-cache',
'content-type' => 'application/x-www-form-urlencoded'
));
$request->setContentType('application/x-www-form-urlencoded');
$request->setPostFields(array('key'=>'START', 'value'=>'https://instagram.com/instagram')
));
try {
$response = $request->send();
echo $response->getBody();
} catch (HttpException $ex) {
echo $ex;
}
If you want to try with cUrl the following code snippet will work.
$curl = curl_init();
$postData = array(
'startUrls' => array(array('key'=>'START', 'value'=>'https://instagram.com/instagram'))
);
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.apify.com/v1/USERID/crawlers/CRAWLERID/execute?token=TOKENID",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $postData,
CURLOPT_HTTPHEADER => array(
"Cache-Control: no-cache",
"content-type: multipart/form-data;"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);

Consume a Rest API using Zend Framework 2

Im' looking to consume a Rest API using Zend Framework 2.
I tried :
How to consume a Rest API using Zend Framework 2
$request = new Request();
$request->getHeaders()->addHeaders(array(
'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8'
));
$request->setUri($url);
$request->setMethod('POST');
$request->setPost(new Parameters(array('param1' => 'val1')));
$client = new Client($url, array(
'sslverifypeer' => null,
'sslallowselfsigned' => null,
));
$response = $client->dispatch($request);
$data = json_decode($response->getBody(), true);
Can someone provide an example how to enter username and password :
I tried this :
$request->getHeaders()->addHeaders(array(
'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8',
'user' => 'username1',
'password' => 'password1'
));
From https://framework.zend.com/manual/2.4/en/modules/zend.http.client.advanced.html#http-authentication
$client->setAuth('username1', 'password1');
it works now, but with curl :
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "param1=value1",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: application/x-www-form-urlencoded",
"password: password01",
"user: user01"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}

Converting Curl request to Guzzle issues with cert

I am Trying to convert an existing phpCurl request to latest guzzle and not getting anywhere fast.
This is the current request.
$curl_opts = array(
CURLOPT_HEADER => false,
CURLOPT_HTTPHEADER => array('Content-Type: text/json', 'Content-length: '.strlen($json)),
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $json,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => 'https://the-domainservice.php',
CURLOPT_VERBOSE => false,
CURLOPT_SSLCERT => '/path/to/file.pem',
CURLOPT_SSLCERTTYPE => 'pem',
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1
);
$curl = curl_init();
curl_setopt_array($curl, $curl_opts);
$response = curl_exec($curl);
For Guzzle I have tried so many ways but here are a couple of example.
$response = $this->client->post('https://the-domainservice.php', [
'body' => $postData,
'cert' => '/path/to/file.pem',
'config' => [
'curl' => [
CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true
]
]
]
);
And more verbose of
$request = $this->client->createRequest('POST', 'https://the-domainservice.php', [
'cert' => '/path/to/file.pem',
'verify' => false,
'headers' => [
'Content-Type' => 'text/json',
'Content-length' => strlen(json_encode($postData))
]
]);
$postBody = $request->getBody();
foreach ($postData as $key => $value) {
$postBody->setField($key, $value);
}
$response = $this->client->send($request);
For my guzzle requests I am just getting
GuzzleHttp\Exception\ServerException: Server error response [url] https://the-domainservice.php [status code] 500 [reason phrase] Internal Service Error
Really hope someone can advise.
Feel a little stupid now.
Just needed to send json data and all worked, end result was.
$response = $this->client->post('https://the-domainservice.php', [
'body' => json_encode($postData),
'cert' => '/path/to/file.pem',
]
);
Excellent stuff Guzzle !

Categories