Curl to PHP with array, probably simple answer - php

I'm new to curl in PHP... and I was just wondering how to transform this curl command into PHP:
curl https://ancient-test.chargebee.com/api/v1/portal_sessions \
-u test_rdsfgfgfddsffds: \
-d customer[id]="EXAMPLE" \
-d redirect_url="https://yourdomain.com/users/3490343"
Right now I've got:
$post_data['customer']['id'] = "EXAMPLE";
$post_data['redirect_url'] = "http://" . SITE_URL . "/myaccount/";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,"https://ancient-test.chargebee.com/api/v1/portal_sessions");
curl_setopt($ch,CURLOPT_USERPWD,"test_rdsfgfgfddsffds:");
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
$output = curl_exec($ch);
curl_close($ch);
But I get the error message:
{"errors":[{"message":"There were errors while submitting"},{"param":"customer[id]","message":"cannot be blank"}]}
Thanks for your help!
Jan

https://github.com/CircleOfNice/CiRestClientBundle
This one has a beautiful api.
$client->post($url, $payload, $options);

Using curl here's probably the answer Posting with PHP and Curl, deep array
$post_data['customer[id]'] = "EXAMPLE";
Guzzle is an awesome HTTP client library wrapping curl in PHP that will make your life way easier :)
With guzzle v6 your php code would look like this :
$client = new GuzzleHttp\Client();
$res = $client->request('POST', 'https://ancient-test.chargebee.com/api/v1/portal_sessions', [
'auth' => ['test_rdsfgfgfddsffds', 'password'],
'json' => [customer => [id => 'EXAMPLE']]
]);

Related

Messenger API Attachment using PHP Curl (Upload from File)

Hi guys I'm getting trouble uploading attachment in facebook messenger API
https://developers.facebook.com/docs/messenger-platform/reference/attachment-upload-api/
I'm using php code but I tried all possible action to upload but my code didn't work every time I send a post request I received this error
"message":"(#100) Incorrect number of files uploaded. Must upload
exactly one file.","type":"OAuthException","code":100"
I tried this curl pattern from the documentation
curl \
-F 'message={"attachment":{"type":"image", "payload":{"is_reusable":true}}}' \
-F 'filedata=#/tmp/shirt.png;type=image/png' \
"https://graph.facebook.com/v12.0/me/message_attachments?access_token=<PAGE_ACCESS_TOKEN>"
and here's my code PHP code
function uploadFromFile($psid,$file) {
$reply_message['message']['attachment'] = array(
'type' => 'image',
'payload' => array(
'is_reusable' => true
)
);
$reply_message['filedata'] = "#".$file['tmp_name].";type=image/png";
$url = "https://graph.facebook.com/v12.0/me/message_attachments?access_token=" . $this->accessToken;
$ch = curl_init();
$headers = array("Content-type: application/json");
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($reply_message));
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,$false);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$st = curl_exec($ch);
curl_close($ch);
file_put_contents("errormessage-api.txt",$st);
$result = json_decode($st,TRUE);
$this->send($psid,$result['attachment_id']);
return $result['attachment_id'];
}
I know the error is on my payload I don't know the right syntax. Thank you guys!

Why do I keep getting unsupported_grant_type when using oAuth2 and curl?

I am trying to authenticate my self with uber rush api, and I keep getting an unsupported_grant_type error message. I am not sure what am I doing wrong here. Any help would be really appreciated. Below is the code I am using
Here is what the command line request looks like:
curl -F "client_secret=<CLIENT_SECRET>" \
-F "client_id=<CLIENT_ID>" \
-F "grant_type=client_credentials" \
-F "scope=delivery" \
https://login.uber.com/oauth/v2/token
Here is how I wrote it in PHP
$cl = curl_init("https://login.uber.com/oauth/v2/token");
curl_setopt($cl,CURLOPT_POST,["client_secret"=>"********"]);
curl_setopt($cl,CURLOPT_POST,["client_id"=>"**********"]);
curl_setopt($cl,CURLOPT_POST,["grant_type"=>"client_credentials"]);
curl_setopt($cl,CURLOPT_POST,["scope"=>"delivery"]);
$content = curl_exec($cl);
curl_close($cl);
var_dump($content);
This is not how to add POST data to cURL. There is PHP documentation to tell you what these options actually mean. Try this instead:
<?php
$postdata = [
"client_secret"=>"xxx",
"client_id"=>"xxx",
"grant_type"=>"client_credentials",
"scope"=>"delivery",
];
$cl = curl_init("https://login.uber.com/oauth/v2/token");
curl_setopt_array($cl, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postdata,
CURLOPT_RETURNTRANSFER => true
]);
$content = curl_exec($cl);
curl_close($cl);
var_dump($content);
This answer is also very useful if the above answer doesn't work: Curl Grant_Type not found FIXED.

cURL command to Guzzle

I need to convert a cURL command like this into Guzzle-way:
curl -XPOST "https://api/v1.0/endpoint" -F "file=#img.jpg"
This is what I'm trying so far:
$httpClient = new \GuzzleHttp\Client;
$req = $httpClient->createRequest('POST', $url), []);
$postBody = $req->getBody();
$postBody->addFile(new \GuzzleHttp\Post\PostFile('photo', fopen(storage_path() . '/' . $filename, 'r')));
$response = $httpClient->send($req);
But I'm not getting the same response as with the previous command, which is something like:
{"id":5378678,"url":"ui/54/68/97/24/img.jpg"}
I'm getting a GuzzleHttp\Message\Response object, but I'm not being able to find the id and url attributes in there.
Any help will be appreciated!
Just noticed I could do $response->json() to get what I wanted.

PHP to connect to remote Parse MongoDB; cURL works on command line but PHP file_get_contents doesn't

