Simple PHP FireBase (FCM) script showing how to send an Android push notification . Be sure to replace the $apikey with a proper one from the Google API's Console page.
<?php
#API access key from Google API's Console
$apikey= 'YOUR-SERVER-API-ACCESS-KEY-GOES-HERE';
$registrationIds = $_GET['id'];
#prep the bundle
$msg = array
(
'body' => 'Body Of Notification',
'title' => 'Title Of Notification',
'icon' => 'myicon',/*Default Icon*/
'sound' => 'mySound'/*Default sound*/
);
$fields = array
(
'to' => $registrationIds,
'notification' => $msg
);
$headers = array
(
'Authorization: key=' . $apikey,
'Content-Type: application/json'
);
#Send Reponse To FireBase Server
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
#Echo Result Of FireBase Server
echo $result;
Related
I need to export woocommerce order data using a POST request to a third-party url.I have this code in functions.php
add_action('woocommerce_thankyou', 'wdm_send_order_to_ext');
function wdm_send_order_to_ext ( $order_id ){
// get order object and order details
$order = new WC_Order( $order_id );
$email = $order->get_billing_email();
$phone = $order->get_billing_phone();
$shipping_type = $order->get_shipping_method();
$shipping_cost = $order->get_total_shipping();
// set the address fields
$user_id = $order->get_user_id();
$address_fields = array('country',
'title',
'first_name',
'last_name',
'company',
'address_1',
'address_2',
'address_3',
'address_4',
'city',
'state',
'postcode');
$address = array();
if(is_array($address_fields)){
foreach($address_fields as $field){
$address['billing_'.$field] = get_user_meta( $user_id, 'billing_'.$field, true );
$address['shipping_'.$field] = get_user_meta( $user_id, 'shipping_'.$field, true );
}
}
// set the username and password
$api_username = 'username';
$api_password = 'password';
// setup the data which has to be sent
$data = array(
'username' => $api_username,
'password' => $api_password,
'name1' => $address['billing_first_name'],
'street' => $address['billing_address_1'],
'city' => $address['billing_city'],
'country' => $address['billing_country'],
'pcode' => $address['billing_postcode'],
'phone' => $phone,
'weight' => 4.0,
'parcel_type' => 'D',
'num_of_parcel' => 1
);
// send API request via cURL
$curl = curl_init();
/* set the complete URL, to process the order on the external system. Let’s consider http://example.com/buyitem.php is the URL, which invokes the API */
curl_setopt($curl, CURLOPT_URL, "https://easyship.si/api/parcel/parcel_import");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec ($curl);
curl_close ($curl);
}
However, it does not pass the request, the third-party API does not receive anything. WP_DEBUG doesn't see any errors. Tell me where to look, what is wrong?
You can use https://requestbin.com/ as endpoint to see data you are posting and if they are being posted correctly. If it successfully posting it to requestbin endpoint you can see the header and body formats as well. If its not working try debugging line by line.
Sorry I wasn't able to add this as comment
Below is my code to create or update subscription in Mailchimp.
function mailchimp_ajax_subscription()
{
$data = isset( $_POST['formData'] ) ? $_POST['formData'] : array();
ob_start();
if(count($data) > 0)
{
$api_key = 'XXXXXXXXXXXXXX';
$status = 'unsubscribed'; // subscribed, unsubscribed, cleaned, pending
$args = array(
'method' => 'PUT',
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( 'user:'. $api_key )
),
'body' => json_encode(array(
'email_address' => $data["email"],
'status' => $status,
'tags' => array($data["name"])
))
);
$response = wp_remote_post( 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/lists/XXXXX/members/' . md5(strtolower($email)), $args );
$body = json_decode( $response['body'] );
if ( $response['response']['code'] == 200 && $body->status == $status ) {
echo 'The user has been successfully ' . $status . '.';
} else {
echo '<b>' . $response['response']['code'] . $body->title . ':</b> ' . $body->detail;
}
}
wp_die();
}
Using above code, I can create subscription into Mailchimp but If I enter same email to edit the tags/status it gives me error.
Error:
400Member Exists: abc#xyz.com is already a list member. Use PUT to
insert or update list members.
I already used PUT in the code so what is missing?
You can use TAGS API to update the TAGS. Below is the sample code to update the TAG:
$postdata = array(
'apikey' => $api_key,
'email_address' => $userData["email"],
'tags' => array(
array(
'name' => $userData["name"],
'status' => 'active'
),
)
);
$mch_api = curl_init(); // initialize cURL connection
curl_setopt($mch_api, CURLOPT_URL, 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/' . md5(strtolower($userData['email']))."/tags");
curl_setopt($mch_api, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Basic '.base64_encode( 'user:'.$api_key )));
curl_setopt($mch_api, CURLOPT_RETURNTRANSFER, true); // return the API response
curl_setopt($mch_api, CURLOPT_TIMEOUT, 10);
curl_setopt($mch_api, CURLOPT_POST, true);
curl_setopt($mch_api, CURLOPT_POSTFIELDS, json_encode($postdata) ); // send data in json
$result = curl_exec($mch_api);
In wordpress, I'm trying to POST a specific email included as a value of a custom field (called customer_email) in each post to a mailchimp automation.
Below is the code I have and it's not working
function email_on_publish( $postid ) {
$api_key = API-KEY;
$workflow_id = WORKFLOW-ID;
$email_id = EMAIL-ID;
$email = get_post_meta( get_the_ID(), 'customer_email', true );
$args = array(
'method' => 'POST',
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( 'user:'. $api_key )
),
'body' => json_encode(array(
'email_address' => $email
))
);
$response = wp_remote_post( 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/automations/' . $workflow_id . '/emails/' . $email_id . '/queue/' . md5(strtolower($email)), $args );
$body = json_decode( $response['body'] );
}
add_action( 'pending_to_publish', 'email_on_publish' );
add_action( 'draft_to_publish', 'email_on_publish' );
Update: This has been resolved. There were two issues at hand.
I didn't need "md5(strtolower($email)" at the end of the post url.
Mailchimp requires you to send all prior emails in the workflow to the user before adding them to an automation. This was rendering all of my testing useless until I learned that.
Thanks for figuring this out, self!
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
));
}
how do I get my app (Android and iOS) receive push notifications, automatically from a control panel, or a webservice ... the only way I found is at the Appcelerator panel, and is not automatic ...
I wish, for example, when there was an update in the database, the push appeared in the user's mobile phone in question ... how can you do this?
Another thing is that how can I do that is generic for android and ios? Is there any module or video lesson to teach to do that?
For Multi Push Module
This is an part of my php for multi-platform push firing.
// iOS
$apnsHost = 'gateway.push.apple.com';
$apnsPort = 2195;
$apnsCert = 'apns-prod.pem';
//
$abrirPush = 1;
$mensagem = array(
"id_push" => $id_push,
"id_empresa" => $id_empresa,
"abrir" => $abrirPush
);
$mensagem = json_encode($mensagem);
$arr['aps'] = array(
'alert' => $nome_empresa . ' tem uma mensagem para você' ,
'badge' => 1,
'sound' => 'default',
'body' => $mensagem
);
$payload = json_encode($arr);
// Abre Conexão iOS
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
// Android
$arrayAndroid = Array();
// Search for iOS or Android Device
for ($i = 0; $i < count($montaArray); $i++){
$pegaToken = $montaArray[$i];
$contaToken = strlen($pegaToken);
if ($contaToken < 70){
$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $montaArray[$i])) . chr(0) . chr(strlen($payload)) . $payload;
fwrite($apns, $apnsMessage);
}else{
/// PUSH ANDROI ////
array_push( $arrayAndroid, $montaArray[$i]);
}
}
fclose($apns);
// API access key from Google API's Console ( Server KEY )
define( 'API_ACCESS_KEY', 'KEY_HERE' );
// prep the bundle
$msg = array
(
'message' => 'Tem uma mensagem para você',
'title' => $nome_empresa,
'payload' => $mensagem,
'vibrate' => 1,
'sound' => 1,
'largeIcon' => 'large_icon',
'smallIcon' => 'small_icon'
);
$fields = array
(
'registration_ids' => $arrayAndroid,
'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, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
print $result;
curl_close( $ch );
note that Apple doesn't alloy an array of tokens like Google does. As Android's token are larger than iOS's Tokens, I count it length to know which token it is.
$montaArray comes from my database where all token are stored