I need your help with Google notifications sending which works correctly but with empty messages, title, message etc. are missing...
Any ideas ?
Here is picture how it looks like:
define( 'API_ACCESS_KEY', 'AIzaSyBBh4ddPa96rQQNxqiq_qQj7sq1JdsNQUQ' );
//$registrationIds = array( $_GET['id'] );
$user_device_key = 'eVuuhJNB3vs:APA91bGyf2iAcDEHMVe8MmYzUmNAVl08tfP4wHQFi0sIMhtlZ9PwljdEfZ8JhtfJ_O0rhXTvdJEiVbeRJaUfWn2qvHG6Gw7OjV2jSCmkUd1HK93dyocyC26_48xb0srxa5imUpqXSxMk';
$payload_info = create_payload_json("I know how to send push notifications!");
// API access key from Google API's Console
define('API_ACCESS_KEY', 'AIzaSyAjcvboyovxihsZBtrs2FmVkFbLs-bNk1k');
// prep the bundle
$msg = array
(
'message' => json_decode($payload_info)->aps->alert,
'title' => 'This is a title. title',
'subtitle' => 'This is a subtitle. subtitle',
'tickerText' => 'Ticker text here...Ticker text here...',
'vibrate' => 1,
'sound' => 1,
'largeIcon' => 'large_icon',
'smallIcon' => 'small_icon'
);
$fields = array
(
'registration_ids' => array($user_device_key),
'data' => $msg
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, false );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
echo $fields;
$result = curl_exec($ch);
curl_close($ch);
return $result > 0;
function create_payload_json($message) {
//Badge icon to show at users ios app icon after receiving notification
$badge = "0";
$sound = 'default';
$payload = array();
$payload['aps'] = array('alert' => $message, 'badge' => intval($badge),'sound' => $sound);
return json_encode($payload);
}
Related
I am trying to build a plugin that sends webhooks to an external site from client sites so I can keep a record of everything that happens from when a user signs in, to when someone installs a new plugin or updates or adds new pages etc.
The problem is I am receiving NULL values through the $api array, and can't seem to figure it out.
This is my last attempt and making this work:
function send_webhook_on_plugin_install( $install_result, $package, $api ) {
$webhook_url = 'https://example.com';
$installed_plugins = get_plugins();
$installed_plugins = array_keys( $installed_plugins );
$new_plugin = false;
$new_plugin_name = '';
$new_plugin_version = '';
foreach ( $installed_plugins as $installed_plugin ) {
if ( ! in_array( $installed_plugin, $package ) ) {
$new_plugin = $installed_plugin;
break;
}
}
if ( $new_plugin ) {
$new_plugin_data = get_plugins( '/' . $new_plugin );
$new_plugin_name = $new_plugin_data[ $new_plugin ]['Name'];
$new_plugin_version = $new_plugin_data[ $new_plugin ]['Version'];
}
$body = array(
'plugin_name' => $new_plugin_name,
'plugin_version' => $new_plugin_version
);
$response = wp_remote_post( $webhook_url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array( 'Content-Type' => 'application/json' ),
'body' => wp_json_encode( $body ),
'cookies' => array()
) );
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
// Log the error
error_log( "Webhook failed: $error_message" );
}
}
add_action( 'upgrader_post_install', 'send_webhook_on_plugin_install', 10, 3 );
The JSON that is being received is:
{
"plugin_name": null,
"plugin_version": null
}
The Warnings I'm getting are this:
PHP Warning: Undefined array key "advanced-custom-fields-pro/acf.php" in C:\xampp\htdocs\site\wp-content\plugins\webhook-sender\plugin-update.php on line 25
PHP Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\site\wp-content\plugins\webhook-sender\plugin-update.php on line 25
Previous Versions of the code that also failed:
function send_webhook_on_plugin_install( $install_result, $package, $api ) {
$webhook_url = 'https://example.com';
$body = array(
'plugin_name' => $api['name'],
'plugin_version' => $api['version']
);
$response = wp_remote_post( $webhook_url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array( 'Content-Type' => 'application/json' ),
'body' => wp_json_encode( $body ),
'cookies' => array()
) );
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
// Log the error
error_log( "Webhook failed: $error_message" );
}
}
add_action( 'upgrader_post_install', 'send_webhook_on_plugin_install', 10, 3 );
I thought by accessing $api array directly might work, but still getting NULL values on the return.
and...
function send_webhook_on_plugin_install( $install_result, $package, $api ) {
$webhook_url = 'https://example.com';
$body = array(
'plugin_name' => $api->name,
'plugin_version' => $api->version
);
$response = wp_remote_post( $webhook_url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array( 'Content-Type' => 'application/json' ),
'body' => wp_json_encode( $body ),
'cookies' => array()
) );
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
// Log the error
error_log( "Webhook failed: $error_message" );
}
}
add_action( 'upgrader_post_install', 'send_webhook_on_plugin_install', 10, 3 );
I am posting a file to dspace through dspace api, I am doing this with an action in php. With postman I send a form-data with the file, filename, bitstream id and token.
I am getting the temp file path with $_FILES and sending it by postfields curl option, but the file uploads empty, or with weird data, without its content.
public function actionSubirBitstream()
{
if (Yii::$app->request->isPost) {
$body = $_POST;
$prefijo = '/rest/items/';
$host = ConfiguracionDspace::find()->where("clave='host'")->one()->valor;
$puerto = ConfiguracionDspace::find()->where("clave='puerto'")->one()->valor;
$token = $body['token'];
$id = $body['id'];
$final = '/bitstreams';
$name = $body['name'];//nombre del archivo sin espacios
$params = "?name=$name";
$url = $host . ':' . $puerto . $prefijo . $id . $final . $params;
$file = $_FILES['file']['tmp_name'];
//$path = $body['path'];
//$file = new CURLFILE("$path");
$headers = array("Content-Type: application/json", 'Accept: application/json', "rest-dspace-token: " . $token);
$curl = curl_init($url);
$options = array(
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => array('file'=> $file,'name' => $name),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers
);
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
}
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => array('photo'=> new CURLFILE('/C:/Users/pfile3.jpeg'),'name' => $name),
this is the example of uploading a file with form key as photo and another key name
in your screen shot you have id and token in form data but in code its not inside POSTFIELDS
in postman you can generate equalent code of request in any language , try generating the PHP equalent code and see if it works:
To do this just click code link under the request url after saving the request
I already post the file by the $_FILE variable, But what I needed to do was to use CURLFILE to create a new file, and give it the temp path of the file in the server
$file = $_FILES['file']['tmp_name'];
and this in the postfields
CURLOPT_POSTFIELDS => array('file'=> new CURLFile("$file"),'name' => $name),
Thanks for the help friends
Here the code:
public function actionSubirBitstream()
{
if (Yii::$app->request->isPost) {
$body = $_POST;
$prefijo = '/rest/items/';
$host = ConfiguracionDspace::find()->where("clave='host'")->one()->valor;
$puerto = ConfiguracionDspace::find()->where("clave='puerto'")->one()->valor;
$token = $body['token'];
$id = $body['id'];
$final = '/bitstreams';
$name = $body['name'];//nombre del archivo sin espacios
$params = "?name=$name";
$url = $host . ':' . $puerto . $prefijo . $id . $final . $params;
$file = $_FILES['file']['tmp_name'];
//$path = $body['path'];
//$file = new CURLFILE("$path");
$headers = array("Content-Type: application/json", 'Accept: application/json', "rest-dspace-token: " . $token);
$curl = curl_init($url);
$options = array(
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => array('file'=> new CURLFile("$file"),'name' => $name),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers
);
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
}
The posted files with the rigth size(finally)
The form data I send by Postman, no need to use the field path
With the help of #Tanaike(see here), I can successfully upload files to GoogleDrive by using php-curl, here is my code by using php-curl:
function uploadByCurl($uploadFilePath, $accessToken){
$ch = curl_init();
$boundary = md5(mt_rand() . microtime());
//MetaData
$params = json_encode([
'name' => basename($uploadFilePath),
'description' => 'This is a test',
]);
$fileContent = file_get_contents($uploadFilePath);
$dataToUpload = "--{$boundary}\r\n";
$dataToUpload .= "Content-Type: application/json\r\n\r\n";
$dataToUpload .= "{$params}\r\n";
$dataToUpload .= "--{$boundary}\r\n";
$dataToUpload .= "Content-Transfer-Encoding: base64\r\n\r\n";
$dataToUpload .= base64_encode($fileContent) . "\r\n";
$dataToUpload .= "--{$boundary}--";
$options = [
CURLOPT_URL => 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart',
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $dataToUpload,
CURLOPT_HTTPHEADER => [
'Authorization:Bearer ' . $accessToken,
'Content-Type: multipart/related; boundary=' . $boundary,
],
//In case you're in Windows, sometimes will throw error if not set SSL verification to false
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 0,
];
//In case you need a proxy
//$options[CURLOPT_PROXY] = 'http://127.0.0.1:1087';
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
return $result;
}
$uploadFilePath = '<YOU-FILE-ABS-PATH>';
$accessToken = '<YOU-ACCESS-TOKEN>';
$ret = uploadByCurl($uploadFilePath, $accessToken);
var_dump($ret);
Response json:
{
"kind": "drive#file",
"id": "1lkuCTeMooRmde8uzNa7COUTTCLAk_jdq",
"name": "timg (12).jpeg",
"mimeType": "image/jpeg"
}
But when I'm trying to use Guzzle6(An curl client written by PHP) to do the same thing, the file(image file) can successfully upload but its name is "Untitled" and I can't preview the image(see the screenshot below):
Here is my code snippet by using Guzzle:
function uploadByGuzzle($uploadFilePath, $accessToken){
$boundary = md5(mt_rand() . microtime());
//MetaData
$params = json_encode([
'name' => basename($uploadFilePath),
'description' => 'This is a test',
]);
$fileContent = file_get_contents($uploadFilePath);
$dataToUpload = "--{$boundary}\r\n";
$dataToUpload .= "Content-Type: application/json\r\n\r\n";
$dataToUpload .= "{$params}\r\n";
$dataToUpload .= "--{$boundary}\r\n";
$dataToUpload .= "Content-Transfer-Encoding: base64\r\n\r\n";
$dataToUpload .= base64_encode($fileContent) . "\r\n";
$dataToUpload .= "--{$boundary}--";
$GuzzleConfig = [
'base_uri' => 'https://www.googleapis.com/upload/drive/v3/files/',
'timeout' => 30.0,
];
//In case you need a proxy
$GuzzleConfig['proxy'] = 'http://127.0.0.1:1087';
//GuzzleHttp
$client = new Client($GuzzleConfig);
$uri = '?uploadType=multipart';
$response = $client->request('POST', $uri, [
'verify' => false,
'headers' => [
'Authorization' => 'Bearer ' . $accessToken,
'Content-Type' => 'Content-Type: multipart/related; boundary=' . $boundary,
],
'body' => $dataToUpload,
]);
$string = $response->getBody()->getContents();
return $string;
}
$uploadFilePath = '<YOU-FILE-ABS-PATH>';
$accessToken = '<YOU-ACCESS-TOKEN>';
$ret = uploadByGuzzle($uploadFilePath, $accessToken);
var_dump($ret);
I think that the request body is correct. In your script, Content-Type is not correct. In this case, I think that body is sent as application/octet-stream. By this, the file of Untitled is created. And I think that it is the text data of the request body.
So how about this modification?
From:
'Content-Type' => 'Content-Type: multipart/related; boundary=' . $boundary,
To:
'Content-Type' => 'multipart/related; boundary=' . $boundary,
I am trying to send a confirmation email once the user has used the form I am creating via acf.
Below is the code I am using in a plugin, but somehow the wp_email is not sending an email. Not receiving it, nor did I receive an error.
function my_pre_save_post( $post_id ) {
// check if this is to be a new post
if( $post_id != 'new_post' ) {
return $post_id;
}
// Create a new post
$post = array(
'id' => $post_id,
'post_status' => 'publish',
'post_title' => $_POST['acf']['_post_title'],
'email' => $_POST['acf']['field_5d49dcb49a31f'],
'bedrag' => $_POST['acf']['field_5d49dd749a321'],
'periodiek' => $_POST['acf']['field_5d49de569a322'],
);
// // insert the post
$post_id = wp_insert_post( $post );
add_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );
$name = get_field('post_title', $post_id);
$email = get_field('email', $post_id);
$body_text = get_field('email_tekst', 'option');
$to = $name . ' <' . $email . '>' . "\r\n";
$headers = array('Content-Type: text/html; charset=UTF-8', 'From: Some name <info#somedomain.com> <noreply#'.$_SERVER['HTTP_HOST'].'>');
$subject = 'Bedankt voor uw donatie: ' . get_field('bedrag', $post_id) . ' ' . get_field('periodiek', $post_id);
$body = $body_text;
wp_mail($to, $subject, $body, $headers );
remove_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );
// return the new ID
return $post_id;
}
add_filter('acf/pre_save_post' , 'my_pre_save_post');
Save the form works, as I see data in the backend.
But I am just not receiving the email.
To make sure that emails are send, I am using a plugin (wp mail smtp).
Do I miss anything?
Ok, I know what was going wrong.
I didn’t used the correct priority.
Now using the following code:
function wpdocs_set_html_mail_content_type() {
return 'text/html';
}
add_action('acf/save_post' , 'my_save_post', 15);
function my_save_post($post_id) {
if( get_post_type($post_id) !== 'donations' ) {
return;
}
add_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );
$name = get_field('post_title', $post_id);
$email = get_field('email', $post_id);
$body_text = get_field('email_tekst', 'option');
$to = $email;
$headers = array('From: some name <some email> <noreply#'.$_SERVER['HTTP_HOST'].'>');
$subject = 'Bedankt voor uw donatie: ' . get_field('bedrag', $post_id) . ' ' . get_field('periodiek', $post_id);
$message = $body_text;
wp_mail($to, $subject, $message, $headers );
remove_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );
}
The priority is now 15, so runs after the save was done.
How to use WordPress REST API to post article? I can edit post using the following PHP code, i'm using the Basic Authentication.
require( dirname(__FILE__) . '/wp-load.php' );
$headers = array (
'Authorization' => 'Basic ' . base64_encode( 'username' . ':' . 'password' ),
);
// Edit post
$url = rest_url( 'wp/v2/posts/1' );
$data = array(
'title' => 'Test API Edit'
);
$response = wp_remote_post( $url, array (
'method' => 'POST',
'headers' => $headers,
'body' => $data
) );
print_r($response);
But I can not post new article
<?php
require( dirname(__FILE__) . '/wp-load.php' );
$headers = array (
'Authorization' => 'Basic ' . base64_encode( 'username' . ':' . 'password' ),
);
// post new article
$url = rest_url( 'wp/v2/create_post/' );
$data = array(
'title' => 'Post from API',
'content' => 'test contents'
);
$response = wp_remote_post( $url, array (
'method' => 'POST',
'headers' => $headers,
'body' => $data
) );
print_r($response);
The return is always No route was found matching the URL and request method
Any suggestions?
It looks like you are using the wrong endpoint for POSTing to the REST API. As mentioned here the endpoint for creating new posts is:
/wp/v2/posts
Hope this solves your problem!