iInfo 資訊交流: Firebase Cloud Messaging (FCM) 入門到進階應用(3) --- 其他程式語言

最新消息

[公告2014/05/30] 如有需要將部落格中,任何一篇文章的程式碼使用在商業用途,請與我聯繫。

[公告2015/04/26] Line版的 iInfo程式與投資應用 群組已上線想加入的朋友們,請先查看 "入群須知" 再與我聯繫 Line : aminwhite5168,加入請告知身分與回答 "入群須知" 的問題。

[公告2017/02/20] 近來有網友詢問 MultiCharts 與 Excel 畫冰火能量圖 (8)MultiCharts 與Excel 畫冰火能量圖(11) --- 更名「台股儀表板」 文章中教學檔案取得方式,有興趣的朋友可透過 Line了解詳情 (請勿以為是免費分享),Line : aminwhite5168。

[公告2018/04/22] 台北 Python + Excel VBA 金融資訊爬蟲課程,課程如網頁內容 金融資訊爬蟲班:台北班 Python 金融資訊爬蟲、EXCEL VBA 金融資訊爬蟲,請盡快把握機會,歡迎券商、大專院校邀約講座。

[公告2018/06/01] 台指能量儀表板教學課程,課程如網頁內容 台北班:台指能量儀表板

[公告2018/10/02] 期交所於2018/10/03進行網址改版,若有參考部落格與期交所相關文章,請各位讀者自行修改。

2017年1月19日 星期四

Firebase Cloud Messaging (FCM) 入門到進階應用(3) --- 其他程式語言

Firebase Cloud Messaging 官方提供的語言原始碼不多,筆者也一樣分享其他相關的語言,讓各方的使用者可以參與,有意願分享的朋友請與筆者聯繫。
Python、GAS、C++、C# 、Node.js、R、Curl版本分享於此。
Python 2.7
import requests
import json

def SendMessageToLineNotify(Message, MessagingSenderId, Token):
        headers = {"content-type": "application/json",
                   "Authorization": "key=" + MessagingSenderId}
        
        url = "https://fcm.googleapis.com/fcm/send"
        
        data = {"notification": {"title" : "iinfo資訊交流",
                                 "body" : Message,
                                 "icon" : "https://www.ccf.org.tw/new/endpoverty/images/product/product-pic1.jpg",
                                 "click_action" : "http://white5168.blogspot.tw/"}, 
                "to": Token}
        
        req = requests.post(url, data=json.dumps(data), headers=headers)
        print req.text

def main():
        Message = "中文字~!@#$%^&*()_+123456789"
        MessagingSenderId = "你的MessagingSenderId"
        Token = "你的Token"
        SendMessageToLineNotify(Message, MessagingSenderId, Token)

if __name__ == '__main__':
    main()
Google Apps Script
function SendMessageByFCM()
{
  var Message = '中文字~!@#$%^&*()_+123456789';
  var PictureURL= 'https://www.ccf.org.tw/new/endpoverty/images/product/product-pic1.jpg';
  var MessagingSenderId = '你的MessagingSenderId';
  var Token = '你的Token';

  sendMessage(Message, PictureURL, MessagingSenderId, Token);
}

function sendMessage(Message, PictureURL, MessagingSenderId, Token){
  
  var URL = 'https://fcm.googleapis.com/fcm/send';

  var payload = 
      {
        'notification':{ 
          'title' : 'iinfo資訊交流',
          'body' : Message,
          'icon' : PictureURL,
          'click_action' : 'http://white5168.blogspot.tw/'
        },
        "to" : Token
      };

  var header =
      {
        'Content-Type':'application/json',
        'Authorization' : 'key=' + MessagingSenderId        
      }
  
  var options =
      {
        'method'  : 'post',
        'payload' : JSON.stringify(payload),
        'headers' : header
      }; 

  var response = UrlFetchApp.fetch(URL, options);
  Logger.log(response);
}
VC++
VC++ 處理 JSON 可參考 Visual Studio 2010 C++ 使用 Jsoncpp 。
#include "stdafx.h"
#include "POSTJSONVC.h"
#import "msxml4.dll"
#include "json/json.h"
#include "json/value.h"

using namespace std;
using namespace MSXML2;

