Sending a Post Request using ZF2 - zend-framework2

I've been struggling to send a POST with a json to a webservice using ZF2. That's what I've been trying so far:
$array = array('nome' => 'cert123', 'certificado' => $cert);
$json = json_encode($array);
$request = new Request();
$request->getHeaders()->addHeaders([
'Content-Type' => 'application/json; charset=UTF-8'
]);
$request->setUri($this->uri);
$request->setMethod('POST');
$client = new Client();
$client->setAdapter('Zend\Http\Client\Adapter\Socket');
$client->setEncType(Client::ENC_FORMDATA);
$client->setRawBody($json);
$response = $client->dispatch($request);
if ($response->isSuccess()) {
echo "the post worked!";
} else {
echo "the post failed";
}
It's always failing, but I don't get any errors, and the POST request in the network tab just keeps running. Any ideas will be much appreciated.
Tnx

Related

Microsoft Graph - Get Token from Authorisation Response

I am following the instructions here:
https://learn.microsoft.com/en-us/graph/auth-v2-user?view=graph-rest-1.0#3-get-a-token
I get the authorisation response and therefore the required code, but when I request the token I get a "HTTP/1.1 401 Unauthorized" response.
This is my code (not for production, just for me to get the flow/code right first):
<?php
/*
Auth
https://learn.microsoft.com/en-us/graph/auth-v2-user?view=graph-rest-1.0
*/
define("HOST", 'https://login.microsoftonline.com');
define("TENANT", 'common');
define("AUTH_ENDPOINT", HOST.'/'.TENANT.'/oauth2/v2.0/authorize');
define("TOKEN_ENDPOINT", HOST.'/'.TENANT.'/oauth2/v2.0/token');
define("CLIENT_ID", '<< FROM AZURE PORTAL >>');
define("CLIENT_SECRET", '<< FROM AZURE PORTAL >>');
define("ALL_SCOPES", rawurlencode('offline_access user.read mail.read'));
define("CALLBACK", rawurlencode('http://localhost:300/graph2/auth.php'));
// Build URL
$url = AUTH_ENDPOINT."?client_id=".CLIENT_ID;
$url .= "&response_type=code";
$url .= "&redirect_uri=".CALLBACK;
$url .= "&response_mode=query";
$url .= "&scope=".ALL_SCOPES;
echo "<a href=$url>$url</a>";
if (isset($_GET))
{
echo '<pre>';print_r($_GET);echo'</pre>';
if (isset($_GET['code']))
{
// Got authorisation code - now need token
$response = requestAccessTokenByVerifier($_GET['code']);
echo ">".$response;
}
}
function requestAccessTokenByVerifier($verifier)
{
return requestAccessToken(
array(
'client_id' => CLIENT_ID,
'redirect_uri' => CALLBACK,
'client_secret' => CLIENT_SECRET,
'code' => $verifier,
'grant_type' => 'authorization_code',
'scope' => ALL_SCOPES
)
);
}
function requestAccessToken($content)
{
$response = sendRequest(TOKEN_ENDPOINT, 'POST', $content);
if ($response !== false)
{
$authToken = json_decode($response);
if (!empty($authToken) && !empty($authToken->{ACCESSTOKEN})) return $authToken;
}
die("No access token");
return false;
}
function sendRequest($url, $method = 'GET', $data = array(), $headers = array('Content-Type: application/x-www-form-urlencoded'))
{
$context = stream_context_create(
array(
'http' => array(
'method' => $method,
'header' => $headers,
'content' => buildQueryString($data)
)
)
);
echo "URL: $url<br>";
echo '<pre>';print_r($data);echo '</pre>';
echo buildQueryString($data)."<br>";
$response = file_get_contents($url, false, $context);
echo '<pre>';var_dump($http_response_header);echo '</pre>';
return $response;
}
function buildQueryString($array)
{
$result = '';
foreach ($array as $k => $v)
{
if ($result == '') $prefix = ''; else $prefix = '&';
$result .= $prefix . $k . '=' . $v;
}
return $result;
}
?>
As you will see I've put a few basic diagnostics in there which show I am getting the code required successfully, but then not being able to get a token from the code.
Can anybody suggest what to try next, I wonder either from a debugging point of view or alternative approaches.
Thanks.
OK, after digging around I realised I'd made a stupid mistake, but just in case anybody else does the same - you need to use the client secret value not id!
I've deleted that client secret :)
Hope that helps somebody else bashing their head against a brick wall.

how to get callback status in twilio

