3 shares

In my last post, I wrote about Android Push Notifications setup using Firebase — a step-by-step guide to implement Firebase Cloud Messaging (FCM) service in Android application. In this post, I’ll discuss server side implementation using PHP to send FCM notification from the app server to the Android device.

FCM Push Notifications: Java Server Side Integration
A step-by-step guide to implement FCM notifications in back-end Java application.

About FCM Server

The server side of FCM consists of two main components:

  • FCM connection servers provided by Google. These servers take messages from an app server and send them to a client app running on a device. Google provides connection servers for HTTP and XMPP.
  • An app server that you must implement in your environment. This app server sends data to a client app via the chosen FCM connection server, using the appropriate XMPP or HTTP protocol.

A full FCM implementation requires both a client implementation and a server implementation to work perfectly.

App Server Implementation in PHP

We can send FCM push notification from our PHP app server to Android users by using Firbase Cloud Messaging HTTP Protocol. It provides following HTTP end-point that can be used to route all notifications requests:

https://fcm.googleapis.com/fcm/send

Here are some of the important parameters used to send downstream FCM messages.

  • to – Type String – (Optional) [Recipient of the message]
    The value must be a single registration token, notification key, or topic. Do not set this field when sending to multiple topics
  • registration_ids – Type String array – (Optional) [Recipients of the message]
    Multiple registration tokens, min 1 max 1000.
  • priority– Type String – (Optional) [ default normal]
    Allowed values normal and high.Normal priority optimizes the client app’s battery consumption and the app may receive the message with unspecified delay.High priority sends the message immediately, and the app can wake a sleeping device and open a network connection to the server.
  • delay_while_idle – Type boolean – (Optional) [default value false]
    True indicates that the message should not be sent until the device becomes active.
  • time_to_live – Type JSON number – (Optional) [default value 4 week maximum 4 week]
    This parameter specifies how long (in seconds) the message should be kept in FCM storage if the device is offline.
  • data – Type JSON Object
    Specifies the custom key-value pairs of the message’s payload.
    For example, with data: {“from”:”Lhe.io″,”title”:”FCM Notifications”}

For a complete list of targets,options and payloads available to send message from server visit this link.

OK let’s start the actual work, PHP coding to send FCM notification. Here is a code snippet that you can add into your PHP project to route push notification to intended user or a group of users.

<?php 

/* Example Parameter $data = array('from'=>'Lhe.io','title'=>'FCM Push Notifications');
	$target = 'single token id or topic name';
	or
	$target = array('token1','token2','...'); // up to 1000 in one request for group sending
*/
public function sendFCMMessage($data,$target){
   //FCM API end-point
   $url = 'https://fcm.googleapis.com/fcm/send';
   //api_key available in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
   $server_key = 'PASTE_YOUR_SERVER_KEY_HERE';
			
   $fields = array();
   $fields['data'] = $data;
   if(is_array($target)){
	$fields['registration_ids'] = $target;
   }else{
	$fields['to'] = $target;
   }
   //header with content_type api key
   $headers = array(
	'Content-Type:application/json',
        'Authorization:key='.$server_key
   );
   //CURL request to route notification to FCM connection server (provided by Google)			
   $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));
   $result = curl_exec($ch);
   if ($result === FALSE) {
	die('Oops! FCM Send Error: ' . curl_error($ch));
   }
   curl_close($ch);
   return $result;
}

You should pass all your custom attributes in data parameter as an array. If you’re sending to single user, pass user id or topic id in target parameter as string. For group notification, pass all user ids as an array in target parameter. Don’t forget to replace PASTE_YOUR_SERVER_KEY_HERE with your actual Secret Server Key that can be found in Firebase Console.

Continue Reading: FCM Push Notifications: Receive Messages in an Andriod App

Need further help? If you’re confused or facing any issue while completing first step, let’s know in comments.


Like it? Share with your friends!

3 shares
attacomsian

A passionate programmer, domainer, writer and photographer! Love writing about web development, latest trends in technology and domain name industry. Working hard to make the world a better place! Follow me at Twitter @attacomsian or visit my website www.attacomsian.com

1,080 Comments

