Calling WordPress REST API from server - php

I have an application server written in PHP, and it needs to interact with a WordPress deployment through WP's REST API. I am having difficulty calling the WP's REST API with authentication. For example, how do I create a user after authenticated with WP?
Most of the examples I found online are either using Ajax or cookies for authentication, which don't work in the server situation.
Can anyone suggest?

So you question is : how do I create a user after authenticated with WP?
I'm considering you don't have probem in the process of authentication.
If you use PHP you can use php file_get_contents function or cURL
bellow I will give you an example with PHP cURL
$post = array(
'username' => 'user2',
'email' => 'user2#somedomain.com',
'password' => 'somerandompassword');
$post = http_build_query($post);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost/wp/wp-json/wp/v2/users");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, "username" . ":" . "password"
);
$headers = array();
$headers[] = "Content-Type: application/x-www-form-urlencoded";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
print_r(json_decode($result, true), true);
You also can use file_get_contents function if your server can't use cURL for some reasons. You can find another another example of WP REST API with php in here www.wpsaga.info/tag/wp-rest-api

Related

PHP / Curl Incoming Webhook to MS Teams doesn't work all of the time

I am using an incoming webhook on a web app to post some data to teams. I got this working in CURL after looking up some implementation methods, but it should be noted I have no experience in CURL. The thing is, it works about half the time, then the other half this comes up in the error log:
[01-Feb-2021 09:00:59 Europe/London] Error: Could not resolve host: outlook.office.com
Was hoping someone can take a look and see if there is something obvious I am doing wrong. This is the code used in my PHP file (with the webhook ID removed for privacy)
// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch, CURLOPT_URL, 'webhook-id-here');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"text\": \"$teamsMessage\"}");
$headers = array();
$headers[] = 'Content-Type:application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
error_log("Error: " . curl_error($ch), 0);
}
curl_close($ch);
Looks like a DNS problem. Could not resolve host: outlook.office.com.
Maybe any firewall involved in blocking that? Remove CURLOPT_SSL_VERIFYPEER and CURLOPT_IPRESOLVE.
Try this simplified solution, which works well for me. I am using JSON header instead of form encoding.
// Paste the URL here
$url = 'https://outlook.office.com/webhook/XXX';
// Use the text encoded as MARKDOWN.
// Any markdown character needs to be escaped!
$body = ['text' => 'Hello World'];
$curlHandle = curl_init($url);
curl_setopt_array($curlHandle, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode($body)
]);
$response = curl_exec($curlHandle);
curl_close($curlHandle);
if ($response !== '1') throw new Exception('No Response from MS incoming webhook API');

Backendless standalone cannot check isvalidusertoken REST API

I've been using the cloud environment, which works fine. I just recently downloaded the standalone version and am successfully running it on my ubuntu server. All the PHP SDK calls work, and the api/v1/data/[X Table Name] CuRL requests work.
However, I cannot get the CuRL request for valid login and logout to work. With the cloud implementation this was working:
function isValidToken($userToken){
$ch = curl_init();
$appId = APP_ID_FOR_CLOUD;
$restKey = REST_KEY_FOR_CLOUD;
$headers = array("application-id:$appId","secret-key:$restKey","application-type:REST");
curl_setopt($ch, CURLOPT_URL, "https://api.backendless.com/v1/users/isvalidusertoken/" . $userToken);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
This returns the proper response.
Now the only thing that changes are the IDs, keys, and URL, but it cannot find the requested URL. Here is the call to the standalone implementation:
function isValidToken($userToken){
$ch = curl_init();
$appId = APP_ID_STANDALONE;
$restKey = REST_KEY_STANDALONE;
$headers = array("application-id:$appId","secret-key:$restKey","application-type:REST");
curl_setopt($ch, CURLOPT_URL, "http://[my_server_ip_address]/v1/users/isvalidusertoken/" . $userToken);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
echo curl_error($ch);
curl_close($ch);
return $response;
}
The response I get is:
The requested URL /v1/users/isvalidusertoken/35A977A7-60DB-3772-FFC9-29E72AFAA200 was not found on this server.
Does anyone know how to resolve this issue? Thanks in advance!
I was just able to figure this out, the issue was due to a simple typo in the URL. For anyone who may make the same mistake, the standalone URL (for isvaliduesrtoken) is:
http://[my_server_ip_address]/api/<your_app_version>/users/isvalidusertoken/<user-token>

Send and Receive JSON using an https curl_exec call in PHP

I'm trying to make a curl call using PHP. My project has a flow like this
I redirect user to the server.
User uses the services and the server redirects him to a page on my application.
I would like to make a server to server call at this point to verify certain details.
Point to be noted - I post JSON data as well as receive JSON data as response.
I have tried this. I am able to send data but don't get any response.
Is this correct?
Please help!
$data = array("One" => "Onedata", "Two" => "Twodata");
$JsonData = json_encode($data);
$ch = curl_init('https://exampleurl');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $JsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($JsonData))
);
$result = curl_exec($ch);
As you mention in the comment:
The problem is with SSL verification of the host. It takes some effort (see http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/) to setup SSL correctly, so a workaround is to add the following two options:
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
Try to use the below code which works for me. and make sure the json_url is correct. When you run it on the browser you should get an output. Before try it using CURL, run in on the browser and see whether you get the output you want.
$json_url ='https://exampleurl';
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json')
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$results = curl_exec($ch); // Getting jSON result string
$json_decoded = json_decode($results);