How to callback status in twilio for example in php.
require __DIR__ . '/vendor/autoload.php';
use Twilio\Rest\Client;
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "---------------";
$token = "-----------------;
$client = new Client($sid, $token);
$call = $client->calls->create(
$to, $from,
array(
"url" => "http://demo.twilio.com/docs/voice.xml",//this line complete
"method" => "GET",
"statusCallbackMethod" => "POST",
"statusCallback" => "https://www.myapp.com/events", //in this line no idea
"statusCallbackEvent" => array(
"initiated", "ringing", "answered", "completed"
)
)
);
echo $call->sid;
In this example how to get event after call
Your code is correct for registering call status notifications from Twilio. For every event you specified in your statusCallbackEvent array, Twilio will make an asynchronous HTTP request to the URL specified in the statusCallback parameter. See this article for more details.
So now you will need a service at this URL: https://www.myapp.com/events, listening for notification sent by Twilio. In your case these will be POST requests, given the method you specified in statusCallbackMethod parameter. The parameter you need to tell which event is being notified is CallStatus. See this documentation for more info.
We're not using PHP, but if you want to do a quick test, just create a Twilio Function and paste the following code in there to see your event notifications:
exports.handler = function(context, event, callback) {
let response = { get_started: true };
console.log(`Call status notified was '${event.CallStatus}'.`);
callback(null, response);
};

Fetch in ReactNative can not deliver the paras in body to the server

ReactNative provide me with fetch to send a httpRequest.The attribute of body includes my parameters which are to send to the server.But I can't get the parameters on my server.My codes are here:
fetch(`${keys.api}/login`,
{
method: 'POST',
body: JSON.stringify({
username: this.state.username,
password: this.state.password,
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}
).then((response) => {
if(response._bodyText == 'success') {
this.props.resetToRoute({
name: '主页',
component: Main,
hideNavigationBar: true,
});
} else {
this.cancelLogin();
}
}).catch((error) => {
console.warn(error);
this.cancelLogin();
});
And the console in my J2EE Web Server prints the message:
The httpRequest message
There is no parameter in my httpRequest(In other words,The body can not deliver any parameters),I need help.
It's dangerous to show my username and password in the url.
i have met the problem twice on jetty-8.1 on different condition
first ,you should know that it has nothing to do with react-native
fetch put the data in body to header "payload" when the client made a request.i thought jetty-8.1 does not support get data from the payload header
,change the way
Getting request payload from POST request in Java servlet will be helpful
or maybe use the websockt or XMLhttpRequest object to send a request
// Read from request
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String data = buffer.toString()

Post Multiple images by statuses/update_with_media twitter api of abraham's twitteroauth library

I am trying to post multiple images by statuses/update_with_media twitter api of abraham's twitteroauth library.
I am posting single image but not multiple images.
My code is like below:
$params = array('media[]' => file_get_contents($image_url),
'status' => $message
);
$connection->post('statuses/update_with_media',$params,true);
Where $connection is a object of TwitterOAuth.
Function of TwitterOAuth library is below:
function post($url, $parameters = array(), $multipart = false) {
$response = $this->oAuthRequest($url, 'POST', $parameters, $multipart);
if ($this->format === 'json' && $this->decode_json) {
return json_decode($response);
}
return $response;
}
I know I have to do some change in media[].But I can not get proper output.
So please suggest me.
Thanks in advance
Harry Shah
You can post multiple images on twitter like this
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token,
$access_token_secret);
$firstimage = $connection->upload('media/upload', ['media' => '/path/to/file/kabootar1.jpg']);
$secondimage = $connection->upload('media/upload', ['media' => '/path/to/file/kabootar2.jpg']);
$parameters = [
'status' => 'This is a test tweet',
'media_ids' => implode(',', [$firstimage->media_id_string, $secondimage->media_id_string])];
$output = $connection->post('statuses/update', $parameters);

Correct Way to use returned ApiGility Implicit Token

My app receives an access token by virtue of an implicit grant. Now I am attempting to use this token to access the content servers RPC service. I am not 100% sure if this is the correct way to do it as I am unable to get it to work.
$code = (string) $this->params()->fromQuery('code', null);
$client = new HttpClient(
'http://www.example.com/api/books',
array(
'maxredirects' => 0,
'timeout' => 30
)
);
$client->setMethod('GET');
$client->setHeaders(
[
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$code
]
);
try {
$response = $client->send();
} catch (\Exception $e) {
throw new \Exception($e);
}
Here is the example in postman which is failing:
In this question the authorization_code was used and not the access_token and that's why it failed.

Resources