Share My Creation PHP code to send Firebase Notification to both Android mobile app and iOS mobile app

Hi there!

I'm sharing one of my work here so that some of you might refer it.

This code is the PHP part from the whole project that I was working on. My project is based on the automated Forex signals that will be sent to Android and iOS mobile app from an indicator built on MT4 MetaQuote. Once the indicator triggered a signal, it will invoke a URL on the server to send the signal to both Android and iOS app at the same time.

I built this PHP part as a middleware so that I don't have to build the end-user apps every time I need to tweak something on the integration part.

The code will send Firebase Notification to both apps and the apps will trigger notification telling the users of a new signal that is coming in. All automated. The tricky part was on the construction of the firebase message data. iOS structure is a little bit different compared to Android. So I code it based on the B4j sample shared by Erel.


Here is the code..

::kamal::

sendmobile.php:
<?php
/*
USAGE IN MT4:
   //https://mydomain.com/sendmobileapp.php?&time=2020.06.17%2006:00:00:00&trade=BUY&pair=TEST&tf=H1&at=0.00&sl=0.00&tp=0.00&pips=0&lot=SMALL
   parameterURL = "https://mydomain.com/flyfx/sendmobileapp.php?";
   parameterURL += "&time="+TimeToString(TimeLocal(),TIME_DATE)+"%20"+TimeToString(TimeLocal(),TIME_SECONDS);
   parameterURL += "&trade="+trade;
   parameterURL += "&pair="+pair;
   parameterURL += "&tf="+tf;
   parameterURL += "&at="+DoubleToString(at, Digits);
   parameterURL += "&sl="+DoubleToString(sl, Digits);
   parameterURL += "&tp="+DoubleToString(tp, Digits);
   parameterURL += "&pips="+string(pips);
   parameterURL += "&lot="+lotsize;
*/


error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once("mysql.php");

$time = stripslashes(trim($_GET["time"]));
$trade = stripslashes(trim($_GET["trade"]));
$pair = stripslashes(trim($_GET["pair"]));
$tf = stripslashes(trim($_GET["tf"]));
$price = stripslashes(trim($_GET["at"]));
$sl = stripslashes(trim($_GET["sl"]));
$tp = stripslashes(trim($_GET["tp"]));
$pips = stripslashes(trim($_GET["pips"]));
$lot = stripslashes(trim($_GET["lot"]));
$time = str_replace(".", "-", $time);

if($trade=="BUY"){
    if($lot=="BIG"){
        $trend=" following an uptrend. Consider using BIG lot size.";
    } else {
        $trend=". Use SMALL lot size for this counter-trend trade and always check your spread.";
    }
} else {
    if($lot=="BIG"){
        $trend=" following a downtrend. Consider using BIG lot size.";
    } else {
        $trend=". Use SMALL lot size for this counter-trend trade and always check your spread.";
    }
}

$desc="Timeframe: ".$tf."\n".$trade." ".$pair." with a TP target around ".$pips."pips".$trend;

//check # of free signals per day:
//  free:   2
//  1m:     4
//  3m:     6
//  6m:     10
//  vip:    all
function PublishedSignals($conn, $package, $time){
    $sql="SELECT COUNT(*) counts FROM signals WHERE package = $package AND visible = 0 AND DATE_FORMAT(time, '%Y-%m-%d')='" . substr($time,0,10) . "'";
    $result = mysqli_query($conn, $sql);
    if($result->num_rows>0) {
        $row  = mysqli_fetch_array($result);
        return $row[0];
    } else {
        return 0;
    }
}

$package = 4;

if($lot=="BIG"){
    if(PublishedSignals($conn, 3, $time)<10) { $package = 3; }
    if(PublishedSignals($conn, 2, $time)<6)  { $package = 2; }
    if(PublishedSignals($conn, 1, $time)<4)  { $package = 1; }
} else {
    if(PublishedSignals($conn, 3, $time)<10) { $package = 3; }
    if(PublishedSignals($conn, 2, $time)<5)  { $package = 2; }
    if(PublishedSignals($conn, 1, $time)<4)  { $package = 1; }
    if(PublishedSignals($conn, 0, $time)<2 && (strtoupper($tf)=='H1' || strtoupper($tf)=='H4'))  { $package = 0; }
}