Php converting file_get_contents fails to connect Bing Search API using Windows Azure

When try to create a new API request with the Windows Azure new Bing based API, Using the code below
$url= 'https://'.$this->m_host.'/Web?Query={keyword}&Adult=%27Off%27&$top=50&$format=Atom';
$url=str_replace('{keyword}', urlencode($this->m_keywords), $url);
// Replace this value with your account key
$accountKey = $this->key;
$WebSearchURL = $url;
$context = stream_context_create(array(
'http' => array(
'proxy' => 'tcp://127.0.0.1:8888',
'request_fulluri' => true,
'header' => "Authorization: Basic " . base64_encode($accountKey . ":" . $accountKey)
)
));
$request = $WebSearchURL;
$response = file_get_contents($request, 0, $context);
print_r($response);
i get following error.
Warning: file_get_contents() [function.file-get-contents]:
Couldn't connect to server in /home/xxxxx on line 43
Warning: file_get_contents(https://api.datamarket.azure.com/
failed to open stream: operation failed in /home/xxxx/ bing_search.php on line 43
Any idea why this fails ? or is it best to use the CURL Library than the file_get_contents() ?
The below code works for me, it is to search news but it will work for web searches too.
Just replace appkey with your one, leave username as it is (i.e. username) since it is ignored by the server
function getBingResult($keyword)
{
$credentials = "username:appkey";
$url= "https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/News?Query=%27{keyword}%27". "&\$format=json";
$url=str_replace('{keyword}', urlencode($keyword), $url);
$ch = curl_init();
$headers = array(
"Authorization: Basic " . base64_encode($credentials)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,5);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($session, CURLOPT_VERBOSE, TRUE);
$rs = curl_exec($ch);
$jsonobj = json_decode($rs);
curl_close($ch);
return $jsonobj;
}
Testing the function:
$bingResult = getBingResult("John");
foreach($bingResult->d->results as $value)
{
echo '<pre>'."URL:". $value->Url.'</pre>';
echo '<pre>'."Title:". $value->Title.'</pre>';
echo '<pre>'."Description:". $value->Description.'</pre>';
echo '<pre>'."Source:". $value->Source.'</pre>';
echo '<pre>'."Date:". $value->Date.'</pre>';
}
Either file_get_contents or CURL will work for the Bing API, you can use what will work on your system and what you are comfortable with.
First I would check your server can connect to the Windows Azure server. Try running a ping and then a wget from the command line to see if it can. Do you go through a proxy? You'll need to set those details in your stream context.
I'm not sure what you have $this->m_host set to, but the new Bing API should be at either:
https://api.datamarket.azure.com/Bing/Search/ or https://api.datamarket.azure.com/Bing/SearchWeb/. The URL https://api.datamarket.azure.com/Web comes back as invalid.
Here is working example of Search API just replace your access key with "XXXX". Even i wasted quite a few hours to get it work using cURL but it was failing cause of "CURLOPT_SSL_VERIFYPEER" on local :(
$process = curl_init('https://api.datamarket.azure.com/Bing/Search/Web?Query=%27xbox%27');
curl_setopt($process, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($process, CURLOPT_USERPWD, "username:XXXX");
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($process);
# Deliver
return $response;
# Have a great day!
curl_close($process);
1.) You do not need str_replace(). Use the var directly inside the url:
$url= 'https://'.$this->m_host.'/Web?Query='.urlencode($this->m_keywords).'&Adult=%27Off%27&$top=50&$format=Atom';
2.) You defined three different vars with the same value:
$WebSearchURL = $url;
$request = $WebSearchURL;
Use $url only.
3.) base64_encode($accountKey . ":" . $accountKey) can be reduced to base64_encode(":" . $accountKey)
4.) Add Accept-Encoding: gzip to your header to reduce traffic and raise speed.
5.) Your problem should be this line:
'proxy' => 'tcp://127.0.0.1:8888',
Remove it or change it to the correct value.

