Receive subscribed messages in URL endpoint from Google Cloud Platform (GCP)


Subscribers get messages published to a topic by subscribing to topic subscriptions. A push subscription can be setup to receive the messages in a URL endpoint from GCP.

IoT Cloud Tester  application provides an easy interface to setup the push endpoint for a subscription.

To receive subscribed messages in URL endpoint from GCP,

  • Create a push subscription 
  • Publish message to the topic in the push subscription.
  • Process the message received in the URL endpoint.
  • In this below example,  the push subscription (subscription_962446) was created for the topic 'device_enviornment'.The push endpoint was setup as 'https://m2msupport.net/m2msupport/process_push.php'. Any message published to the topic 'device_enviornment' will be sent to that endpoint.

In the 'Publish' tab, device 'dev_70234' is enabled to publish messages to the topic 'device_enviornment'. IoT Cloud Tester application will generate data based on the data model 'device_data'. Google Cloud forwards those messages to the endpoint 'https://m2msupport.net/m2msupport/process_push.php' which parses the message and writes to a text file.

Here is the PHP code example that processes the message from the Google Cloud Platform

<?php

//Read the push JSON message from Google Cloud
$json = file_get_contents('php://input');

// Converts it into a PHP object
$output = json_decode($json,TRUE);

$file = 'push_messages.txt';

// Open the file to get existing content
$current = file_get_contents($file);

//Add the parsed elements to the text file
$current .= "JSON Post from Google Cloud"."\n".$json."\n";
$current .= "Device Id - ".$output['message']['attributes']['deviceId']."\n";
$current .= "Message data - ".base64_decode($output['message']['data'])."\n";
$current .= "Subscription ID - ".$output['subscription']."\n\n";

// Write the contents back to the file
file_put_contents($file, $current);

?>