I am working with a Wordpress site with CPanel and a MySQL database. I want to be able to read data from a MongoDB held on Parse.com. Eventually, I want to change Wordpress's login.php script to search through the MongoDB and create users if necessary.
I am having lots of trouble connecting to the database.
Here is my php script:
<?php
$url = 'http://mercury.example.com:2234/parse/login';
$data = array('username' => 'username', 'password' => 'password');
$appID = "X-Parse-Application-Id: parseAppID";
$restKey = "X-Parse-REST-API-Key: praseRESTapiKey";
$session = "X-Parse-Revocable-Session: 1";
$contentType = "Content-Type: application/json";
$context = array(
'http'=> array(
"method" => "GET",
"header" => $appID . $restKey . $session . $contentType,
"content" => http_build_query($data)));
$context = stream_context_create($context);
$result = file_get_contents($url, false, $context);
var_dump($result);
?>
The errors I am receiving are:
Notice: file_get_contents(): Content-type not specified assuming application/x-www-form-urlencoded in C:\wamp\www\parseDB.php on line 26
Warning: file_get_contents(http://mercury.example.com:2234/parse/login): failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden in C:\wamp\www\parseDB.php on line 26
From my understanding, the 403 error means the web server is returning the "forbidden" status code.
I am testing my php script on localhost using WAMP. A colleague of mine tried to run a similar command on Bash and received a response. (I broke it out so it is easier to read).
curl -X GET
-H "X-Parse-Application-Id: parseAppID"
-H "X-Parse-REST-API-Key: parseRESTapiKey"
-H "X-Parse-Revocable-Session: 1"
-G --data-urlencode 'username=username' --data-urlencode 'password=password'
http://mercury.example.com:2234/parse/login
I have been stuck on this for 2 days so far, and I have no idea what is going on. I appreciate all the help I can get.
EDIT
Here is my final solution:
$url = 'http://mercury.example.com:3432/parse/login';
$data = array('username' => 'USERNAME', 'password' => 'PASSWORD!');
$context = array(
'http'=> array(
'method' => "GET",
'header' => "X-Parse-Application-Id: APPID\r\n" .
"X-Parse-REST-API-Key: RESTAPIKEY\r\n" .
"X-Parse-Revocable-Session: 1" .
"Content-Type: application/json\r\n",
'content' => http_build_query($data)
)
);
$context = stream_context_create($context);
$result = file_get_contents($url, false, $context);
var_dump($result);
?>
Look at the stream_content_create example at http://php.net/manual/en/function.stream-context-create.php which explains how to pass headers properly. At this time, you slam each header together without any line feeds which will make them look like concatenated string:
X-Parse-Application-Id: parseAppIDX-Parse-REST-API-Key: praseRESTapiKeyX-Parse-Revocable-Session: 1Content-Type: application/json
Hint - add \r\n after each header line.
Instead of file_get_contents you could also use curl methods.

Godaddy api authorization error

I am trying to develop client application for GoDaddy based on their API that they provide here https://developer.godaddy.com
And I have a problem with simple example, I am trying to use the next PHP code to check if domain available:
use GuzzleHttp\Client;
try {
$client = new Client([
'base_uri' => 'https://api.godaddy.com',
]);
$responce = $client->get(
'/v1/domains/available?domain=example.guru',
[
'headers' => [
'Authorization' => "sso-key $myKey:$mySecret",
'X-Shopper-Id' => "$myID",
'Accept' => 'application/json',
]
]
);
echo $responce->getBody();
} catch (Exception $e) {
echo $e->getMessage();
}
And all the time I get error: "Client error: 401". Same problem I have with using cURL library. I didn't find any online support.
I need help with it, can someone explain how I should authorize at their api service? Maybe I need to send any other http headers or additional params?
Are the key and secret you're using for production? When I go through the process, by default it creates a TEST key/secret, which I think are meant to go against https://api.ote-godaddy.com
If you are using production keys, try doing a manual Curl request from the command like; something like:
curl -H 'Authorization: sso-key {KEY}:{SECRET}' -H 'Content-Type: application/json' https://api.godaddy.com/v1/domains/available?domain=example.guru'
Let us know how it works out!
The problem was that I was using TEST {KEY}:{SECRET} and set wrong URL.
For the test {KEY}:{SECRET} URL has to be: https://api.ote-godaddy.com.
Also the method for checking domain availability (/v1/domains/available) doesn't need parameter 'X-Shopper-Id' in header. It works well without it. With parameter X-Shopper-Id request returns error "NOT_FOUND: The specified shopperId could not be found"(but it's other problem, maybe I didn't activate some option)
So if to take into account all changes, the working code for checking domain availability with test key/secret should be like this:
use GuzzleHttp\Client;
try {
$client = new Client([
'base_uri' => 'https://api.ote-godaddy.com'
]);
$responce = $client->get(
'/v1/domains/available?domain=example.guru',
[
'headers' => [
'Authorization' => "sso-key $myKey:$mySecret",
'Accept' => 'application/json',
]
]
);
echo $responce->getBody();
} catch (Exception $e) {
echo $e->getMessage();
}
I am using php and curl.
$domain = "jaisinghverma.com";<br>
$apiURL = 'https://api.ote-godaddy.com/v1/domains/available?
domain='.$domain.'&checkType=FULL&forTransfer=false';<br>
$headers = array(
'Accept: application/json',
'Authorization: sso-key ?????????',
);<br>
$ch = curl_init();<br>
curl_setopt($ch, CURLOPT_URL, $apiURL);<br>
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);<br>
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);<br>
$server_output = curl_exec ($ch);<br>
curl_close ($ch);<br>
print_r(json_decode($server_output));
above code is working fine for me.

Categories