Your email address will not be published.

  1. i am use But when Phone is locked then this notification not ring and show launcher icon doesn’t show those icons that icon i am set in android device
    Please Help me how can i fix this Problem

  2. hello sir can we send notification in our portal using firebase fcm standard in php to notifiy specific user

  3. Pingback: Cheap NFL Jerseys
  4. i got notification when our app in recent list….when app is dead status, notification wont come….can you help me???

  5. Если вы приняли решение получить мгновенный займ, вам надо определиться с организацией, где лучше взять займ online. В наши дни не все компании выдают срочные займы. Если вы хотите получить мгновенные займы, вам необходимо просмотреть список организаций, которые предоставляют займы на приемлемых условиях.

    На все-займы-тут.рф размещен каталог МФО, которые выдают мгновенные займы заемщикам. На сайте реально найти разные организации, прочитать отклики и определиться с параметрами займа. Большое количество компаний предоставляют деньги на нормальных условиях. Получить займ вы можете сегодня с паспортом.

    Для того, чтобы человек мог получить микрозайм на карту необходимо выбрать компанию, изучить условия займа. Каждый клиент попадал в положение, когда финансы нужны очень срочно. Близкие люди не всегда могут помочь финансово. По этой причине необходимо изучить шанс взять online займ на карту.

    Если вы стремитесь оформить онлайн займы на банковскую карту срочно , вам нужно выбрать условия. Если вы честный заемщик, финансы будут переведены вам в моментальные сроки. Получить деньги вы можете в рублях на конкретный срок. Нужно выделить, что сервис гарантирует полную конфиденциальность. На сайте собраны МФО, которые всегда идут людям навстречу. Новые лица также не будут ощущать какого-то дискомфорта. Лояльные условия кредитования также доступны для многих людей.

    У вас присутствует вероятность получить микрозаймы быстрее, чем это проходит в банковских учреждениях. Вам не придется собирать что-то из документов. Моментальные займы – уникальный выход, если вам в сжатые сроки нужны средства. Для получения средств следует заполнить анкету на портале МФО. С вами в сжатые сроки свяжется администратор и обсудит все детали.

    Если вы не уверены, где можно найти список лучших МФО, можете смело изучить его на портале. Лучшие микрофинансовые организации есть на портале. У всех сервисов есть техническая поддержка. Получить кредит вы можете на банковскую карту любого банка. Вы можете также получить деньги за 15 минут без лишних вопросов от банковских менеджеров.

    Затем, как ваша заявка будет одобрена, вы получите подтверждение. Более 90% заявок получают одобрение. Оформить кредит можно даже через планшет. Для этого нужно иметь выход в интернет. Также вам потребуется паспорт и банковская карта, куда вы будете получать средства.

  6. Отзывы: Обман Ренессанса И Секвойи О Прощении Части Долга

    ———————————–
    Приведем таблицу основных условий для заемщика. Несовершенство предлагаемого инструмента отметили многие клиенты банка, потому вопросы пересмотра лимита суммы инвестирования и его сроков решаются. Как быть таким смертным? Это очень важно, ведь услуги создаются таким образом, чтобы держатели карт не просто открывали счета, но и активно пользовались ими. На данный момент чаще всего можно встретить сообщения, в которых клиенты выражают недовольство обслуживанием в отделениях учреждения, недоброжелательностью сотрудников. Среди всех заключаемых договоров автострахования оформление электронных полисов на настоящий момент занимает порядка 12,2%. При этом есть ряд регионов, где более половины всех договоров ОСАГО заключается в электронном виде. При этом в банке работает четыре варианта рассмотрения заявки. На сегодняшний день эта организация имеет более 150 собственных филиалов и кредитных офисов. На счетах, которые используются для регистрации состояния и движения источников средств, в Д. После заполнения заявления введите присланный вам ключ электронной подписи (см п.2). После нажатия кнопки «Отправить» вам будет прислан пароль в смс-сообщении, после ввода которого счет за коммунальные услуги будет оплачен. У них есть собственный телефон, причем, не простой, а такой, на который вам звонить можно бесплатно. Часть средств Сбербанк будет возвращать на счет клиента в виде баллов, которые можно потратить у партнеров. Активно-пассивный счет – это счет, применяемый в бухгалтерском учете, на котором одновременно отражаются активы, или имущество предприятия, и пассивы, источники его формирования.

    Перейдите ниже по ссылке, чтобы получить кредит:

    почта банк

  7. Buy Hip-Hop Kit by raspberrymusic on AudioJungle. Easy and positive hip-hop to the background. It sends a pleasant summer atmosphere and easy mood. Great for motivati…

    http://v.ht/zXnx – Show more!

  8. Избавит от грибка всего за 20 дней и не допустит повторного заражения, благодаря комплексу из натуральных масел и лекарственных растений.
    Наш сайт: https://ljvgzmqd.morningeverning.com

  9. King bedroom sets
    On site online our store customer waiting large variety at cost.Catalog contains retail prices, farmhouse style information about options fittings possible alternatives complete modules.Each item furnishings produced directly from manufacturer. Lowering cost on farmhouse style formed due to the absence of production floor space, for hiring which relied make payment and smallest state workers. No such costs allow to establish very affordable prices for all categories acquisitions.

  10. I am really impressed along with your writing skills as neatly as with the structure for your blog. Is this a paid subject or did you customize it your self? Either way keep up the excellent high quality writing, it is uncommon to look a nice weblog like this one nowadays.

  11. На мой взгляд, это интересный вопрос, буду принимать участие в обсуждении.


    кульно скачать фифа, fifa 15 или fifa 15 скачать fifa

  12. Pingback: ncfuqtic
  13. Pingback: buy cialis
  14. Pingback: this essay help me
  15. Pingback: amoxicillin pills
  16. Pingback: buy stromectol
  17. Pingback: albuterol 0.83
  18. Pingback: clomid steroid
  19. Pingback: diflucan alcohol
  20. Pingback: cost of metformin
  21. Pingback: paxil pi
  22. Pingback: viagra india price
  23. Pingback: duloxetine dr 30mg
  24. Pingback: cialis cost uk
  25. Pingback: rcp tadalafil
  26. Pingback: cialis 200mg
  27. Pingback: 80 mg viagra
  28. Pingback: cialis buy india
  29. Pingback: levitra e molly
  30. Pingback: cialis drug
  31. Pingback: viagra substitutes
  32. Pingback: cytotmeds.com
  33. You really make it appear really easy with your presentation however I find this
    matter to be actually something which I feel I would by no means understand.

    It kind of feels too complicated and extremely huge
    for me. I’m looking ahead on your subsequent submit,
    I will try to get the dangle of it!

  34. Pingback: generic priligy uk
  35. Pingback: chipotle keto bowl
  36. Pingback: stromectol for ear
  37. Pingback: how to get cialis
  38. Pingback: can plaquenil
  39. Pingback: purchase viagra
  40. Pingback: viagra pills
  41. Pingback: viagra sale
  42. Pingback: order viagra
  43. Pingback: buy generic cialis
  44. Pingback: viagra otc
  45. Pingback: sildenafil generic
  46. Pingback: sildenafil
  47. Pingback: gtrviagraok.com
  48. Pingback: generic for viagra
  49. Pingback: merck ivermectin
  50. Pingback: cialis france
  51. Pingback: viagra purple pill
  52. Pingback: cialis superactive
  53. Pingback: sildenafil 100mg
  54. Pingback: ivermectin liquid
  55. Pingback: ivermectin liquid
  56. Pingback: ivermectina usa
  57. Pingback: compra viagra
  58. Pingback: cheap viagra
  59. Pingback: buy amoxicillin uk
  60. Pingback: furosemide 45 mg
  61. Pingback: neurontin 30 mg
  62. Pingback: apo-prednisone
  63. Pingback: viagra walmart
  64. Pingback: generic priligy
  65. Pingback: order zithromax
  66. Pingback: lasix sale
  67. Pingback: real cialis 20mg
  68. Pingback: cost of priligy
  69. Pingback: stromectol nz
  70. Pingback: buying viagra
  71. Pingback: cialis viagra
  72. Pingback: citrate sildenafil
  73. Pingback: levitra vs viagra
  74. Pingback: walgreens viagra
  75. Pingback: viagra for men
  76. Pingback: online viagra
  77. Pingback: viagra sildenafil
  78. Pingback: viagra substitute
  79. Pingback: zithromax 250
  80. Pingback: olumiant covid
  81. Pingback: tizanidine 44
  82. Pingback: tamoxifen brand
  83. Pingback: clomid generic
  84. Pingback: bactrim ivpb
  85. Pingback: flagyl 400
  86. Pingback: cephalexin storage
  87. There’s certainly a great deal to know about
    this issue. I really like all the points you have made.

  88. My relatives every time say that I am killing my time here at net, however I know I am getting knowledge every
    day by reading thes nice articles or reviews.

  89. Pingback: 3brochures
  90. Pingback: viagra
  91. Pingback: revatio