google url shortener api with wp_remote_post - php

I try to make google url shortener with wp_remote_post()
but I got error result,
I know how to use CURL, but CURL not allowed in WordPress!
This resource for API with WordPress:
http://codex.wordpress.org/Function_Reference/wp_remote_post
http://codex.wordpress.org/Function_Reference/wp_remote_retrieve_body
http://codex.wordpress.org/HTTP_API#Other_Arguments
http://codex.wordpress.org/Function_Reference/wp_remote_post#Related
This google url shortener API docs:
https://developers.google.com/url-shortener/v1/getting_started#shorten
This is my code:
function google_url_shrt{
$url = 'http://example-long-url.com/example-long-url'; // long url to short it
$args = array(
"headers" => array( "Content-type:application/json" ),
"body" => array( "longUrl" => $url )
);
$short = wp_remote_post("https://www.googleapis.com/urlshortener/v1/url", $args);
$retrieve = wp_remote_retrieve_body( $short );
$response = json_decode($retrieve, true);
echo '<pre>';
print_r($response);
echo '</pre>';
}

The WordPress API requires that the headers array contain an element content-type if you want to change the content type of a POST request.
Also, it looks like the body of your HTTP request is being passed as a PHP array, not as a JSON string as the Google Shortener API requires.
Wrap the array definition for body in a json_encode statement, and make the headers field a sub-array, and give it a shot:
$args = array(
'headers' => array('content-type' => 'application/json'),
'body' => json_encode(array('longUrl' => $url)),
);
Alternative, you could just write the JSON format yourself as it is fairly simple:
$args = array(
'headers' => array('content-type' => 'application/json'),
'body' => '{"longUrl":"' . $url . '"}',
);

Related

Bing Search API in PHP - missing webPages property in json response

I am trying to get search results as per the api documentation
Here is what I wrote in PHP
require_once 'HTTP/Request2.php';
$api_key = 'my_bing_search_api_key';
$url_encoded_keyword = urlencode('animation concepts and tutorials');
$request = new \Http_Request2('https://api.cognitive.microsoft.com/bing/v5.0/search');
$headers = [
'Ocp-Apim-Subscription-Key' => $api_key
];
$request->setHeader($headers);
$url = $request->getUrl();
$parameters = [
'q' => $url_encoded_keyword,
'count' => '10',
'offset' => '0',
'safesearch' => 'Strict',
);
$url->setQueryVariables($parameters);
$request->setMethod(\HTTP_Request2::METHOD_GET);
$request->setBody("{body}");
$search_result = null;
try {
$response = $request->send();
$search_results = json_decode($response->getBody(), true);
return $search_results;
} catch (HttpException $ex) {
return [];
}
I am getting response but it is not having webPages property. It has _type, rankingResponse, relatedSearches and videos properties only.
I tested the same request in the api console. There I am getting the webPages property in the json response.
Any ideas what could have been the reason why I am not getting the webPages in PHP but works on microsoft's api tester site?
From the code snippet, you are passing the keyword to Bing web search API after encoding it.
$url_encoded_keyword = urlencode('animation concepts and tutorials');
$parameters = [
'q' => $url_encoded_keyword,
'count' => '10',
'offset' => '0',
'safesearch' => 'Strict',
);
Try without encoding the keyword. From their API testing console, HTTP request for the same keyword would appear as
https://api.cognitive.microsoft.com/bing/v5.0/search?q=animation
concepts and tutorials&count=10&offset=0&mkt=en-us&safesearch=Moderate

WordPress notification rest API code

Like WordPress give us rest API for comments, posts etc. I want to get notification API code.
developer.wordpress.com gives the documentation for how to use notification API.
https://developer.wordpress.com/docs/api/1/get/notifications/$note_ID/.
To use this API, I need WordPress rest API notification code.
How can I get that code.
WordPress rest API code doesn't have notification code.
https://wordpress.org/plugins/rest-api/
Please help me.
You can use following code to get notification id using rest api.
Note : assume id is 1801481297
<?php
$options = array (
'http' =>
array (
'ignore_errors' => true,
'header' =>
array (
0 => 'authorization: Bearer YOUR_API_TOKEN',
),
),
);
$context = stream_context_create( $options );
$response = file_get_contents(
'https://public-api.wordpress.com/rest/v1/notifications/1801481297',
false,
$context
);
$response = json_decode( $response );
?>

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.

wp_remote_get( $url, $args ) not working?

I'm trying to request data from the virgin giving api to display my fundraising information on my blog. I'm a complete novice and have been unable to workout how such a task would be completed after reading and trying out everything I can find on the topic. This is the code I have been using in a .php file within a wordpress installation on cloud9 (I have removed the search and api key). I have also tried the code on a page on my live blog which is hosted with Bluehost. I'm not sure if I'm creating the page in the correct location or if the below code should be wrapped in some sort of function. Any help that you can provide would be much appreciated.
$url = "https://api.virginmoneygiving.com/fundraisers/v1/";
$args = array(
'headers' => array( "Content-type" => "application/json" ),
'httpversion' => 1.1,
);
$response = wp_remote_get( $url, $args );
$body = wp_remote_retrieve_body( $response );
$response_code = wp_remote_retrieve_response_code( $response );
print_r( $response_code );
echo $response;
'httpversion' takes a string...
'httpversion' => '1.1',
Read more in the source.

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

Categories