Retrieve authentication token from api via post - php

Im trying to build an app that uses the simplenote api but I am having trouble with the authentication part. I am getting a 400 error(bad request).
Im guessing this issue is not related to the simplenote api, it's rather my understanding of the documentation.
Here is what the api is saying:
HTTP POST to the following URL:
https://simple-note.appspot.com/api/login
The body of the request should contain this, but base64-encoded:
email=[email-address]&password=[password]
To be clear, you will concatenate email= with the user’s email address (trimmed),
&password=, and the user’s password; then base64 the resulting string and send it as
the HTTP request body. (Do not encode this request using the standard variable
encoding used for POSTed web forms. We basically ignore the Content+Type header
for this request, but text/plain makes the most sense here.)
And here is my code so far:
$url = 'https://simple-note.appspot.com/api/login';
$data = array('email' => base64_encode($email), 'password' => base64_encode($password));
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);

I think what they mean is:
$data = base64_encode(http_build_query(array(
"email" => $email,
"password" => $password
));
So base64 encode the resulting string, not the individual parts.
As for making the request. I can recommend you take a look at cURL, it's much faster than file_get_contents.

Related

Failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request - PHP Error

SOLUTION: I had malformed my JSON data for the payload body. The "ttl" => 30 was in the incorrect array() method. This probably won't help anyone in the future, moving the ttl key/value pair made this work correctly as seen below.
$data = array(
"statement" => array(
"actor" => array(
"mbox" => "mailto:test#example.com"
),
),
"ttl" => 30
);
I have checked numerous other StackOverflow questions and cannot find a solution that works. I should note that I am testing this using a local XAMPP server running on port 8080. Not sure if that matters. I have been able to get this working using Postman, but translating it to PHP has been problematic. Am I missing something? I am not all that familiar with PHP, but need this for work.
EDIT: Some more information about what the API is expecting. It's a fairly simple API that requires a JSON body, a Basic Authorization header, and a Content-Type: application/json.
Here is the JSON body I am using in Postman. This is a direct copy/paste from Postman, which is successfully communicating with the API:
{
"statement": {
"actor": {
"mbox": "mailto:test#example.com"
}
},
"ttl": 30
}
Is there a syntax error in my below PHP code for this? Again, I am learning PHP on the fly so I'm unsure if I am properly constructing a JSON payload using the array() method in PHP.
My code below has the $https_user,$https_password, and $url domain changed for obvious security reasons. In my actual PHP code, I have the same credentials and domain used in Postman.
The $randomSessionID serves no real purpose other than an identification number for future requests. Has no affect on the API response failing or succeeding.
<?php
$https_user = 'username';
$https_password = 'password';
$randomSessionID = floor((mt_rand() / mt_getrandmax()) * 10000000);
$url = 'https://www.example.com/session/' . $randomSessionID . '/launch';
$json = json_encode(array(
"statement" => array(
"actor" => array(
"mbox" => "mailto:test#example.com"
),"ttl" => 30
)
));
$options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-Type: application/json\r\n'.
"Authorization: Basic ".base64_encode("$https_user:$https_password")."\r\n",
'content' => $json
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
?>
SOLUTION: I had malformed my JSON data for the payload body. The "ttl" => 30 was in the incorrect array() method. This probably won't help anyone in the future, but moving the ttl key/value pair made this work correctly as seen below.
$data = array(
"statement" => array(
"actor" => array(
"mbox" => "mailto:test#example.com"
),
),
"ttl" => 30
);

Trying to send a HTTP request but have no idea how to do it

I'm trying a new service to do a specific task, they have a pretty basic API which lets the users build simple apps.
An example of the HTTP request is:
https://domainname.com/dashboard/api
?to={PHONE NUMBER}&from={SENDER ID}&message={TEXT}
&email={YOUR EMAIL}&api_secret={API SECRET}
&unicode={TRUE/FALSE}&id={IDENTIFIER}
I have tried everything, using postman,php and googling for the past 3 hours and i can't get it to work.
(even tried to send it through the browser lol)
Whats a proper way to send a http request?
Thank you.
You can send an HTTP request without CURL using PHP5. This answer is based off of How do I send a POST request with PHP?. You'll have to enter your variables into the $data array.
$url = 'https://domainname.com/dashboard/api';
$data = array('to' => PHONE_NUMBER, 'from' => SENDER_ID, 'message' => TEXT, 'email' => EMAIL, 'api_secret' => SECRET, 'unicode' => BOOLEAN, 'id' => IDENTIFIER);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
var_dump($result);
You can test if your requests are working from your script by using http://www.postb.in or some other similar service. This allows you to see your requests to debug them (rather than relying on feedback/errors from the service you are using). Then you'll know if your requests are formatted correctly and working. Sometimes a service is down... and you spend hours troubleshooting something that's not on your end.

HTTPS REQUEST WITH stream_context_create()

I have problem with my code, the error I get is:
Warning: fopen(https://discordapp.com/api/v6/auth/login): failed to open stream: HTTP request failed! HTTP/1.1 400 BAD REQUEST in
C:\xampp\htdocs\s2.php on line 15
Here is the relevant Code:
<?php
$data = array("email" => 'Email#gmail.com', "password" => 'Password');
$data_string = json_encode($data);
$context_options = array (
'https' => array (
'method' => 'POST',
'header'=> "Content-type: application/json\r\n"
. "Content-Length: " . strlen($data_string). "\r\n",
'content' => $data_string
)
);
$context = stream_context_create($context_options);
$fp = fopen('https://discordapp.com/api/v6/auth/login', 'r', false, $context);
?>
Thank you for your help!
It seems directly logging in via a bot is no longer allowed as you should use the OAuth2 (how does OAuth2 work?) functionality of Discord. This means that your bot needs to be set up inside your Discord account and then you may use token-based access on the bot to authenticate the external application against Discord.
The change to no longer allow bot-based logins happened around the beginning of 2017 and at that point all PHP-based Discord-related Github applications stopped to be maintained. Here is a discussion and comment about banning bots with automated login and this one about that OAuth2 has to be used.
Read more about authentication and bots in the Discord OAuth2 chapter.
If you can tell more about what you plan to achieve, maybe we can help you find a solution to your task.
Previous (no-longer working) answer:
I haven't used DiscordApp so I haven't tried this yet. Instead of sending JSON-encoded data, have you tried posting the values as FORM values to the API?
$postData = array(
'email' => 'Email#gmail.com',
'password' => 'Password'
);
$params = array('https' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postData
)
);
$context = stream_context_create($params);
// get the entire response ...
$result = file_get_contents('https://discordapp.com/api/v6/auth/login', false, $context);
// ... or alternatively using fopen()
$fp = fopen('https://discordapp.com/api/v6/auth/login', 'r', false, $context);
I haven't found any docs regarding how the parameters should be passed to the login URI but at least that's how normal form-based logins can be used.
According to the DiscordApp Response codes a 400 may be received if either the call was not understood (non-existent function called) or the parameters were send improperly so you should find out about how to call the logininterface with parameters using scripts.

Webservice not able to parse JSON Request from a PHP file

I'm trying to access a webservice. I'm already using this webservice from an android app but now I need to access some functions from a php document. If I use chromes advanced rest client application for testing it works fine if I select the POST option and application/x-www-form-urlencode as content-type. But when I try to access the webservice from my PHP file I get the response from the server that it can't find the value "tag". This is the code:
$data = array( 'tag' => 'something');
$options = array('http' => array(
'method' => 'POST',
'content' => $data,
'header' => "Content-Type: application/x-www-form-urlencode")
);
$context = stream_context_create($options);
$url = 'myurl';
$result = file_get_contents($url,false,$context);
$response = json_decode($result);
What is wrong with this code?
Thanks for any help!
Try this:
$data = http_build_query( array( 'tag' => 'something') );
As defined here, "Content" value must be a string: http_build_query generate the URL-encoded query string you need.

Validation data using api

I need to validate some form data both in client-side and server-side (php). I can use some API web service to check the data form. The problem is: I can validate the data, in client side, using an Ajax call and my API web service. How can I use the API web service from server-side?
You can use file_get_contents to invoke external call
$homepage = file_get_contents('http://www.example.com/');
And there you can send the parameter from the url itself,
Here the example to send parameter to your api
Construct an array and place your values to be validated
$getdata = http_build_query(
array(
'name' => 'Francesco',
'phone' => '2434343',
'age'=>'23',
'city'=>'MA',
'state'=>'US'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $getdata
)
);
$context = stream_context_create($opts);
Then send it to your api's directly
file_get_contents('http://example.com/send.php?'.$getdata, false, $context);

Categories