I am testing out using wp-api, I am very excited to use this by the way. Here is what I have done.
installed wp-api and verified that I can get from the website using cURL
Installed basic authentication, created an editor level account for this testing.
I have tried to update a post using cURL and Postman in chrome.
my headers:
-Content-Type: application/javascript
-data in a file
I am not sure if there are other headers that I am missing. Both cURL and postman handle username and password in basic authentication for me.
my JSON
{
"title":"Hello Updated World!",
"content_raw":"Howdy updated content.",
"date":"2013-04-01T14:00:00+10:00"
}
straight from the examples in wp-api docs
the error I keep getting is
[
{
"code": "json_missing_callback_param",
"message": "Missing parameter data"
}
]
Looking at the source code on github it looks like a required parameter is missing
according to the documentation title and content raw seem to be the only required fields. I would love to know what I am missing if you have any suggestion. Thanks.
You can also try this plugin for making use of Wordpress webservices and by using it you can also create your custom webservice too :
https://wordpress.org/plugins/json-api/
Here's the code I use to call a local WP-API with PHP/cURL:
$endpoint = 'http://localhost/my-site/wp-json/wp/posts';
$username = 'test-user';
$password = 'test-pass';
$data = array(
'title' => $post_title,
'content_raw' => $post_content,
'status' => 'publish',
);
$json_data = json_encode($data);
$ch = curl_init($endpoint);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json_data),
));
$result = json_decode(curl_exec($ch));
To update this post, I would change my data to:
$data = array(
'ID' => $post_id,
'title' => $new_title,
'content_raw' => $new_content,
);
ID is a required field when updating.
Related
Dear good people of Stack. I have a custom PHP web site and would like to ask for help in passing new user's name and emails to my GetResponse list. I currently have a Mailchimp integration, which works great, but would like to rewrite it for GetResponse (Please see the code below).
I've consulted this doc, but couldn't do it: https://apidocs.getresponse.com/v3/case-study/adding-contacts
Could someone please help me modify this to work with GetReponse please? I would be very thankful.
\Unirest\Request::auth('Arsen', 'MAILCHIMP_API_KEY');
$body = \Unirest\Request\Body::json([
'email_address' => $_POST['email'],
'merge_fields' => [
'LNAME' => $_POST['name']
],
'status' => 'subscribed'
]);
\Unirest\Request::post(
'MAILCHIMP_LINK' . '/lists/' . 'MAILCHIMP_API_LIST' . '/members',
[],
$body
);
Thank you in advance!
See code below, which works for me. I developed this to gather user's actual IP address (not shown in this example). The API URL is important: should end /contacts ($url below), but this is less than clear in Getresponse documentation. I'm not sure there is a 'status' field in Getresponse, so I have not included that (once added to contacts, the status will be subscribed).
<?php
//API url
$url = 'https://api.getresponse.com/v3/contacts';
// Collection object
// Change YYYYY to campaign ID, called campaign_token in sign-up html forms
$post = ['dayOfCycle' => 0,'email' => $_POST['email'],'name' => $_POST['name'], 'campaign' => ['campaignId' => 'YYYYY']];
// Initializes a new cURL session
$curl = curl_init($url);
// Set the CURLOPT_RETURNTRANSFER option to true
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Set the CURLOPT_POST option to true for POST request
curl_setopt($curl, CURLOPT_POST, true);
// Set the request data as JSON using json_encode function
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($post));
// Set custom headers for X-Auth-Token, needed for Getresponse API
// Change ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ to actual API key
curl_setopt($curl, CURLOPT_HTTPHEADER, [
'X-Auth-Token: api-key ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ',
'Content-Type: application/json'
]);
// Execute cURL request with all previous settings
ob_start();
curl_exec($curl);
// close the connection, release resources used
curl_close($curl);
ob_end_clean();
?>
I have been struggling with the youtube alot.
The problem is, i have made my own php curl script which should connect to the youtube api and send a livechat message to my current stream.
I am so close to finishing this issue but only this 1 last part stops me.
The script i currently use is:
$data = array("snippet" => ["type" => 'textMessageEvent', 'textMessageDetails' => ['messageText' => '<3']], 'livechatid' => '{{livechatid_here}}');
$data_string = json_encode($data);
$ch = curl_init('https://www.googleapis.com/youtube/v3/liveChat/messages?part=snippet&fields=authorDetails%2Ckind%2Csnippet&key={{Here is my key}}');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
'Authorization: Bearer {{access_key}} ')
);
$result = curl_exec($ch);
dd($result);
But im constantly getting the following error:
"code": 400,
"message": "snippet.live_chat_id is required"\n
So what i did was i changed 'livechatid' to:
liveChatId (as API tells me)
live_Chat_Id
livechatid
snippet.livechatid
snippet.liveChatId
snippet.live_chat_id
And none of them worked.
Does anybody know how i can fix this?
Ofcourse i have been deleting my keys and access_tokens from the code above.
I have also tried adding them to the header but i still get the same error again and again.
Does anybody know how i can solve this problem?
Put liveChatId inside the snippet field :
$data = array("snippet" => [
"type" => 'textMessageEvent',
'textMessageDetails' => ['messageText' => '<3'],
'liveChatId' => 'YOUR_LIVE_CHAT_ID'
]);
$data_string = json_encode($data);
I'm building my first Spotify application and right now I'm tackling the authorization process.
So far I have been successful in retrieving my State and Code from https://accounts.spotify.com/authorize
and now I'm sending a POST request via PHP CURL request to acquire my access token.
Spotify's instructions for this step
I keep getting the following JSON error response indicating that my grant_type is not valid and it offers me three valid options:
{"error":"unsupported_grant_type","error_description":"grant_type must be client_credentials, authorization_code or refresh_token"}bool(true)
If you look at my code below, I believe I have set the correct grant_type of "authorization_code" but I'm getting the error. I have highlighted with '******' the code snippet of what I believe to be the correct line of code.
Can anyone see what I'm doing incorrectly? Here's the code I'm using to send the request:
// Get access tokens
$ch = curl_init();
// Specify the HTTP headers to send.
//Authorization: Basic <base64 encoded client_id:client_secret>
$ClientIDSpotify = "[my spotify app id]";
$ClientSecretSpotify = "[my secret code]";
$authorization = base64_encode ( "{$ClientIDSpotify}:{$ClientSecretSpotify}" );
$http_headers = array(
"Authorization: Basic {$authorization}"
);
curl_setopt( $ch, CURLOPT_HTTPHEADER, $http_headers );
curl_setopt( $ch, CURLOPT_POST, true);
$spotify_url = "https://accounts.spotify.com/api/token";
curl_setopt( $ch, CURLOPT_URL, $spotify_url );
// *************************************************
// HERE'S WHERE I CORRECTLY SPECIFY THE GRANT TYPE
// *************************************************
$data['grant_type'] = "authorization_code";
$data['code'] = $authorizationCode;
$callbackURL = "[my callback URL]";
$data['redirect_uri'] = $callbackURL;
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$response_json = curl_exec( $ch );
curl_close( $ch );
}
Just as a note to the last comment about switching to http_build_query, I had to URLDECODE the data, in order for Spotify to recognize it. Try using this line instead.
curl_setopt($ch, CURLOPT_POSTFIELDS, urldecode(http_build_query($data)));
Seems to me like the POST body isn't being formatted correctly, everything else looks good.
My limited understanding of PHP tells me that your POST body looks like
{
"fields" : {
"code" : $authorizationCode,
"grant_type" : "authorization_code",
"redirect_uri" : "http://www.example.com/spotify/callback/index.php"
}
}
Of course, what you'd like to send is just
{
"code" : $authorizationCode,
"grant_type" : "authorization_code",
"redirect_uri" : "http://www.example.com/spotify/callback/index.php"
}
Therefore, try to set the $data object with
$data['grant_type'] = "authorization_code";
$data['code'] = $authorizationCode;
$data['redirect_uri'] = $callbackURL;
or even shorter
$data = array("grant_type" => "authorization_code", "code" => $authorizationCode, "redirect_uri" => $callbackURL);
Hope this helped!
OK, so I dug a little digging and found some code in the PHP CURL manual comments section. The problem with Spotify's documentation is it doesn't specify the format of the POST data to be sent. I assumed since Spotify was sending me JSON data that I should be sending my data in JSON format as well. So I was formatting the POST data as such:
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
After reading through some documentation I decided to try this instead:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
I got exactly the results I needed:
{"access_token":"[long access token]","token_type":"Bearer","expires_in":3600,"refresh_token":"[long refresh token]"}
Thank you, Michael, for attempting to assist!
We're updating our Mailchimp implementation from 1.3 to 3.0. We succesfully updated our code to subscribe someone to a list. Now we're trying to add an ecommerce order. In API v1.3 we did this with the function campaignEcommOrderAdd. I found the function to this with in v3.0: /ecommerce/stores/{store_id}/orders(website link).
But I can't get it to work. When posting to Mailchimp I get an 404 error, but I don't know what I'm doing wrong. Below is my code.
$apiKey = "xxx"; //xxx for privacy reasons
$json = json_encode(array(
'id' => $mailchimp_order['id'],
'customer' => array(
'id' => $mailchimp_order['email_id'],
),
'campaign_id' => $mailchimp_order['campaign_id'],
'currency_code' => "EUR",
'order_total' => $mailchimp_order['total'],
'tax_total' => $mailchimp_order['tax'],
'lines' => $mailchimp_order['items'],
));
$dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
$url = 'https://'.$dataCenter.'.api.mailchimp.com/3.0/ecommerce/stores/'.$mailchimp_order['store_id'].'/orders';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
This is the output of my $json var:
{
"id":"10000003",
"customer":{
"id":"a90f52f710"
},
"campaign_id":"641657",
"currency_code":"EUR",
"order_total":"56.90",
"tax_total":"47.02",
"lines":[
{
"id":"224",
"product_id":"4427",
"product_title":"Product name",
"product_variant_id":0,
"quantity":"1",
"price":"49.95"
}
]
}
And this is the error I get:
object(stdClass) {
type => 'http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/'
title => 'Resource Not Found'
status => (int) 404
detail => 'The requested resource could not be found.'
instance => ''
}
Without knowing more I would try a few things here. One (you may have already tried this, but check the output of $url) to make sure that all that is getting set correctly. Secondly I would make sure that the store instance you are posting this order to is reachable/exists by making a GET request to, what would be:
$url = 'https://'.$dataCenter.'.api.mailchimp.com/3.0/ecommerce/stores/'.$mailchimp_order['store_id']'
Lastly I would verify that both the campaign and product instances associated with the order are reachable using:
GET https://{dc}.api.mailchimp.com/3.0/campaigns/641657
GET https://{dc}.api.mailchimp.com/3.0/ecommerce/stores/{store_id}/products/4427
Also if you are doing a lot of updating to 3.0 for your app it might be useful to implement a library that abstracts out a lot of this code I use this one:
https://github.com/Jhut89/Mailchimp-API-3.0-PHP
My reputation score wont let me post more links to those endpoints but they should be easily found in the MailChimp documentation. Hope that helps out.
I have written an API that I want to accept form values for the HTTP header POST.
Using PHP, I can make use of the API link using the following code:
$data = array(
"authorid" => $_POST['author'],
"filmid" => $_POST['film'],
"content" => "".$_POST['content']."",
"score" => $_POST['score']
);
$post = json_encode($data);
$ch = curl_init('http://www.website.co.uk//v1/review/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array(
'Content-Type: application/json',
'Content-Length: ' . strlen($post))
);
$result = curl_exec($ch);
echo $result;
I am however using the API in a QT application.
What is the best way to store the form values and when they are submitted, send the HTTP header request POST along with the array of data to the link I gave above.
Got no idea how to achieve this!
Thanks,
Luke.
There are tons of questions like this here, just browse through them and find what is closest to your situation. This shows how to do a POST request. Here is another one with JSON serializiation, just google "qt post qnetworkrequest json" and there should be tons of answers.