How to convert this cURL to wp_remote_get?

I want to convert curl to wp_remote_get.

    $url = 'https://accounts.google.com/o/oauth2/token';

    $curl_post = 'client_id=' . $client_id . 'redirect_uri=' . $redirect_uri . 'client_secret=' . $client_secret . 'code=' . $code . 'grant_type=authorization_code';
    $ch        = curl_init();
    curl_setopt( $ch, CURLOPT_URL, $url );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt( $ch, CURLOPT_POST, 1 );
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
    curl_setopt( $ch, CURLOPT_POSTFIELDS, $curl_post );

    $data = json_decode( curl_exec( $ch ), true );

    $http_code = curl_getinfo( $ch, CURLINFO_HTTP_CODE );

Topic curl http-api plugin-development Wordpress

Category Web


The curl is sending a POST request, to convert this you'll want to use wp_remote_post(). As described in the documentation, the request arguments are the same as WP_Http::request(), so let's look there how we can replicate your current version.

  • curl_setopt( $ch, CURLOPT_URL, $url ); just sets the URL. Already doing this with wp_remote_post()
  • curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); tells that we want the result. wp_remote_post() is returning that by default.
  • curl_setopt( $ch, CURLOPT_POST, 1 ); makes sure to send a POST request. wp_remote_post() does that by default.
  • curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false ); now this is an interesting one. Tells curl not to verify the https certificate. The corresponding argument that we need is sslverify.
  • curl_setopt( $ch, CURLOPT_POSTFIELDS, $curl_post ); specifies the fields to be posted. The corresponding argument that we need is body.

With this in mind, the result could look something like

$url = 'https://accounts.google.com/o/oauth2/token';
$curl_post = 'client_id=' . $client_id . '&redirect_uri=' . $redirect_uri . '&client_secret=' . $client_secret . '&code=' . $code . '&grant_type=authorization_code';

$args = [
    'sslverify' => false,
    'body' => $curl_post,
];

$result = wp_remote_post($url, $args);

This should give you enough to play around with. It might be more readable to send the data as an array:

$curl_post = [
    'client_id' => $client_id,
    'redirect_uri' => $redirect_uri,
    // ..
];

But that is up to you.

Check what exactly $result is. You might need to call json_decode() on its body.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.