I am unable to call Mailchimps API 3.0 endpoints such as /lists using OAuth 2 tokens.
I already have the token and have the endpoint from the /metadata call however, when I attempt to access /lists using the below
//Get lists
$client = new \GuzzleHttp\Client(['base_uri' => $datacenter]);
$headers = [
'Authorization' => 'OAuth ' . $token,
'Accept' => 'application/json',
'Host' => $client_endpoint,
'User-Agent' => 'oauth2-draft-v10'
];
$response = $client->request('GET', 'lists', [
'headers' => $headers
]);
$lists = json_decode($response->getBody());
Surely there is a simple solution, I am new to OAuth 2 and MailChimp, and struggling to find any information about MailChimp calls using OAuth2 tokens.
I have also tried the below...
//Get list data
$client = new \GuzzleHttp\Client(['base_uri' => $client_endpoint]);
$headers = [
'Authorization' => 'OAuth ' . $token
];
$response = $client->request('GET', 'lists',[
'user' => 'anystring:' . $token,
'headers' => $headers
]);
Log::debug($response);
Any help from here would be extremely useful
It seems that providing the token in the headers in the format Authorization: OAuth [token] doesn't work as expected.
I completed the following request using PostMan, code provided for ease of use:
// GET https://us1.api.mailchimp.com/3.0/lists
// authorization:"Bearer 0319[redacted]f966"
$response = $client->get( $datacenter.'/3.0/lists', [
'headers' => ['Authorization' => 'Bearer ' . $token]
]);
$lists = json_decode($response->getBody());
Note: the code is untested, the request is tested
Related
I have used Api on to Single Sign In Opt with in Laravel https://sso/{custom_path}/token like this Api created using jwt.
And on my end in web application passing access token and content type in header to Api call using http client guzzle.
With content type application/x-www-form-urlencoded with parameters in form_params.
But in response i am getting missing grant_type. As i am passing grant_type in form_parms array. Is there any other way to resolve this issue. Any valueable response will be considered.
Code:
$uri = $this->userTokenAuthencticateUrl();
$token = session('token')->access_token;
$params['header'] = [
"Content-Type: application/x-www-form-urlencoded",
"Authorization: Bearer $token"
];
$params['form_params'] = array(
'grant_type' => 'xxxxx',
'response_include_resource_name' => 'xxx',
'audience' => 'xxxx',
'permission' => 'xxxxxx',
);
$response = Http::post($uri, $params);
dd($response->json());
Ressponse:
array:2 [▼
"error" => "invalid_request"
"error_description" => "Missing form parameter: grant_type"
]
As you are using HTTP Client. You need to change your code. You do not need to pass Content-Type as application/x-www-form-urlencoded in your header and I believe the Authorization token is passed separately in headers you can pas it in your params.
$uri = $this->userTokenAuthencticateUrl();
$token = session('token')->access_token;
$params = array(
'grant_type' => 'xxxxx',
'response_include_resource_name' => 'xxx',
'audience' => 'xxxx',
'permission' => 'xxxxxx',
);
$response = Http::asForm()->withHeaders([
'Authorization' => 'Bearer ' . $token
])->post($uri, $params);
dd($response->json());
Method 2:
It is also mentioned in docs
If you would like to quickly add an Authorization bearer token header to the request, you may use the withToken method
so you can do like this as well
$uri = $this->userTokenAuthencticateUrl();
$token = session('token')->access_token;
$params = array(
'grant_type' => 'xxxxx',
'response_include_resource_name' => 'xxx',
'audience' => 'xxxx',
'permission' => 'xxxxxx',
);
$response = Http::asForm()->withToken($token)->post($uri, $params);
dd($response->json());
See the doc for more details
Method 3:
You can even directly use guzzle as well.
define("form_params", \GuzzleHttp\RequestOptions::FORM_PARAMS );
try{
$client = new \GuzzleHttp\Client(['headers' => ['Authorization' => 'Bearer ' . $token]]);
$guzzleResponse = $client->post(
$api_url, [
'form_params' => [
'grant_type' => 'xxxxx',
'response_include_resource_name' => 'xxx',
'audience' => 'xxxx',
'permission' => 'xxxxxx'
]
]);
if ($guzzleResponse->getStatusCode() == 200) {
$response = json_decode($guzzleResponse->getBody(),true);
//perform your action with $response
}
}
catch(\GuzzleHttp\Exception\RequestException $e){
// you can catch here 400 response errors and 500 response errors
// see this https://stackoverflow.com/questions/25040436/guzzle-handle-400-bad-request/25040600
}catch(Exception $e){
//other errors
}
I am working on project that uses Guzzle3 (v3.9.3), I would like to know how to send a raw post request, I have tried these solutions but none of them worked for me. I am using this Guzzle3 manual.
Solution :
$client = new Client();
$client->setDefaultOption('headers', array(
'Authorization' => 'Bearer '.$token,
'Accept' => 'application/json'
));
$body = '{"filter_":{"user":{"email":"aaa#test.com"}}}';
$req = $client->post($url, array(), $body,
array(
'cert' => array($certification, 'password'),
)
);
$response = json_decode($client->send($req)->getBody(true));
Solution 2 :
$client = new Client();
$client->setDefaultOption('headers', array(
'Authorization' => 'Bearer '.$token,
'Accept' => 'application/json'
));
$body = '{"filter_":{"user":{"email":"aaa#test.com"}}}';
$req = $client->post($url, array(), array(),
array(
'cert' => array($certification, 'password'),
)
);
$req->setBody($body);
$response = json_decode($client->send($req)->getBody(true));
None of them worked for me,
Error : Client error response [status code] 404 [reason phrase] Not Found [url]
I have tried some solutions found in the internet (but for Guzzle6) it works but I don't get the right results (it doesn't take in consideration the filter that I have sent , which is the mail address, so I get all results)
...
$body = array(
'filter_' => array(
'user' => array( "email" => $email )
)
);
$req = $client->post($url, array(),array('body'=> $body),
array(
'cert' => array($certification, 'password'),
)
);
...
On postman the call to WS work.
Thanks in advance
I'm posting the response in case someone need , I had to put all the bloc between try catch
try{
$client = new Client();
$client->setDefaultOption('headers', array(
'Authorization' => 'Bearer '.$token,
));
$body = '{"filter_":{"user":{"email":"aaa#test.com"}}}';
$req = $client->post($url, array(), $body,
array(
'cert' => array($certification, 'password'),
)
);
$response = json_decode($client->send($req)->getBody(true));
catch(Guzzle\Http\Exception\BadResponseException $e){
$response = json_decode($e->getResponse()->getBody(),true);
}
I have an app that connects to Paypal Connect. Upon Paypal connect button click I am taken to Paypal website and I do receive a code they send after authentication. But then I can't send the POST request to paypal with authorization_code to require user info I am receiving an error. I am getting this error:
Authentication failed due to invalid authentication credentials or a missing..
And I am pretty sure that my credentials are good.
Am I missing something?
This is what Paypal gives me:
curl -X POST https://api.sandbox.paypal.com/v1/oauth2/token \
-H 'Authorization: Basic {Your Base64-encoded ClientID:Secret}=' \
-d 'grant_type=refresh_token&refresh_token={refresh token}'
I am using Guzzle to send post request. Please see code below
$client = new \GuzzleHttp\Client();
$headers = [
'Authorization' => 'Basic clientID:clientSecret'
];
$response = $client->request('POST',
'https://api.sandbox.paypal.com/v1/oauth2/token',
[
'grant_type ' => 'authorization_code',
'code' => $data['code']
],
$headers);
Looking at the paypal api documentation, it appears as though your authorization header is incorrect.
Authorization request header:
The Base64-encoded client ID and secret credentials separated by a
colon (:). Use the partner's credentials.
You can use php's base64_encode() function to do this.
$client = new \GuzzleHttp\Client();
$authorizationString = base64_encode($clientId . ':' . $clientSecret);
$client->request(
'POST',
'https://api.sandbox.paypal.com/v1/oauth2/token',
[
'headers' => [
'Authorization' => 'Basic ' . $authorizationString
],
'form_params' => [
'grant_type ' => 'authorization_code',
'code' => $data['code']
]
]
);
I am sending this as a test to a test webserver, but the response although its a 201 which means it got it, it does not show the posted data I want to send:
<?php
$url = "https://jsonplaceholder.typicode.com/posts";
$client = \Drupal::httpClient();
$post_data = array('color' => 'red');
$response = $client->request('POST', $url, [
'form_params' => $post_data,
'verify' => false
]);
$body = $response->getBody();
dsm($body);
?>
Is the format of the request I made incorrect?
I can see that it is not getting the post data because when I do a dsm of the response body, it isn't there.
This worked for me, looks like I needed to add the headers:
$url="https://jsonplaceholder.typicode.com/posts";
$client = \Drupal::httpClient();
$post_data = $form_state->cleanValues()->getValues();
$response = $client->request('POST', $url, [
'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'],
'form_params' => $post_data,
'verify'=>false,
]);
$body = $response->getBody()->getContents();
$status = $response->getStatusCode();
dsm($body);
dsm($status);
Hello guys i've been pulling my hair for this problem. I'm accessing an api from ryver to send post chat messages for automated notification. I'm following this doc https://support.ryver.com/chatmessage-api/ and I'm using laravel 5.1 with Guzzle and here's my code if it helps
$client = new Client();
$postData = \GuzzleHttp\json_encode(['JSON Payload' => ['body' => 'test123']]);
$options = [
'json' => $postData
];
$request = $client->post('https://somecompany.ryver.com/api/1/odata.svc/workrooms(1099207)/Chat.PostMessage()', $options);
$request->setHeader('Content-Type', 'application/json');
$request->setHeader('Accept', 'application/json');
$request->setHeader('Authorization', 'Basic Base64codehere');
$response = $request->send();
It always returns a [status code] 400, Please help :( Thank you and have a great day!
You may try sending the API request using this params
$postData = \GuzzleHttp\json_encode(['body' => 'test123']);
$options = [
'JSON Payload' => $postData
];
Fixed it :) I just need to stringfy the JSON to make it work and set body the JSON. here's the code.
$client = new Client();
$postData = '{
"body":"**Update!**\n> ** Test success for ryver integration.",
"extras": {
"from": {
"__descriptor":"Developer",
"avatarUrl":"https://cdn2.f-cdn.com/ppic/4973381/logo/4389970/developer_avatar.png"
}
}
}';
$request = $client->post('https://company.ryver.com/api/1/odata.svc/workrooms(1098712)/Chat.PostMessage()',[
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'Authorization' => 'Basic base64'
]);
$request->setBody($postData);
$response = $request->send();