LoginSignup
8
8

More than 5 years have passed since last update.

niftyクラウドmobile backendのREST APIをC#から叩いてPush通知登録

Last updated at Posted at 2015-08-19

niftyクラウドのREST APIを利用するには、シグネチャを生成する必要がある。
http://mb.cloud.nifty.com/doc/current/rest/common/signature.html

C#からシグネチャを生成して(生成後はその文字列を利用)、Push通知登録するまでのコード(コンソールアプリ)を書いた。

REST APIをたたくためにRestSharpを利用(NuGetから入れる)。
http://restsharp.org/

また、ハッシュ値を生成してBase64エンコードする部分では、以下のサイトにあったCreateToken関数を利用。
http://www.jokecamp.com/blog/examples-of-creating-base64-hashes-using-hmac-sha256-in-different-languages/#csharp

さらに、JSON形式を取り扱うためにDymamicJSONを利用(DynamicJson.csをプロジェクトに追加)。
http://neue.cc/2010/04/30_256.html

注意:
* キーの部分は、<入れる>としてある
* 関数化しきれてない部分あり(PushNotification関数の引数にsignatureを入れてるが、内部でキー決め打ちとか)

Prgram.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RestSharp;
using System.Security.Cryptography;
using System.Web.Script.Serialization;
using Codeplex.Data;

namespace ConsoleApp_PushSendTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Send PushMessage using nifty cloud REST API\n");

            Console.WriteLine("Input title");
            string str_title = Console.ReadLine();
            Console.WriteLine("Input message");
            string str_message = Console.ReadLine();
            Console.WriteLine("Input URL [defaut: http://www.google.com/]");
            string str_URL = Console.ReadLine();
            Console.WriteLine("Use dialog ? [y]/n");
            string str_dialog = Console.ReadLine();

            if (str_title.Equals("")) { str_title = "empty"; }
            if (str_message.Equals("")) { str_message = "empty"; }
            if (str_URL.Equals("")) { str_URL = "http://www.google.com/"; }
            bool b_dialog = true;
            if (str_dialog.Equals("n") || str_dialog.Equals("no") || str_dialog.Equals("N") || str_dialog.Equals("No") || str_dialog.Equals("NO")) { b_dialog = false; }

            const string client_key = "<入れる>";

            //通信とAPI利用回数消費がもったいないのでコメントアウト
            //string str_signature = CreateToken(getNiftyCloudAPIHeader(), client_key);
            //Console.WriteLine(str_signature);
            string str_stored_signature = "<上記で取得した文字列を入れる>";
            //Console.WriteLine(str_stored_signature);

            PushNotification(str_stored_signature, str_title, str_message, str_URL, b_dialog);

            Console.WriteLine("Hit any key to end...");
            Console.ReadLine();
        }

        static string getNiftyCloudAPIHeader()
        {
            // http://mb.cloud.nifty.com/doc/current/rest/common/signature.html
            // niftyクラウドでREST APIを使う際は、署名が必要
            // 署名データを得るための文字列を返す
            // JSONデータは不要なので、timeまで
            // timeは現在時刻とあったが、とりあえず固定値にしてある
            //
            const string str_header1 = "POST\nmb.api.cloud.nifty.com\n/2013-09-01/push\n";
            //DateTime dt = DateTime.Now;
            //string time = dt.ToString("yyyy-MM-ddTHH:mm:sszzzz");
            string time = "2013-12-02T02:44:35.452Z";
            string str_header2 = "SignatureMethod=HmacSHA256&SignatureVersion=2&X-NCMB-Application-Key=<入れる>X-NCMB-Timestamp=" + time;
            return str_header1 + str_header2;
        }

        // 与えられたmessegeを秘密鍵secretでハッシュ値を生成してBase64エンコードする
        // http://www.jokecamp.com/blog/examples-of-creating-base64-hashes-using-hmac-sha256-in-different-languages/#csharp
        static string CreateToken(string message, string secret)
        {
            secret = secret ?? "";
            var encoding = new System.Text.ASCIIEncoding();
            byte[] keyByte = encoding.GetBytes(secret);
            byte[] messageBytes = encoding.GetBytes(message);
            using (var hmacsha256 = new HMACSHA256(keyByte))
            {
                byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
                return Convert.ToBase64String(hashmessage);
            }
        }

        static void PushNotification(string signature, string pushTitle, string pushMessage, string pushURL, bool dialog)
        {
            // ----------------------------------------------------------------------
            // http://www.macklabmedia.com/send-push-notification-parse-rest-api-c/
            // RestSharpを利用(nugetでインストールする)
            // try-catch必要かも?
            // ----------------------------------------------------------------------

            // Output "BEGIN" to console
            Console.WriteLine("PushNotification_BEGIN");

            // Build Request URL
            var client = new RestClient("https://mb.api.cloud.nifty.com");
            var request = new RestRequest("2013-09-01/push", Method.POST);

            string mess = "\"" + DateTime.Today.ToShortDateString() + ": " + pushMessage + "\"";

            // Build JSON string to send to server
            string json = "{\"immediateDeliveryFlag\": true, \"target\":[\"android\"], \"message\":\"Please input your test messge\",\"deliveryExpirationTime\":\"3 day\"}";

            // Build JSON string using DynamicJson
            // http://neue.cc/2010/04/30_256.html
            // DynamicJson.csをプロジェクトに追加
            var obj = new
            {
                immediateDeliveryFlag = true,
                target = new[] {"android"},
                message = mess,
                deliveryExpirationTime = "3 day",
                title = pushTitle,
                dialog = dialog,
                action = "com.example.hogehoge.RECEIVE_PUSH",  // カスタムレシーバー(適宜変更する)
                richUrl = pushURL
            };
            var formattedString = DynamicJson.Serialize(obj);
            Console.WriteLine(formattedString);

            // Output json to console
            //Console.WriteLine(json);
            //Console.WriteLine(formattedString);
            json = (string)formattedString;

            // Build Parameters and Headers to send with request
            request.AddParameter("application/json", json, ParameterType.RequestBody);

            // Enter your App ID and REST API Key from your Parse account. Login and go to Settings and Keys.
            request.AddHeader("X-NCMB-Application-Key", "<入れる>");
            request.AddHeader("X-NCMB-Signature", signature);
            request.AddHeader("X-NCMB-Timestamp", "2013-12-02T02:44:35.452Z");

            // Let the Parse server know you're sending JSON
            request.AddHeader("Content-Type", "application/json");

            // Execute the Request
            IRestResponse response = client.Execute(request);

            // Get the response back from server
            var content = response.Content;
            Console.WriteLine("response = " + content);

            // Output "END" to console
            Console.WriteLine("PushNotification_END");
        }
    }
}
8
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8