Resteasy service expecting 2 json objects - php

I have a service that expects 2 objects... Authentication and Client.
Both are mapped correctly.
I am trying to consume them as Json, but I'm having a hard time doing that.
If I specify just one parameter it works fine, but how can I call this service passing 2 parameters? Always give me some exception.
Here is my rest service:
#POST
#Path("login")
#Consumes("application/json")
public void login(Authentication auth, Client c)
{
// doing something
}
And here is my PHP consumer:
$post[] = $authentication->toJson();
$post[] = $client->toJson();
$resp = curl_post("http://localhost:8080/login", array(),
array(CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
CURLOPT_POSTFIELDS => $post));
I tried some variations on what to put on CURLOPT_POSTFIELDS too but couldn't get it to work.

The problem you are probably having, is that you are declaring $post as a numbered array, which probably contains the array keys you are mapping. Basically, this is what you are giving it:
Array(
1 => Array(
'authentication' => 'some data here'
),
2 => Array(
'client' => 'some more data here'
)
)
When in reality, you should be creating the $post var like so:
Array(
'authentication' => 'some data here',
'client' => 'some more data here'
)
Try changing your code to something more like this (not optimal, but should get the job done):
$authentication = $authentication->toJson();
$client = $client->toJson();
$post = array_merge($authentication, $client);
$resp = curl_post("http://localhost:8080/login", array(),
array(CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
CURLOPT_POSTFIELDS => $post));

Related

Dropbox API - Error: expected list got dict

I am currently building a routine that needs to download files from one specific Dropbox folder , send them to another server and then move them to another folder on Dropbox.
I am using the /files/move_batch API endpoint for Dropbox to do so.
Here are the params sent to the API to move multiples files (well I'm only trying to move one file right now as it's still not working) :
$params = array(
'headers' => array(
'method' => 'POST',
'content-type' => 'application/json; charset=utf-8',
),
'body' => json_encode(array(
'entries' => array(
'from_path' => self::$files[0],
'to_path' => '/Applications/Archives/' . substr(self::$files[0], strrpos(self::$files[0], '/') + 1),
),
'autorename' => true,
)),
);
But I keep getting the same error message :
Error in call to API function "files/move_batch": request body: entries: expected list, got dict
I don't know what the API means by a list or how it should be formated.
The entries value should be a list of dict, one per file you want to move, each one containing both a from_path and a to_path. Your code is supplying the entries value to be a single dict though. (In PHP you can make both lists and dicts using the array keyword.)
It's easier to see and work with when you break it into pieces. Here's a working sample that does that.
<?php
$fileop1 = array(
'from_path' => "/test_39995261/a/1.txt",
'to_path' => "/test_39995261/b/1.txt"
);
$fileop2 = array(
'from_path' => "/test_39995261/a/2.txt",
'to_path' => "/test_39995261/b/2.txt"
);
$parameters = array(
'entries' => array($fileop1, $fileop2),
'autorename' => true,
);
$headers = array('Authorization: Bearer <ACCESS_TOKEN>',
'Content-Type: application/json');
$curlOptions = array(
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($parameters),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_VERBOSE => true
);
$ch = curl_init('https://api.dropboxapi.com/2/files/move_batch');
curl_setopt_array($ch, $curlOptions);
$response = curl_exec($ch);
echo $response;
curl_close($ch);
?>
To move just one file using this batch endpoint, you would change that line to something like:
'entries' => array($fileop1),

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.

How to log into a web service with php post request

So i need to gain access to a web service containing some json, but to do so I was told to make use of PHP POST method to first log into the web service. I was giving an array with 3 types/values.
{
"Username":"user",
"password":"1234",
"LoginClient":"user"
}
I have been searching all day for a solution, but have come up short :(.
Any advice or push into a right direction would be much appreciated.
Hope I have explained this clearly enough.
you could do as follows:
$url = 'http://yourDomain.net/api/auth/';
$data = array('Username' => 'user', 'password' => '1234', 'LoginClient' => 'user');
$opts = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
)
);
$context = stream_context_create($opts); //Creates and returns a stream context with any options supplied in options preset.
$response = file_get_contents($url, false, $context);
var_dump($response);
Or you could read about CURL as another option to make POST requests.

Woocommerce custom payment gateway redirect

