I'm using Symfony with Buzz\Browser vendor, I need to send file to my Slack channel via POST. This's the Slack method that I should call: Slack file upload
This's my code:
public function uploadFile(array $channels, File $file, $initial_comment = '', $title = '') {
$channels = implode(',', $channels);
$headers['Content-Type'] = 'multipart/form-data';
$content = json_encode(array(
'channels' => $channels,
'file' => new FormUpload($file->getPathname()),
'filename' => $file->getFilename(),
'filetype' => $file->getExtension(),
'initial_comment' => $initial_comment,
'title' => $title
));
return $this->post('/files.upload', $headers, $content);
}
Post method:
public function post($endpoint, $headers = array(), $content = '') {
$headers['Authorization'] = sprintf('Bearer %s', $this->getToken());
return $this->browser->post($this->url . $endpoint, $headers, $content);
}
I receive the response error message: invalid_form_data
EDIT:
I find this solution: How to send file data as post parameter in BuzzBrowser post call
and works fine, but is there a way to send file via Buzz's post method?
Related
I want to submit contact form by custom function
The code below is getting the instance of form but when submitted. It submit the form but not the fields which I wanted.
$item = wpcf7_contact_form( $formId );
$result = $item->submit();
Here where I can pass the fields I define in admin panel like "textarea-123" & "email-234" ?
I did not get exact answer for what I look but I found the alternate solution.
function cf7Submit($formId , $args) {
$url = 'http://example.com/wp-json/contact-form-7/v1/contact-forms/'.$formId.'/feedback';
$response = wp_remote_post( $url, array(
'method' => 'POST',
'body' => $args
)
);
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>';
}
}
I can call this function like this:
cf7Submit(128, array(
'textarea-123' => 'test email',
'email-234' => 'asd#asd.com'));
#daraptoor has found a good solution, but as #davevsdave noticed in the comment, it does not work properly in CF7 5.6.
Error 415 is caused by added to API check for content type passed into a request header:
// part of create_feedback() from CF7's rest-api.php
if ( ! str_starts_with( $content_type, 'multipart/form-data' ) ) {
To figure it out, just add the expected content type into a request header:
$response = wp_remote_post( $url, array(
'method' => 'POST',
'headers' => array(
'Content-Type' => 'multipart/form-data'
),
'body' => $args
)
);
UPD
Faced with an issue, that wp_remote_post() send data in body and not in POST, so CF7 API does not get any fields. It is caused because the WP's function uses http_build_query() (read more here).
I have used cURL request as a workaround:
// Same user agent as in regular wp_remote_post().
$userAgent = 'WordPress/' . get_bloginfo('version') . '; ' . get_bloginfo('url');
// Note that Content-Type wrote in a bit different way.
$header = ['Content-Type: multipart/form-data'];
// Same array with fields to pass, not changed.
$body = ['foo' => 'bar'];
$curlOpts = [
// Send as POST
CURLOPT_POST => 1,
// Get a response data instead of true
CURLOPT_RETURNTRANSFER => 1,
// CF7 will reject your request as spam without it.
CURLOPT_USERAGENT => $userAgent,
CURLOPT_HTTPHEADER => $header,
CURLOPT_POSTFIELDS => $body,
];
$ch = curl_init($apiUrl); // Create a new cURL resource.
curl_setopt_array($ch, $curlOpts); // Set options.
$response = curl_exec($ch); // Grab response.
if (!$response) {
// Do something if an error occurred.
} else {
$response = json_decode($response);
// Do something with the response data.
}
// Close cURL resource, and free up system resources.
curl_close($ch);
Hope it saves someones time :)
You can add a piece of JS code, like:
$("form.wpcf7").submit()
How can I use wp_remote_post to send SMS from Twilio?
The code below work nice, but it need to be done with WordPress HTTP API using wp_remote_post
function send_twilio_text_msg($id, $token, $from, $to, $body)
{
$url = "https://api.twilio.com/2010-04-01/Accounts/".$id."/SMS/Messages";
$data = array (
'From' => $from,
'To' => $to,
'Body' => $body,
);
$post = http_build_query($data);
$x = curl_init($url );
curl_setopt($x, CURLOPT_POST, true);
curl_setopt($x, CURLOPT_RETURNTRANSFER, true);
curl_setopt($x, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($x, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($x, CURLOPT_USERPWD, "$id:$token");
curl_setopt($x, CURLOPT_POSTFIELDS, $post);
$y = curl_exec($x);
curl_close($x);
print_r($y);
}
To make a call to the Twilio API using wp_remote_post you need to do a few things:
Create the URL, as you did in your example
Collect the data you want to send (your From, To, and Body from your example)
Create an Authorization header out of your Account Sid and Auth Token. To do so, you need an array with one key, Authorization and the value made from base 64 encoding the Account Sid and Auth Token concatenated with a colon.
The $url is the first argument to wp_remote_post the second argument is an associative array with body and headers properties.
See the example below:
function send_twilio_text_msg($id, $token, $from, $to, $body)
{
$url = "https://api.twilio.com/2010-04-01/Accounts/".$id."/SMS/Messages";
$data = array(
'From' => $from,
'To' => $to,
'Body' => $body
);
$headers = array(
'Authorization' => 'Basic ' . base64_encode($id . ':' . $token)
);
$result = wp_remote_post($url, array(
'body' => $data,
'headers' => $headers
));
}
I've just integrated the marketing tool Klaviyo with our Wordpress/WooCommerce set up and I'm trying to push user meta data through a cURL API - but failing!
You can find out how the API works here: https://www.klaviyo.com/docs/http-api#people
I'm hoping to add an action so when the user profile saves, it hooks in my function sending the meta data through to Klaviyo.
Can anyone see what I've done wrong please - code below?
Thanks so much in advance.
Linz
<?php
// Hook into the action which saves the User Meta Data (written by LD)
add_action( 'personal_options_update', 'klaviyo_send' );
add_action( 'edit_user_profile_update', 'klaviyo_send' );
function klaviyo_send () {
// Get cURL resource
$curl = curl_init();
// Set some options
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://a.klaviyo.com/api/identify?data=eyJ0b2tlbiI6ICJoYXFYaXEiLCAicHJvcGVydGllcyI6IHsiJGVtYWlsIjogInRob21hcy5qZWZmZXJzb25AZXhhbXBsZS5jb20iLCAiJGxhc3RfbmFtZSI6ICJKZWZmZXJzb24iLCAiUGxhbiI6ICJUcmlhbCIsICJTaWduIFVwIERhdGUiOiAiMjAxMy0wMS0yNyAxMjoxNzowNiIsICIkZmlyc3RfbmFtZSI6ICJUaG9tYXMifX0=',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
'token' => 'haqXiq', //This is the public 'key' in Klaviyo
'$email' => $user_id->email, //This translates the wordpress field into the Klaviyo field
'twitter' => $user_id->twitter,
)
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
}
?>
Try sending data by this way .. change the posted data to url friendly ways like ?key=value&key=value&key=value
//extract data from the post
//set POST variables
$url = 'https://a.klaviyo.com/api/identify?data=eyJ0b2tlbiI6ICJoYXFYaXEiLCAicHJvcGVydGllcyI6IHsiJGVtYWlsIjogInRob21hcy5qZWZmZXJzb25AZXhhbXBsZS5jb20iLCAiJGxhc3RfbmFtZSI6ICJKZWZmZXJzb24iLCAiUGxhbiI6ICJUcmlhbCIsICJTaWduIFVwIERhdGUiOiAiMjAxMy0wMS0yNyAxMjoxNzowNiIsICIkZmlyc3RfbmFtZSI6ICJUaG9tYXMifX0=';
$fields = array(
'token' => 'haqXiq', //This is the public 'key' in Klaviyo
'$email' => $user_id->email, //This translates the wordpress field into the Klaviyo field
'twitter' => $user_id->twitter,
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
I read dozens of articles, the guidelines, I read everything but I do not understand anything. I'm going crazy. Are three days that I'm trying to post on my facebook fan page through the last 4 API 2.4 SDK.
1. I created the app on facebook but the permissions are almost impossible to enforce
2. I have created the appropriate PHP code with the various authentication codes
the result is always the same: NOTHING
Then the questions:
1. What do you need the app to publish on my fan page?
2. What permissions are needed?
3. If I do not have screenshots to be indicated in the permit to push them through whatever I do (I do the screen shot of the source code?).
4. as you get the access token to the fan page?
A desperate help.
$APP_ID = 'XXXXXXXXXXXXXXXXX'; //app id
$APP_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; //app secret
$TOKEN = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; //access token
$page_id = "XXXXXXXXXXXXXXXXXXXXX"; // facebook page id ottenuto da
$message = "Stiamo testando la pubblicazione delle inserzioni anche su Facebook";
$link = "http://qualcosa";
$name = "Me";
/*$fb = new Facebook\Facebook([
'app_id' => $APP_ID,
'app_secret' => $APP_SECRET,
'default_graph_version' => 'v2.4',
]);
$linkData = [
'link' => 'http://qualcosa/altro',
'message' => $message,
];
var_dump($linkData);
$helper = $fb->getPageTabHelper();
$accessToken = $helper->getAccessToken();
var_dump($accessToken);
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->post('/me/feed', $linkData,$TOKEN);//
} catch(Facebook\Exceptions\FacebookResponseException $e) {
$msg = 'Graph returned an error: ' . $e->getMessage();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
$msg = 'Facebook SDK returned an error: ' . $e->getMessage();
}
var_dump("MSG: ".$msg);
$graphNode = $response->getGraphNode();
var_dump("Graph: ".$graphNode);
$msg = 'Posted with id: ' . $graphNode['id'];
var_dump($msg);
$msg="Nulla";
// I tryed but nothing
try {
FacebookSession::setDefaultApplication($APP_ID, $APP_SECRET);
$session = new FacebookSession($TOKEN);
var_dump($session);
$page_post = (new FacebookRequest( $session, 'POST', '/'. $page_id .'/feed', array(
'access_token' => $TOKEN,
'name' => $name,
'link' => $link,
'picture' => '',
'caption' => 'Test da Cip!',
'message' => $message,
) ))->execute()->getGraphObject()->asArray();
} catch (Facebook\Exceptions\FacebookResponseException $e)
{$msg = 'Graph returned an error: ' . $e->getMessage();}
catch (Facebook\Exceptions\FacebookSDKException $e)
{$msg = 'Facebook SDK returned an error: ' . $e->getMessage();}
// return post_id, optional
var_dump( $page_post );
var_dump($msg);
echo "<br />Finito";
After many attempts I have solved the problem. In graph explorer serves select the App, then the page on publish, assign publishing rights and withdraw the access token created. In the bottom of the page then you can extend the time validity of the token and you will have to use the latter.
I am using a service that accepts URL in this format...
http://www.mydomain.com/zone1/code/verify/?data1=Apple&data1=Banana&data3=Orange&data4=Pear
I am trying to use wp_remote_post to submit it and receive a response....
$url = 'http://www.mydomain.com/zone1/code/verify/';
$fields = array();
$fields['data1'] = 'Apple';
$fields['data2'] = 'Banana';
$fields['data3'] = 'Orange';
$fields['data4'] = 'Pear';
$response = wp_remote_post( $url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => $fields,
'cookies' => array()
)
);
This isn't working and the response I am recieving back is that the fields are missing.
Can anyone see anything wrong with my approach and also is there an easy way to echo out exactly the URL it is sending?
This url:
http://www..../verify/?data1=Apple&data1=Banana&data3=Orange&data4=Pear
is in a GET format, not POST so you should check the API docs for that request, but it likely does not support the POST format so you will need to use the GET syntax, like so:
$url = 'http://www.mydomain.com/zone1/code/verify/';
$url .= '?data1=Apple';
$url .= '&data2=Banana';
$url .= '&data3=Orange';
$url .= '&data4=Pear';
$args = array(); //the default arguments should be ok unless the API needs something special like authentication headers
$response = wp_remote_get($url, $args);
I like to use the kint-debugger plugin to dig through output like this, using that you could call dd($response); and get a nicely formatted display of the response. Without that plugin, just add this afterwards:
print '<pre>';
print_r($repsonse);
die();
This should show everything in the response variable.