inline void THROW_IF_FAIL( HRESULT _hr )  { if FAILED(_hr) throw(_hr); }

void SendMessageByFCM()
{
 CString csMessage;

 OutputDebugString("測試XMLHTTP傳文字與網路圖片!\n");

 try
 {
  //初始化Com元件
  THROW_IF_FAIL(CoInitialize(NULL));

  IXMLHTTPRequestPtr xmlrequest=NULL;  
  VARIANT vAsync;
  vAsync.vt = VT_BOOL;
  vAsync.boolVal = FALSE;

  VARIANT vUser;
  vUser.vt = VT_BOOL;
  vUser.bstrVal = NULL;

  VARIANT vPassword;
  vPassword.vt = VT_BOOL;
  vPassword.bstrVal = NULL;             

  //指定的FCM Token
  bstr_t MessagingSenderId = "你的MessagingSenderId";

  bstr_t Token = "你的Token";

  //網路圖片連結 家扶娃娃撲滿
  CString PicURL = "http://www.ccf.org.tw/new/endpoverty/images/product/product-pic1.jpg";
    
  //FCM網址
  bstr_t sUrl = "https://fcm.googleapis.com/fcm/send";   

  //文字訊息
  CString csMessage = "中文字~!@#$%^&*()_+123456789";
  Json::Value root; 
  Json::Value notification;
  notification["title"] = "iinfo資訊交流";
  notification["body"] = Json::Value(csMessage);
  notification["icon"] = Json::Value(PicURL);
  notification["click_action"] = "http://white5168.blogspot.tw/";
  root["notification"] = notification;
  root["to"] = Json::Value(Token);
  Json::StyledWriter fw;
  string outputConfig = fw.write( root );
  CString payload = outputConfig.c_str();
  printf("%s\n", payload);

  //
  // 建立 MSXML2.XMLHTTP 物件.
  //
  THROW_IF_FAIL(xmlrequest.CreateInstance("MSXML2.XMLHTTP"));  

  //
  // 傳送 HTTPPOSTrequest.
  //
  bstr_t sMethod = "POST";
  THROW_IF_FAIL(xmlrequest->open(sMethod, 
   sUrl,
   vAsync,
   vUser,
   vPassword));

  //Header內容設定
  THROW_IF_FAIL(xmlrequest->setRequestHeader("Content-Type:", "application/json"));                
  THROW_IF_FAIL(xmlrequest->setRequestHeader("Authorization", "key=" + MessagingSenderId));

  //
  // 傳送 request 到 server.
  //
  THROW_IF_FAIL(xmlrequest->send(_variant_t(payload)));

  //
  // 取得執行狀態
  //
  long lStatus;
  xmlrequest->get_status(&lStatus);
  if(lStatus == 200)
  {
   BSTR bstrResponseText;
   xmlrequest->get_responseText(&bstrResponseText);
   _bstr_t bstrtbody(bstrResponseText);
   csMessage.Format("responseText = %s\n", (char*)(bstr_t)bstrtbody); 
   MessageBox(NULL, csMessage, "執行成功", MB_ICONASTERISK);
  }
  else
  {
   BSTR bstrResp;
   xmlrequest->get_statusText(&bstrResp);   
   csMessage.Format("statusText = %s\n", (char*)(bstr_t)bstrResp);
   MessageBox(NULL, csMessage, "執行失敗", MB_ICONERROR);
  }
 }
 catch (_com_error &e)
 {
  if(BSTR(e.Description())) 
  {
   csMessage.Format("Description = %s", BSTR(e.Description())); 
   OutputDebugString(csMessage);
  }
 }

 CoUninitialize();

 OutputDebugString("執行結束\n");
}

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
 SendMessageByFCM();

 return 0;
}
C#
透過 Nuget 安裝  Newtonsoft.Json,並使用 using Newtonsoft.Json。
安裝指令:
Install-Package Newtonsoft.Json
using System;
using System.IO;
using System.Net;
using System.Text;
using Newtonsoft.Json;