I have a problem. I should do a custom gateway. I know the basics. I read the documentation. URL data to be transmitted (such as user name, the amount of the transaction). My question is how to redirect the user to the payment page of the bank? What is the command and where to give the exact url? And then the returned data must be processed what method? cURL or something else? I could not find any real solution to the problem.
Different gateway's have different needs, if your gateway uses a POST, you can use this to POST the data, and get a response.. it is better than cURL.
$response = wp_remote_post( $environment_url, array(
'method' => 'POST',
'body' => http_build_query( $payload ),
'timeout' => 90,
'sslverify' => false,
) );
// Retrieve the body's response if no errors found
$response_body = wp_remote_retrieve_body( $response );
$response_headers = wp_remote_retrieve_headers( $response );
// Payload would look something like this.
$payload = array(
"amount" => $order.get_total(),
"reference" => $order->get_order_number(),
"orderid" => $order->id,
"return_url" => $this->get_return_url($order) //return to thank you page.
);
//use this if you need to redirect the user to the payment page of the bank.
$querystring = http_build_query( $payload );
return array(
'result' => 'success',
'redirect' => $environment_url . '?' . $querystring,
);

Post JSON with PHP CURL to a Tin Can API LRS

Sorry, I can only post 2 hyperlinks so I'm going to have to remove the http : //
Background
I'm, trying to convert the code here: https://github.com/RusticiSoftware/TinCan_Prototypes/blob/92969623efebe2588fdbf723dd9f33165694970c/ClientPrototypes/StatementIssuer/StatementIssuer.java
into PHP, specifically the makeRequest function. This code posts data to a Tin Can Compliant Learner Record Store.
The current version of my PHP code is here:
tincanapi.co.uk/wiki/tincanapi.co.uk:MediaWikiTinCan
The specification for the Tin Can API which everything should conform to is here:
scorm.com/wp-content/assets/tincandocs/TinCanAPI.pdf
There is also a working java script function that Posts data in the right format here (see the XHR_request function I think):
https://github.com/RusticiSoftware/TinCan_Prototypes/blob/92969623efebe2588fdbf723dd9f33165694970c/ClientPrototypes/GolfExample_TCAPI/scripts/TCDriver.js
I don't have access to the code or server that I'm posting to, but the end result should be an output here: beta.projecttincan.com/ClientPrototypes/ReportSample/index.html
Problem
I'm trying to use Curl to POST the data as JSON in PHP. Curl is returning 'false' but no error and is not posting the data.
On the recommendation of other questions on this site, I've tried adding 'json=' to the start of the POSTFIELDS, but since the Java and JavaScript versions does have this, I'm not sure this is right.
Can anybody suggest either how I might fix this or how I might get useful errors out of curl? My backup is to output the relevant JavaScript to the user's browser, but surely PHP should be able to do this server side?
Very grateful for any help.
Andrew
At least one thing is wrong: you should not be using rawurlencode on your Authorization header value.
Consider using php streams and json_encode() and json_decode() instead. The following code works.
function fopen_request_json($data, $url)
{
$streamopt = array(
'ssl' => array(
'verify-peer' => false,
),
'http' => array(
'method' => 'POST',
'ignore_errors' => true,
'header' => array(
'Authorization: Basic VGVzdFVzZXI6cGFzc3dvcmQ=',
'Content-Type: application/json',
'Accept: application/json, */*; q=0.01',
),
'content' => json_encode($data),
),
);
$context = stream_context_create($streamopt);
$stream = fopen($url, 'rb', false, $context);
$ret = stream_get_contents($stream);
$meta = stream_get_meta_data($stream);
if ($ret) {
$ret = json_decode($ret);
}
return array($ret, $meta);
}
function make_request()
{
$url = 'https://cloud.scorm.com/ScormEngineInterface/TCAPI/public/statements';
$statements = array(
array(
'actor' => array(
'name' => array('Example Name'),
'mbox' => array('mailto:example#example.com'),
'objectType' => 'Person',
),
'verb' => 'experienced',
'object' => array(
'objectType' => 'Activity',
'id'=> 'http://www.thincanapi.co.uk/wiki/index.php?Main_Page',
'definition' => array(
'name' => array('en-US'=>'TinCanAPI.co.uk-tincanapi.co.uk'),
'description' => array('en-US'=> 'TinCanAPI.co.uk-tincanapi.co.uk'),
),
),
),
);
return fopen_request_json($statements, $url);
}
list($resp, $meta) = make_request();
var_export($resp); // Returned headers, including errors, are in $meta
We've now released an open source library specifically for PHP, it uses a similar method as the accepted answer but rounds out the rest of the library as well. See:
http://rusticisoftware.github.io/TinCanPHP/
https://github.com/RusticiSoftware/TinCanPHP

Categories