WordPress REST API Basic Authentication - php

I am working on a project that requires some integration between different WordPress instances and I am in the process of creating a WordPress plugin that will provide that functionality through the REST API.
I have enabled the WP-API plugin and the Basic Authentication plugin and am able to make requests that do not require authentication but when I make a request that does require authentication, such as adding a new page, I am met with 401 - Sorry, you are not allowed to create new posts.
I realize basic authentication is not suitable for production needs but would like to get it working properly for development and have been spinning my wheels on this seemingly small problem. I am perfectly able to make these requests using Postman, so there is something wrong with my implementation. Here is the code in question:
function add_new_page($post) {
// Credentials for basic authentication.
$username = 'user';
$password = 'password';
// Request headers.
$headers = array(
'Authorization' => 'Basic ' . base64_encode( $username . ':' . $password ),
'Content-Type' => 'application/json'
);
// Request URL.
$url = "http://localhost/wp-json/wp/v2/pages";
// Request body.
$body = array(
'slug' => $post->post_name,
'status' => $post->post_status,
'type' => $post->post_type,
'title' => $post->post_title,
'content' => $post->post_content,
'excerpt' => $post->post_excerpt,
);
$body_json = json_encode($body);
// Request arguments.
$args = array(
'method' => 'POST',
'blocking' => true,
'headers' => $headers,
'cookies' => array(),
'body' => $body_json,
);
// Fire request.
$response = wp_remote_request($url, $args);
// Handle response.
if (is_wp_error($response)) {
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
} else {
$response_body = json_decode(wp_remote_retrieve_body($response));
// Display response body.
echo '<pre>';
print_r($response_body);
echo '</pre>';
}
// Exit so we can read the response.
exit();
}
I would be really appreciative of any insights somebody out there could provide.

Related

Slack API Interactive Messages, receiving Button click

I work at an MSP and I'm trying to integrate our ticketing system (Autotask) with Slack. So far, I have set up an HTTP POST request to some PHP code when a new ticket is created, which posts a chat message in a certain channel ("New Ticket Created! [Ticket Title] - [Ticket Description]" etc.) using Incoming Webhooks. Below is the important bits of that code:
<?php
require_once __DIR__ . '/src/autoload.php';
//Gets ticket number from HTTP POST
$ticketNum = $_POST['subject'];
//Generated at api.slack.com/apps > Incoming webhooks (for the channel I'm posting in)
$responseURL = 'https://hooks.slack.com/services/XXXXXXXXXXXX';
class Response {
public $response_type = "";
public $text = "";
public $attachments = array();
}
//*****
//QUERYING TICKETING SYSTEM API FOR TICKET INFORMATION
//THIS CODE WORKS, OMITTED FOR EASIER READING
//*****
$r = new Response();
$r->response_type = "in_channel";
$r->text = "New Ticket Created: \n*".$ticketName."* (".$ticketNum.") \n".$ticketDescription;
$r->attachments = array(
0 => array('callback_id' => 'newTicketAction', 'text' => 'Select an action:',
'color' => '95baa9', 'actions' => array(
0 => array('name' => 'newTicketAction', 'text' => 'Accept', 'type' => 'button',
'value' => 'accept', 'style' => 'primary'),
1 => array('name' => 'newTicketAction', 'text' => 'View', 'type' => 'button',
'value' => 'view')
)
)
);
header('Content-Type: application/json');
//Using CURL
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $responseURL,
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => json_encode($r)
));
$resp = curl_exec($curl);
var_dump($resp);
curl_close($curl);
?>
This works and posts a message in the correct channel that looks like this:
The problem I'm having is with responding to those button clicks. I have my Request URL set up, pointing to another PHP script. My understanding is that the button click sends another HTTP POST request to this page with a JSON object, which has a payload item. My hunch is I'm accessing this incorrectly. My code is below:
<?php
require_once __DIR__ . '/src/autoload.php';
//get information from HTTP POST, sent at button click
$payload = $_POST['payload'];
$data = json_decode($payload,true);
$responseURL = $data -> response_url;
class Response {
public $response_type = "";
public $text = "";
public $attachments = array();
}
$r = new Response();
$r->response_type = "in_channel";
$r->text = "Ticket Accepted";
header('Content-Type: application/json');
//Using CURL
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $responseURL,
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => json_encode($r)
));
$resp = curl_exec($curl);
var_dump($resp);
curl_close($curl);
?>
You can see right now I'm just trying a simple response message for testing purposes, but when I click the 'Accept' button I get the following response:
I've scoured the web and cannot find a solid tutorial on Interactive Messages which includes "receiving" button clicks. Any help would be greatly appreciated.
PHP syntax was wrong for accessing array element.