$body="Trade: " .$trade."\n";
$body.="Pair: " .$pair."\n";
$body.="TF: "   .$tf."\n";
$body.="Price: ".$price."\n";
$body.="SL: "   .$sl."\n";
$body.="TP: "   .$tp."\n";
$body.="Pips: " .$pips."\n";
$body.="Lot: "  .$lot."\n";

$api_key = "<put your server API key here>";

function SendMessage($platform, $api_key, $Topic, $Title, $Body){
    $url = 'https://fcm.googleapis.com/fcm/send';

    if($platform=="android"){
        $fields = array (
            'to' => "/topics/".$Topic,         
            'data' => array (
                    "body" => $Body,
                    "title" => $Title )
            );
    } else {
        $fields = array (
            'to' => "/topics/".$Topic, 
            'priority' => 10,                 
            'data' => array (
                    "body" => $Body,
                    "title" => $Title ),
            'notification' => array (
                "sound" => "default",
                "body" => $Body,
                "title" => $Title ),
                );
    }

    $headers = array(
        'Authorization:key='.$api_key,
        'Content-Type: application/json;charset=UTF-8'
        );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    //echo  json_encode($fields);
    $result = curl_exec($ch);           
    //curl_error($ch);
    //if ($result === FALSE){
    //    die('Sending Firebase Message failed: ' . curl_error($ch));
    //}
    curl_close($ch);
    return $result;
}

$result = mysqli_query($conn,"SET CHARACTER SET utf8");
$result = mysqli_query($conn,"INSERT INTO signals (pair, time, action, price, sl, tp, description, package, visible)
                                VALUES('$pair', '$time', '$trade', $price, $sl, $tp, '$desc', $package, $visible)");
if($result) {
    
    $id = 0;
    $result = mysqli_query($conn,"SELECT MAX(id) FROM signals");
    if($result->num_rows>0) {
        $row  = mysqli_fetch_array($result);
        $id = $row[0];
    }

    switch($package){
    case 0:
        $topic = "general";
        $topic_ios = "ios_general";
        break;
    case 1:
        $topic = "1m";
        $topic_ios = "ios_1m";
        break;
    case 2:
        $topic = "3m";
        $topic_ios = "ios_3m";
        break;
    case 3:
        $topic = "6m";
        $topic_ios = "ios_6m";
        break;
    case 4:
        $topic = "vip";
        $topic_ios = "ios_vip";
        break;
    default:
        $topic = "general";
        $topic_ios = "ios_general";
        break;
    }

    $sent_android = SendMessage("android", $api_key, $topic,     "New signal has been published", $body);
    $sent_ios     = SendMessage("ios",     $api_key, $topic_ios, "New signal has been published", $body);

    $message_sent = ($sent_android && $sent_ios);

    if(!$message_sent){
        if(!$sent_android && !$sent_ios) {$code = "4"; $errMsg="Android and iOS";} //error sending to both android & ios
        if(!$sent_android && $sent_ios)  {$code = "2"; $errMsg="Android";} //error sending to both android
        if($sent_android && !$sent_ios)  {$code = "3"; $errMsg="iOS";} //error sending to both ios
        print '{"status":"OK", "code":"'.$code.'", "id":"'.$id.'", "message":"'.$package.': Signal upload successful but alert not sent to '.$errMsg.'!"}';
    } else {
        print '{"status":"OK", "code":"0", "id":"'.$id.'", "message":"'.$package.': Signal upload successful!"}';
    }
    
} else {
    print '{"status":"FAILED", "code":"-1", "id":"0", "message":"Unable to upload or database error!"}';
}

?>
 

Kope

Active Member
Licensed User
This is amazing, have been planning to code same app but am yet to learn how to code mt4. Will be happy if you can assist and share your project.
 

Muhamad Kamal

Member
Licensed User
well you can always find mt4 mql codes in stackoverflow and mt4/mt5 forums.. unfortunately I could not share my mql projects as I'm bound to contract with clients coz they sell these codes..

however I can share some of my knowledge for certain things if you have questions..
 

Similar Threads

Top