C2DM implementation PHP code

I am creating the Android application where C2DM push notification is used. But i have a problem in creating the php code to use c2dm for sending messages. please guide me how to use the php code to send the messages. Actually there is a problem regarding this that how to get client auth token. I have seen the http://code.google.com/android/c2dm/index.html#server url but according to this i have created the android application and i got the registration id also and i also send to the user but how server uses this to send the application.
is there anything needed for the server from the android device to send the messages?.
To register your own server system and obtain the Authorise Tokens (this is what Cpt. Ohlund proposed):
function googleAuthenticate($username, $password, $source="Company-AppName-Version", $service="ac2dm") {
session_start();
if( isset($_SESSION['google_auth_id']) && $_SESSION['google_auth_id'] != null)
return $_SESSION['google_auth_id'];
// get an authorization token
$ch = curl_init();
if(!ch){
return false;
}
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/accounts/ClientLogin");
$post_fields = "accountType=" . urlencode('HOSTED_OR_GOOGLE')
. "&Email=" . urlencode($username)
. "&Passwd=" . urlencode($password)
. "&source=" . urlencode($source)
. "&service=" . urlencode($service);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// for debugging the request
//curl_setopt($ch, CURLINFO_HEADER_OUT, true); // for debugging the request
$response = curl_exec($ch);
//var_dump(curl_getinfo($ch)); //for debugging the request
//var_dump($response);
curl_close($ch);
if (strpos($response, '200 OK') === false) {
return false;
}
// find the auth code
preg_match("/(Auth=)([\w|-]+)/", $response, $matches);
if (!$matches[2]) {
return false;
}
$_SESSION['google_auth_id'] = $matches[2];
return $matches[2];
}
To send a message to a phone:
// $msgType: all messages with same type may be "collapsed": if multiple are sent,
// only the last will be received by phone.
function sendMessageToPhone($authCode, $deviceRegistrationId, $msgType, $messageText) {
$headers = array('Authorization: GoogleLogin auth=' . $authCode);
$data = array(
'registration_id' => $deviceRegistrationId,
'collapse_key' => $msgType,
'data.message' => $messageText //TODO Add more params with just simple data instead
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://android.apis.google.com/c2dm/send");
if ($headers)
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
I've created an example in my blog in working with Android C2DM. I use Zend Framework and a custom component that I wrote out. It should give you the basic information that you will need in order to handle your Android C2DM implementation in PHP.
Android C2DM PHP w/ Zend Framework: http://blog.digitalstruct.com/2010/11/21/android-c2dm-with-php-and-zend-framework/
Regards,
Mike
Check this out: http://www.toppa.com/2010/google-clientlogin-php-example/
Otherwise I will get back to you, as I will try C2DM later this week.
As C2DM has been officially deprecated (google c2dm)
I recommend using the new GCM API as described in the following link:
GCM Php implementation
I have tried using the php code that was accepted as the correct answer but it is not working.
I am getting the response http code as "0".
I found the same code in the following link
Need help from the experts out here.

Categories