namespace POSTJSON
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a request using a URL that can receive a post. 
            WebRequest request = WebRequest.Create("https://fcm.googleapis.com/fcm/send");

            // Set the Method property of the request to POST.
            request.Method = "POST";

            // Create POST data and convert it to a byte array.
            string MessagingSenderId = "你的MessagingSenderId";
            string Token = "你的Token";
            string message = "中文字~!@#$%^&*()_+123456789";
            string PictureURL = "http://www.ccf.org.tw/new/endpoverty/images/product/product-pic1.jpg";
            var payload = new
            {
                notification = new { title = "iinfo資訊交流",
                                     body = message,
                                     icon = PictureURL,
                                     click_action = "http://white5168.blogspot.tw/"
                                    }, 
                to = Token
            };
            string postData = JsonConvert.SerializeObject(payload);           

            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/json";

            // Set the Header property of the WebRequest.
            request.Headers["Authorization"] = "key=" + MessagingSenderId;

            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;

            // Get the request stream.
            Stream dataStream = request.GetRequestStream();

            // Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);

            // Close the Stream object.
            dataStream.Close();

            // Get the response.
            WebResponse response = request.GetResponse();

            // Display the status.
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);

            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream();

            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);

            // Read the content.
            string responseFromServer = reader.ReadToEnd();

            // Display the content.
            Console.WriteLine(responseFromServer);

            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();
        }
    }
}
Node.js
var MessagingSenderId = "你的MessagingSenderId"
var Token = "你的Token";
var PictureURL = "http://www.ccf.org.tw/new/endpoverty/images/product/product-pic1.jpg";
var Message = "中文字~!@#$%^&*()_+123456789";
sendMessage(Message, PictureURL, MessagingSenderId, Token)

function sendMessage(Message, PictureURL, MessagingSenderId, Token)
{
    var FCMURL = "https://fcm.googleapis.com/fcm/send";
    var strMessage = { "notification" :{
                            "title" : "iinfo資訊交流",
                            "body" : Message,
                            "icon" : PictureURL,
                            "click_action" :  "http://white5168.blogspot.tw/"
                        } ,
                        "to" : Token };
    var payload = JSON.stringify(strMessage);
    
    var XMLHttpRequest = require("w3c-xmlhttprequest").XMLHttpRequest;
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
        if (xhttp.readyState === 4) {
            console.log(xhttp.responseText);
            console.log(xhttp.status);
        }
    };            
    
    xhttp.open('POST', FCMURL, true);
    xhttp.setRequestHeader('Content-Type', 'application/json');
    xhttp.setRequestHeader('Authorization', 'key=' + MessagingSenderId);
    xhttp.send(payload);
}
R
需在Rstudio上先安裝rjson套件。
install.packages("rjson")
再使用以下程式碼。
library(httr)
library(rjson)
MessagingSenderId <- "key=你的MessagingSenderId"
token <- "你的Token"
url <- "https://fcm.googleapis.com/fcm/send"
title <- "iinfo資訊交流"
body <- "中文測試~@#$%^&*()123456789"
icon <- "http://www.ccf.org.tw/new/endpoverty/images/product/product-pic1.jpg"
click_action <- "http://white5168.blogspot.tw/"
notification <- list(title=iconv(title, "big5", "utf8"), body=iconv(body, "big5", "utf8"), icon=iconv(icon, "big5", "utf8"), click_action=iconv(click_action, "big5", "utf8"))
payload <- toJSON(list(notification=notification, to=token))
header <- add_headers("Content-Type"="application/json", "Authorization"=MessagingSenderId)
req <- POST(url, header, body = payload, encode = "json") 
status <- content(req , as ="text", encoding = "utf-8")
status
更精進的寫法,置換第10、11行成以下程式碼。
notification <- c(title=title, body=body, icon=icon, click_action=click_action)
payload <- toJSON(list(notification=iconv(notification, "big5", "utf8"), to=token))
Curl
透過外部工具 Curl 指令執行,中文字無法處理。
curl -X POST -H "Authorization: key=你的MessagingSenderId" -H "Content-Type: application/json" https://fcm.googleapis.com/fcm/send -d "{\"to\":\"你的Token\",\"notification\":{\"title\":\"iinfo資訊交流\", \"body\":\"中文字~!@#$%^&*()_+123456789\",\"icon\":\"http://www.ccf.org.tw/new/endpoverty/images/product/product-pic1.jpg\", \"click_action\":\"http://white5168.blogspot.tw/\"}}"

執行結果:

參考資料: