Here's my PHP code for a REST function to POST to the MQTT Subscription End Point.
I'm not the best coder but it should be pretty solid. Guy
<?php
$sResp = "" ;
$iRC = 0 ;
$fields = array('payload' => 'REST Msg' , 'topic' => 'esp32/publish' ); // Data is typically an array
$sUserKey = '4p8OMdfdHcwrtBTHR84lmqYXSbJWxOJq2I4EJxxxxxxxxxxxxxxxxxxxxxxx'; // Your MQTT Token
//By Ref Arg
function f_RestPublish_MQTT($Userkey , $arrData , &$sRespMsg ) {
try{
$iRC = 0; //return Code
$sError = "" ;
$headers = array
(
'Content-Type: application/json' ,
'Accept: application/json' ,
'Authorization:' . $Userkey
);
$sPayload = json_encode( $arrData ); //JSON encode to string
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, 'https://flespi.io/mqtt/messages' ); // End Point
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, $sPayload );
// Execute post
$server_output = curl_exec($ch);
if($server_output === false){
$sError = 'Curl failed: ' . curl_error($ch);
curl_close($ch);
throw new Exception($sError);
}
curl_close($ch);
//We had a Valid Curl execution, decode json respomse
$oJsonResp = json_decode( $server_output, JSON_NUMERIC_CHECK ) ;
if( isset( $oJsonResp['errors'] ) ){
$oErrors = $oJsonResp['errors'][0] ;
$sError = 'REST Server Error Code: ' . implode( ", ", $oErrors ) . "." ;
throw new Exception($sError);
}
//All Good
$iRC = 1 ;
} //Try
catch (exception $e){
$sError = 'MQTT Exception: '. $e->getMessage();
}
finally {
$sRespMsg = $sError ; //ByRef Param
return $iRC ; //Returns Response err string
}
}
// Now Call It. $sResp is Byref so it has any error message
$iRC = f_RestPublish_MQTT( $sUserKey ,$fields ,$sResp ) ;
?>