Unable to retrieve body from wp_remote_post request to a WP rest api registered route - wordpress-rest-api

I am trying to make a simpole post request to a registered route using the following method:
// inside a function that registers the rest route
$namespace = 'marketplace/v1';
$route = 'one_image';
register_rest_route($namespace, $route, array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => [$this, 'one_image'],
));
//inside a function
...
$args = array(
'method' => 'POST',
'headers' => array(
'Content-type: application/x-www-form-urlencoded'
),
'sslverify' => false,
'body' => array(
'this' => 'should show in response'
)
);
$response = wp_remote_request($url, $args);
...
public function one_image(\WP_REST_Request $request) {
$params = $request;
$response = new WP_REST_Response($params);
return rest_ensure_response($response); <--- this just returns an empty object
}
Why are my body arguments not being returned in the response?

Related

Argument 1 passed to GuzzleHttp\Client::send() must implement interface

hi I am new to laravel and I am trying to consume the api with laravel 8 I have a problem with my POST and I do not understand
public function storeEntreprise(Request $request){
$request->validate([
'name' => 'required',
'email' => 'required',
'phone_number'=>'required',
'address' => 'required',
'password' => 'required',
'password_confirmation' => 'required'
]);
$client = new Client();
$post = $request->all();
$url = "http://flexy-job.adsyst-solutions.com/api/entreprises-store";
$create = $client->request('POST', $url, [
'headers' => [
'Content-Type' => 'text/html; charset=UTF8',
],
'form-data' => [
'name' => $post['name'],
'email' => $post['email'],
'phone_number' => $post['phone_number'],
'address' => $post['address'],
'logo' => $post['logo'],
'password' => $post['password'],
'password_confirmation' => $post['password_confirmation']
]
]);
//dd($create->getBody());
echo $create->getStatusCode();
//echo $create->getHeader('Content-Type');
echo $create->getBody();
$response = $client->send($create);
return redirect()->back();
}
Can you help me please
You calling (accidentally?) $response = $client->send($create); where $create is response of API request you made ($create = $client->request('POST', $url, ...).
So PHP reports you that you can't pass ResponseInterface where RequestInterface required.
Also, you echo's body of response, and return redirect response at same time. So browser will not show you API response (because of instance back redirect).

Drupal7 REST: I am not able to perform POST and PUT methods. Error is :Not Acceptable : Node type is required, Code:406?

I'm using drupal7. my drupal_http_request() for get and delete are working fine for authenticated users, but the post and put methods are not working.
The error is :Not Acceptable : Node type is required, and http error code is :406. My code is below:
function ws_form_post_auth() {
$base_url = 'http://localhost/drupalws/api/v1';
$data = array(
'username' => 'student1',
'password' => 'welcome',
);
$data = http_build_query($data, '', '&');
$options = array(
'headers' => array(
'Accept' => 'application/json',
),
'method' => 'POST',
'data' => $data
);
$response = drupal_http_request($base_url . '/user/login', $options);
$data = json_decode($response->data);
// Check if login was successful
if ($response->code == 200) {
$options['headers']['Cookie'] = $data->session_name . '=' . $data->sessid;
$options['headers']['X-CSRF-Token'] = $data->token;
$data = array(
'title' => 'First forum post',
'type'=> 'forum',
'body'=> array(
'und'=>array(
0=> array(
'value'=>'This is my first forum post via httprequest.'
)
)
)
);
$data = json_encode($data);
$options['data'] = $data;
$options['method'] = 'POST';
$response = drupal_http_request($base_url . '/node', $options);
return $response->status_message;
}
return $response->status_message;
}
I got the solution for my issue,I just missed a Content-Type in Headers.
[....]
if ($response->code == 200) {
$options['headers']['Cookie'] = $data->session_name . '=' . $data->sessid;
$options['headers']['X-CSRF-Token'] = $data->token;
$options['headers']['Content-Type'] = 'application/json';
[....]

REST Api for Sugarcrm

Sugarcrm is providing Restful API support.So how can i check json response using rest client(browser plugin to check restful web services)?.
I am developing a web-app using spring MVC(Restful API).I want to use sugarcrm as my crm module.how can i integrate both?.
I have gone through sugar's documentation about the same ,but I do not have any idea about php biased programming.
can anyone please help me?
Thanks.
run below code, if you have any problem then let me know.
<?php
//Put your Base url
$url = 'yoursugarcrm_url/service/v4_1/rest.php';
// Open a curl session for making the call
$curl = curl_init($url);
// Tell curl to use HTTP POST
curl_setopt($curl, CURLOPT_POST, true);
// Tell curl not to return headers, but do return the response
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Set the POST arguments to pass to the Sugar server
$parameters = array(
'user_auth' => array(
'user_name' => 'admin',
'password' => md5('uDje9ceUo89nBrM'),
),
);
$json = json_encode($parameters);
$postArgs = array(
'method' => 'login',
'input_type' => 'JSON',
'response_type' => 'JSON',
'rest_data' => $json,
);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($curl);
// Convert the result from JSON format to a PHP array
$result = json_decode($response);
if ( !is_object($result) ) {
die("Error handling result.\n");
}
if ( !isset($result->id) ) {
die("Error: {$result->name} - {$result->description}\n.");
}
// Get the session id
$sessionId = $result->id;
//echo json_encode(array("sessionId"=>$sessionId));
//Your moduel parameter
//Parameter of the customer
$fullname = $_POST['fullname'];
$password = md5($_POST['password']);
$email_address = $_POST['email_address'];
// My moduel
$parameters = array(
'session' => $sessionId, //Session ID get from session.php
'module' => 'custo_Customers', // Your PackageKey_ModuleName
'name_value_list' => array (
array('name' => 'fullname', 'value' => $fullname),
array('name' => 'email_address', 'value' => $email_address),
array('name' => 'password', 'value' => $password),
),
);
$json = json_encode($parameters); // Json strgin
$postArgs = 'method=set_entry&input_type=JSON&response_type=JSON&rest_data=' . $json;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($curl);
// Convert the result from JSON format to a PHP array
$result = json_decode($response,true);
echo $response;
?>

Error 100 schedule a post on Facebook Page

I've used the following code. It works fine without 'scheduled_publish_time', otherwise I get this error "(#100) You cannot specify a scheduled publish time on a published post".
I've previously registered my app with another piece of code. It's so weird.
include_once("inc/facebook.php"); //include facebook SDK
$appId = '21xxxxxxxxxxx'; //Facebook App ID
$appSecret = '6b8f4bxxxxxxxxxxxxxd56'; // Facebook App Secret
$return_url = 'http://localhost:8888/...'; //return url (url to script)
$homeurl = 'http://localhost:8888/...'; //return to home
$fbPermissions = 'publish_stream,manage_pages'; //Required facebook permissions
//Call Facebook API
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $appSecret,
'cookie' => true,
'fileUpload' => true
));
$accounts = $facebook->api('/me/accounts');
$PAGE_ID = get_option('fb_post_cron_page'); // it is an option saved in WordPress
foreach($accounts['data'] as $account){
if($account['id'] == $PAGE_ID){
$ACCESS_TOKEN = $account['access_token'];
}
}
$post_url = '/'.$PAGE_ID.'/photos';
$upload_dir = wp_upload_dir();
$upload_dir= $upload_dir['path'];
$timezone= 'Europe/Rome';
$date = new DateTime($dateStr, new DateTimeZone($timezone));
//posts message on page statues
$args = array(
'access_token' => $ACCESS_TOKEN,
'source' => '#' . $image_abs_path,
'message' => $post_message,
'published' => true,
'scheduled_publish_time' => $date->getTimestamp()
);
try {
$postResult = $facebook->api($post_url, 'post', $args );
} catch (FacebookApiException $e) {
echo $e->getMessage();
}
you have to set 'published' to false
$args = array(
'access_token' => $ACCESS_TOKEN,
'source' => '#' . $image_abs_path,
'message' => $post_message,
'published' => false,
'scheduled_publish_time' => $date->getTimestamp()
);

