【问题标题】:Sending push notification through Urban Airship via JavaScript通过 JavaScript 通过 Urban Airship 发送推送通知
【发布时间】:2013-04-18 14:20:41
【问题描述】:

我建立了一个简单的网站,其中包含一个带有 JavaScript onclick 方法的按钮,我想使用 Urban Airship 向我的手机发送推送通知。

如果我在 data 属性周围使用引号,我会得到“500(内部服务器错误)”。如果我不在 data 属性周围使用引号,我会从 Urban Airship 获得一个弹出授权窗口,我在其中写入我的应用程序密钥和主密钥。它似乎接受了这一点,但之后我得到一个“405(不允许的方法)”。

根据 Chrome 开发工具,两种方式都作为 GET 处理,即使它被指定为 POST(这是必需的)。有什么问题?

function sendButtonClick(){
    jQuery.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        username:'my app key',
        password:'my app secret',
        url: 'https://go.urbanairship.com/api/push/broadcast/',
        data: {"android": {"alert": "alerttest", "extra": {"extra test": "extra value test"}}},
        dataType: 'jsonp',
    });
};

提前致谢!

【问题讨论】:

  • 你不能跨域POST
  • docs.urbanairship.com/display/DOCS/Server%3A+Android+Push+API 的官方文档底部显示“POST to /api/push/broadcast/”。那我是不是误解了 POST 方面?我见过使用类似语法的其他示例。
  • 在常规桌面浏览器上,您不能跨域发布。我相信移动设备有一个例外 - 所以它引出了一个问题,您是在移动设备上还是在桌面上进行测试?
  • 我正在我的桌面上进行测试。我还有什么其他选择?我必须创建一个独立的应用程序吗?我希望能够通过 Urban Airship 从我的自定义 Web 界面发送推送通知。
  • 有些模拟器可以工作。否则,您可以将手机插入计算机并使用一些远程调试工具。不确定应用程序与网络界面的问题。

标签: jquery ajax json push-notification urbanairship.com


【解决方案1】:

您使用的服务器端技术是什么?你必须从那里开始。基本上,您不能通过桌面浏览器进行跨域调用。您可以执行此操作的方法是,使用有效负载调用您的服务器端方法,然后让服务器端发送通知。这是我编写的 c# 示例代码。

 public interface INotification
{
    void Set(string deviceId, string alert, int? badge, string sound);
}

public class BaseNotification
{

    public List<string> Aliases { get; set; }
    public List<string> Tags { get; set; }
}

 public class iOSNotification : BaseNotification, INotification
{
    public List<string> Device_Tokens { get; set; }
    public NotificationBody aps { get; set; }

    public iOSNotification()
    {
        Device_Tokens = new List<string>();
    }

    public void Set(string deviceId, string alert, int? badge, string sound)
    {
        Device_Tokens.Add(deviceId);
        aps = new NotificationBody
        {
            Alert = alert,
            Badge = badge.HasValue ? badge.Value : 0,
            Sound = sound
        };
    }
}

//in a static extensions
 public static string ToJSONString<T>(this IEnumerable<T> items)
   {
        var jsonString =  JsonConvert.SerializeObject(items, Formatting.Indented, new JsonSerializerSettings
            {
                ContractResolver = new LowerCaseContractResolver(),
                NullValueHandling = NullValueHandling.Ignore
            });

        jsonString = jsonString.Replace("\r\n", string.Empty);

        return jsonString;

    }



protected internal void SendPushNotification(List<INotification> payLoad, string uriKey) {

        var json = payLoad.ToJSONString();
        var Uri = GetAppSettings(uriKey);
        var encoding = new UTF8Encoding();

        var contentLength = encoding.GetByteCount(json);

        var request = (WebRequest)WebRequest.Create(Uri);

        request.Method = "POST";
        CredentialCache credentialCache = new CredentialCache();
        credentialCache.Add(new Uri(Uri), "Basic", GetCredentials());

        request.Credentials = credentialCache;

        request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(_username + ":" + _password)));
        request.ContentType = "application/json";
        request.ContentLength = contentLength;


        using (var stream = request.GetRequestStream()) {

            stream.Write(encoding.GetBytes(json), 0, contentLength);
            stream.Close();

            var response = request.GetResponse();

            response.Close();
        }

    }

【讨论】:

  • 好吧,所以我想这就是为什么 docs.urbanairship.com/display/DOCS/Server%3A+Libraries 中没有 JavaScript api 的原因。似乎唯一的工作方法是创建一个独立的应用程序。感谢您的意见!
  • 这一直是我们的想法。您需要创建一个服务器应用程序来执行此操作以访问城市飞艇 api。在某种程度上,它更安全,并且您不会在主应用程序 js 中输入密钥和密码。只是好奇,您使用的是什么服务器端技术?
  • 只是补充一下,您可以从支持它的现代桌面浏览器进行 cors 调用,但接收您的请求的服务器也需要允许它。因此,尽管可以完全按照您在此处尝试的操作,Urbanairship API 不支持它。
  • 我明白了,感谢您提供的信息。最后,我最终创建了一个简单的 C# ASP.NET 网页,在该网页中,我可以将 Web 界面与发生在代码隐藏文件中的服务器端推送结合起来。它基于此 stackoverflow.com/questions/2393725/… 。像魅力一样工作!
【解决方案2】:

您将无法在任何浏览器、移动设备或桌面上跨域发布。您最好的选择是在您的服务器上设置一个端点,该端点需要来自 jQuery 的 POST 请求(例如 yoursite.com/message/broadcast)。然后,在服务器上,对https://go.urbanairship.com/api/push/broadcast 进行 POST。当它响应时,将响应作为您的响应发回。

您最好将自己的 API 主密码保存在您的服务器上。

NOTE: You'll want to make sure you don't include the API password on your client. In fact, I suggest leaving the auth header out in the client, and then add it on your server before sending the request off to UrbanAirship. So even if you could POST cross-domain (aka you were building an iOS native Cocoa application), you're still better off keeping the secure credentials on your server instead of the device)

例如,使用Sails(javascript / Node.js 服务器):

// api/MessageController.js
module.exports = {
  broadcast: function (req,res) {

   // Your message for UrbanAirship should be sent as JSON in req.body
   // e.g. req.body === '{ "android": { "alert": "foo" } } '

    var httpRequest = require('request');
    httpRequest({
      url: 'https://go.urbanairship.com/api/push/broadcast/',
      json: 'true',
      auth: {
        'user': 'YOUR_API_KEY',
        'pass': 'YOUR_MASTER_SECRET',
        'sendImmediately': true
      },
      body: req.body
    }, function (err) {

      // Send confirmation back to jQuery of either success (200) or error (500)
      if (err) res.send(err, 500);
      else res.send(200);

    });
  }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多