How to Integrate 3rd party API in Wordpress

I'm using wordpress and i want to integrate an SMS API into my wordpress site. Can anyone help in knowing where (in which file) to write the code for integration and also the code to integrate SMS API.
My SMS API Url is :
http://www.elitbuzzsms.com/app/smsapi/index.php?key=KEY&campaign=****&routeid=**&type=text&contacts=< NUMBER >&senderid=SMSMSG&msg=< Message Content >
I want to integrate above API in my wordpress theme so that i can send sms based on mobile number and add required message.
In wordpress you can use wp_remote_get and wp_remote_post
get request example
$url = 'http://www.elitbuzzsms.com/app/smsapi/index.php?key=KEY&campaign=****&routeid=**&type=text&contacts=< NUMBER >&senderid=SMSMSG&msg=< Message Content >';
$response = wp_remote_get( $url );
if( is_array($response) ) {
$header = $response['headers']; // array of http header lines
$body = $response['body']; // use the content
}
post request example
$response = wp_remote_post( $url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => array( 'username' => 'bob', 'password' => '1234xyz' ),
'cookies' => array()
)
);
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
} else {
echo 'Response:<pre>';
print_r( $response );
echo '</pre>';
}

How to set request headers in WordPress Rest API calls

Hi am new to WP development, I would like to add request headers to WordPress Rest API calls but don't know how, can anyone help me in this?
I tried following code but no luck
$args = array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( Fk-Affiliate-Id . ':' . YOUR_PASSWORD )
)
);
$api_url = 'https://affiliate.com/api/';
global $affiliate;
$response = wp_remote_request( add_query_arg( array(
'Affiliate-Id' => $affiliate['aff-id'],
'Affiliate-Token' => $affiliate['aff-token']
), $api_url ) , array( 'timeout' => 10));
You can send the headers you need by including those in request options - second argument of wp_remote_request function($args in my example)
$args = [
'method' => 'GET',
'timeout' => 10,
'headers' => array() //add headers here
];
wp_remote_request('http://test.com', $args);

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,
);

Get Twitter Following Count

Im creating a widget for a Wordpress site and i am trying to get the twitter following count, I can get the followers count which is taken from http://www.wpbeginner.com/wp-tutorials/displaying-the-total-number-of-twitter-followers-as-text-on-wordpress/. Any help would be great.
thanks Pierce
Current code in functions.php:
// Twitter
function getTwitterFollowers($screenName = 'hellowWorld')
{
// some variables
$consumerKey = 'hidden';
$consumerSecret = 'hidden';
$token = get_option('cfTwitterToken');
// get follower count from cache
$numberOfFollowers = get_transient('cfTwitterFollowers');
// cache version does not exist or expired
if (false === $numberOfFollowers) {
// getting new auth bearer only if we don't have one
if(!$token) {
// preparing credentials
$credentials = $consumerKey . ':' . $consumerSecret;
$toSend = base64_encode($credentials);
// http post arguments
$args = array(
'method' => 'POST',
'httpversion' => '1.1',
'blocking' => true,
'headers' => array(
'Authorization' => 'Basic ' . $toSend,
'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8'
),
'body' => array( 'grant_type' => 'client_credentials' )
);
add_filter('https_ssl_verify', '__return_false');
$response = wp_remote_post('https://api.twitter.com/oauth2/token', $args);
$keys = json_decode(wp_remote_retrieve_body($response));
if($keys) {
// saving token to wp_options table
update_option('cfTwitterToken', $keys->access_token);
$token = $keys->access_token;
}
}
// we have bearer token wether we obtained it from API or from options
$args = array(
'httpversion' => '1.1',
'blocking' => true,
'headers' => array(
'Authorization' => "Bearer $token"
)
);
add_filter('https_ssl_verify', '__return_false');
$api_url = "https://api.twitter.com/1.1/users/show.json?screen_name=$screenName";
$response = wp_remote_get($api_url, $args);
if (!is_wp_error($response)) {
$followers = json_decode(wp_remote_retrieve_body($response));
$numberOfFollowers = $followers->followers_count;
} else {
// get old value and break
$numberOfFollowers = get_option('cfNumberOfFollowers');
// uncomment below to debug
//die($response->get_error_message());
}
// cache for an hour
set_transient('cfTwitterFollowers', $numberOfFollowers, 1*60*60);
update_option('cfNumberOfFollowers', $numberOfFollowers);
}
return $numberOfFollowers;
}
It was pretty simple if I just read the documentation anyway...
Instead of followers_count i replaced it with friends_count as outlined in the API 1.1 documentation. :)

Categories