create post wordpress.com using rest api - php

I want to make php app to create post on wordpress.com using REST api.
I use this code:
<?php
$curl = curl_init( 'https://public-api.wordpress.com/oauth2/token' );
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_POSTFIELDS, array(
'client_id' => 12345,
'redirect_uri' => 'http://example.com/wp/test.php',
'client_secret' => 'L8RvNFqyzvqh25P726jl0XxSLGBOlVWDaxxxxxcxxxxxxx',
'code' => $_GET['code'], // The code fromthe previous request
'grant_type' => 'authorization_code'
) );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1);
$auth = curl_exec( $curl );
$secret = json_decode($auth);
$access_token = $secret->access_token;
$post = array(
'title'=>'Hello World',
'content'=>'Hello. I am a test post. I was created by
the API',
'date'=>date('YmdHis'),
'categories'=>'API','tags=tests'
);
$post = http_build_query($post);
$apicall = "https://public-api.wordpress.com/rest/v1/sites/mysite.wordpress.com/posts/new";
$ch = curl_init($apicall);
curl_setopt($ch, CURLOPT_HTTPHEADER, array
('authorization: Bearer ' . $access_token,"Content-Type: application/x-www-form-urlencoded;
charset=utf-8"));
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
$return = curl_exec($ch);
echo "<pre>";
print_r($return);
exit;
?>
but I get this error:
{"error":"unauthorized","message":"User cannot publish posts"}
Can help me?
Thanks

Standard way to create posts is to use cookies and nonce.
However I found a more easy way to do it.
Install Basic-Auth plugin to your wordpress.
Create wordpress user with username admin and password admin (both credentials are insecure, used for demonstration purposes only)
Create post using code:
$username = 'admin';
$password = 'admin';
$rest_api_url = "http://my-wordpress-site.com/wp-json/wp/v2/posts";
$data_string = json_encode([
'title' => 'My title',
'content' => 'My content',
'status' => 'publish',
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $rest_api_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
'Authorization: Basic ' . base64_encode($username . ':' . $password),
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
if ($result) {
// ...
} else {
// ...
}
Note that in example above version 2 of REST API is used.

The answer is right that we can use the "Basic-Auth" plugin to make a Rest API request.
But, #vallez want to create a post on wordpress.com website.
And wordpress.com provide the oAuth support for authentication.
Recently I have created a post which demostrate about using the oAuth to create a post on wordpress.com. You can read the article at create the post on wordpress.com site using oAuth and Rest API
Below are the steps to successfully create a post with oAuth on wordpress.com.
Step 1: Add authentication details to get auth key.
$auth_args = array(
'username' => '',
'password' => '',
'client_id' => '',
'client_secret' => '',
'grant_type' => 'password', // Keep this as it is.
);
$access_key = get_access_key( $auth_args );
Below is the function get_access_key() which return the access key.
Step 2: Get Access Key.
/**
* Get Access Key.
*
* #param array $args Auth arguments.
* #return mixed Auth response.
*/
function get_access_key( $args ) {
// Access Token.
$curl = curl_init( 'https://public-api.wordpress.com/oauth2/token' );
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_POSTFIELDS, $args );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1);
$auth = curl_exec( $curl );
$auth = json_decode($auth);
// Access Key.
return $auth->access_token;
}
Step 3: Set post arguments and pass it create the post.
$post_args = array(
'title' => 'Test Post with oAuth',
'content' => 'Test post content goes here..',
'tags' => 'tests',
'post_status' => 'draft',
'categories' => 'API',
);
Step 4: Create a post with the access key.
Now, We have access key and the create post arguments. So, Lets pass them to function create_post().
create_post( $access_key, $post_args );
Step 5: Create a post with access key.
/**
* Create post with access key.
*
* #param string $access_key Access key.
* #param array $post_args Post arguments.
* #return mixed Post response.
*/
function create_post( $access_key, $post_args )
{
$options = array (
'http' => array(
'ignore_errors' => true,
'method' => 'POST',
'header' => array(
0 => 'authorization: Bearer ' . $access_key,
1 => 'Content-Type: application/x-www-form-urlencoded',
),
'content' => http_build_query( $post_args ),
),
);
$context = stream_context_create( $options );
$response = file_get_contents(
'https://public-api.wordpress.com/rest/v1/sites/YOURSITEID/posts/new/',
false,
$context
);
return json_decode( $response );
}

Related

PHP curl POST for Watson Video Enrichment

Am trying to use PHP 7.2 to submit a new job to the Watson Video Enrichment API.
Here's my code:
//set some vars for all tasks
$apiUrl = 'https://api-dal.watsonmedia.ibm.com/video-enrichment/v2';
$apiKey = 'xxxxxxxx';
//vars for this task
$path = '/jobs';
$name = 'Test1';
$notification_url = 'https://example.com/notification.php';
$url = 'https://example.com/video.mp4';
$data = array(
"name" => $name,
"notification_url" => $notification_url,
"preset" => "simple.custom-model",
"upload" => array(
"url" => $url
)
);
$data_string = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_URL, $apiUrl.$path );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
'Authorization: APIKey '.$apiKey
));
$result = curl_exec($ch);
echo $result;
But I can't get it to work, even with varying CURLOPTs, like:
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
I keep getting the response: Bad Request.
Here's the API docs.
Am I setting up the POST CURL all wrong? Is my $data array wrong? Any idea how to fix this?
Reading their API documentation, it looks like the field preset is not of type string. Rather it has a schema defined here. This appears similar to how you are using the upload schema.
You should change your data array to look like this:
$data = array(
"name" => $name,
"notification_url" => $notification_url,
"preset" => array(
"video_url" => "https://example.com/path/to/your/video"
),
"upload" => array(
"url" => $url
)
);
Ok, I figured it out. Thanks to #TheGentleman for pointing the way.
My data array should look like:
$data = array(
"name" => $name,
"notification_url" => $notification_url,
"preset" => array(
"simple.custom-model" => array(
"video_url" => $url,
"language" => "en-US"
)
),
"upload" => array(
"url" => $url
)
);

POST Request PHP with Curl

I'm working on a wordpress project where I have to modify my theme, so I can request a JSON to an external API.
I've been searching through the internet how to do that and a lot of people use CURL.
I must do a POST request, yet I don't know how it works or how to do it.
So far I've got this code running:
$url='api.example.com/v1/property/search/';
$data_array = array(
$id_company => '123456',
$api_token => 'abcd_efgh_ijkl_mnop',
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_array);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'APIKEY: 111111111111111111111',
'Content-Type: application/json'
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$result = curl_exec($curl);
if(!$result){die("Connection Failure");}
curl_close($curl);
echo($result);
I don't know where exactly I should put my authentication info or how does the curl methods work in PHP. Can you guys check it out and help me solve this?
There are some answers out there that would help you, such as this one.
However, WordPress actually has built-in functions to make GET and POST requests (that actually fall back to cURL I believe?) named wp_remote_get() and wp_remote_post(). Clearly in your case, you'll want to make use of wp_remote_post().
$url = 'https://api.example.com/v1/property/search/';
$data_array = array(
'id_company' => 123456,
'api_token' => 'abcde_fgh'
);
$headers = array(
'APIKEY' => 1111111111,
'Content-Type' => 'application/json'
);
$response = wp_remote_post( $url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => $headers,
'body' => $data_array,
'cookies' => array()
)
);
if( is_wp_error( $response ) ){
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
} else {
echo 'Success! Response:<pre>';
print_r( $response );
echo '</pre>';
}

How to get a list of users of bugzilla project using XMLRPC after login

I'm looking for XMLRPC keywords to find out a list of users of a BUGZILLA project.
Here is my code, login works fine and im' able to use several keywords to find out what i need : Bug.search, Bug.fields.
public function loginBz($url,$login,$password,$getResult)
{
set_time_limit(0);
$URI = $url;
$xml_data = array(
'login' => $login,
'password' => $password,
'remember' => 1
);
$ch = curl_init();
$file_cookie = tempnam ("/tmp", "CURLCOOKIE");
$options = array(
//CURLOPT_VERBOSE => true,
CURLOPT_URL => $URI,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array( 'Content-Type: text/xml', 'charset=utf-8' )
);
curl_setopt($ch, CURLOPT_TIMEOUT,60);
curl_setopt_array($ch, $options);
$request = xmlrpc_encode_request("User.login", $xml_data);
// var_dump($request);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_COOKIEJAR, $file_cookie);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$server_output = curl_exec($ch); // Array( [id] => 1 ) for example
$response = xmlrpc_decode($server_output);
//print_r ($response);
if($getResult)
return $response;
else
return $ch;
}
public function getFieldsBz($product,$component,$ch){
$xml_data = array(
'product' => $product,
'component' => '$component'
);
$request = xmlrpc_encode_request("Bug.user", $xml_data); // create a request for filing bugs
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
$server_output = curl_exec($ch); // Array( [id] => 1 ) for example
$response = xmlrpc_decode($server_output);
return $response;
}
I've been searching into BugZilla API but did not found what I need : List of Users for a product Bz.
Does anyone know which keyword I have to use in xmlrpc_encode_request(keyword,array_filter) ?
It would help :)
First there isn't a method called Bug.user, see https://www.bugzilla.org/docs/4.4/en/html/api/Bugzilla/WebService/Bug.html for a complete list.
There is a method called User.get, see https://www.bugzilla.org/docs/4.4/en/html/api/Bugzilla/WebService/User.html#get
There is a parameter called groups which may do what you want depending on how you setup Bugzilla security.
You can use https://xmlrpc.devzing.com/ to experiment or if you upgrade to Bugzilla 5.x you can use the new REST API. https://www.bugzilla.org/docs/5.0/en/html/api/Bugzilla/WebService/Server/REST.html

Getting error in setting Transdirect Shipping sender APi code

I am trying to implement transdirect.com shipping set sender API to my website but i am getting error i don't know what is the main cause of it.
here is the snippet::
$params = array(
'session' => $session,
'postcode' => '2164',
'name' => 'abc',
'company'=>'abc',
'email' => $email ,
'phone' => '4561237',
'streetName' => 'abcStreet',
'streetNumber' => '28',
'streetType' => 'St',
'suburb' => 'JHONFEILD',
'state' => 'NSW',
'pickupDate' => date( 'Y-m-d' ),
'pickupTime' => '1-4pm',
'hydraulicGate' =>'false'
);
$query = http_build_query($params);
$query = 'http://transdirect.com.au/api/v2/booking/sender?'.$query;
$result = json_decode( curl_sender( $query, $session, $email, $arg = 'sender') );
// curl_sender method::
function curl_sender( $url, $session, $email, $arg ) {
if ( $arg == 'sender' ) {
$datastring = "postcode=2164&name=Tara Trampolines&company=abc&email=".$email."&phone=0280049375&streetName=Unit 4/28 Victoria St&streetNumber=28&streetType=St&suburb=SMITHFIELD&state=NSW&pickupDate". date( 'Y-m-d' )."&pickupTime=1-4pm&hydraulicGate=false";
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $datastring);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data1 = curl_exec( $ch );
curl_close( $ch );
return $data1;
}
I am getting:
stdClass Object (
[message] => Must be authenticated-please create a session first.
[code] => 403
)
Here is the link from we have implemented the api::
http://transdirect.com.au/api/v2/documentation
please specify how we can authenticate each method.
Any help will be appreciable, Thanks in advance.
You've to create a valid session before you requesting the API.
Create the session:
$credentials = array(
'email' => 'test#example.com',
'password' => 'secret'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $credentials);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
Take a look at the session part: http://transdirect.com.au/api/v2/documentation
You can't mix the session creation process and the real API request.
Create session
Create API request with this session from step 1.
I'm not sure but I think you don't have to use the valid session as any parameter.
The documentation says only create a valid session, there is no parameter specified to append the session, so creation is maybe enough.
This is maybe very important for you:
Confirm booking with any special instructions etc. Once the booking is
confirmed your session is cleared and you will need to
re-authenticate.

error in Android: GCM using PHP

I used following code in PHP to send GCM message to Android:
<?php
$apiKey = "xxxxx"; //my api key
$registrationIDs = array("APA91bGGN7o7AwVNnv35lwP5Jw8OTJQL331XcxPfEIu4xt-ZKLe6R0aSSbAve99uKSDXhzE9L2PVLihpqFt0DEawhymUs9h5ICbTMweMAEJypg6ZLFqmf6SOGlyULQzudw9MM1DjbPaaKbo--wxWoHGkjyec2H_63e7mesYjaRf4_rgxBe655M0");
// Message to be sent
$message = "Message Text";
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $message ),
);
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
echo $result;
It's working fine. Here I added my device tokens manually(hardcoded).
But when i tried getting device tokens from the database, I am getting below mentioned error.
Code:
<?php
include 'config.php';
if($_REQUEST['msg']!='')
{
echo $message = $_REQUEST['msg'];
// Replace with real BROWSER API key from Google APIs
$apiKey ="xxxxxx"; //my api key
// Replace with real client registration IDs
$sql = mysql_query("SELECT `device_token` FROM `users`");
$result = mysql_fetch_array($sql);
$registrationIDs = $result;
// Message to be sent
$message = $_REQUEST['msg'];
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $message ),
);
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
echo $result;
}
I also tried using json_encode($registration_ids) with no use.
"registration_ids" field is not a JSON array
I finally got a solution. I used a for loop to get all the results into an array and converted array into JSON array using json_encode();
I was getting the same error because my array indexes are not properly sorted I fix it by using PHP's sort() function.
Before Sort
$registration_ids = Array
(
[1] => "xxx"
[6] => "xxx"
[8] => "xxx"
)
Sort
sort($registration_ids);
After Sort
$registration_ids = Array
(
[0] => "xxx"
[1] => "xxx"
[2] => "xxx"
)
Pass to PHP's cURL
$fields = array(
'registration_ids' => $ids,
'data' => array('message' => $data)
);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

Categories