Hashing passwords and AuthComponent

I'm trying to login in my CakePHP 2.0 application but I always get the login error.
In the official documentation and the tutorial I've read how to hash the passwords, but I still get the login error, here is how I did it:
// Users Model
public function beforeSave ($options = array ()) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
return true;
}
// Users Controller
public $components = array ('Acl', 'Session',
'Auth' => array (
'authenticate' => array (
// login e logout sono di default i seguenti controller e views
// 'loginRedirect' => array ('controller' => 'users', 'action' => 'login'),
// 'logoutRedirect' => array ('controller' => 'users', 'action' => 'logout'),
'Form' => array (
'fields' => array (
// il valore default
'username' => 'email'
),
'scope' => array (
'User.active' => 1
)
)
),
'authError' => 'Login error message I get'
));
public function login () {
if ($this->request->is('post')) { // if the request came from post data and not via http (useful for security)
// the password is hashed in User Model in beforeSave method as read on documentation
// debug ($this->data);
if ($this->Auth->login()) {
$id = $this->Auth->user('id');
return $this->redirect(array('controller'=>'users', 'action'=>$id, $this->Auth->user('username')));
} else {
$this->Session->setFlash('Login error message', 'default', array(), 'auth');
}
}
}
In the view I have this:
// the view login.ctp
echo $this->Form->text('User.email', array('id'=>'email', 'value'=>'your#email.com'));
echo $this->Form->password('User.password', array('id'=>'password', 'value'=>'password'));
If I try to debug the data I get this:
// in the controller
debug($this->data);
// in the view
Array
(
[User] => Array
(
[email] => the#email.com
[password] => thepass // not hashed
)
)
I can't login because I get always the Login error message. How can I fix it?
Vitto,
(1) Which error message is displayed?
(2) Just for the record, be sure sessionFlash is printed at layout!
echo $this->Layout->sessionFlash();
(3) How did you set your Auth component? For example, in my AppController I've set this way:
public $components = array(
'Session',
'Cookie',
'Acl',
/**
* Default is authorize option is ActionsAuthorize.
* In this case, system uses AclComponent to check for permissions on an action level.
* learn more: http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#authorization
*/
'Auth'=> array(
'authorize' => array(
'Actions' => array('actionPath' => 'controllers')
),
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email', 'password' => 'password')
)
)
)
);
(4) Finally, I believe (must be sure) there is no need to manually hash password to perform login. At least, after correct configuration, this code works for me:
if ($this->request->is('post')) {
if ($this->Auth->login()) {
// recirect stuffs