---
title: "Perl之Net::APNS实现苹果消息推送"
author: "lzqustc"
date: "2017-10-18T16:26:42Z"
tags: ["Apple", "Perl"]
categories: ["移动开发"]
slug: "perl-net-apns"
draft: false
lastmod: "2017-10-18T16:26:42Z"
id: 2396832
url: "https://lzqustc.iteye.com/blog/2396832"
---

[Net::APNS is Apple Push Notification Service.](https://metacpan.org/pod/Net::APNS) Push message to iPhone and get unavalble-devicetoken.

 

苹果开发者官网说明：[The APNs provider API lets you send remote notification requests to APNs.](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html) 

 

Net::APNS模块已经封装了整个推送逻辑，调用者只需提供设备的deviceToken和要推送的消息即可。

举例如下：

use Net::APNS;

 

**sub net\_apns {**

     my $devicetoken = $\_\[0];

     my $content = $\_\[1];

     return 0 if($devicetoken eq "");

     return 0 if($content eq "");

 

     my $message; #用户自定义的内容

     my $message-&gt;{obj} = "apple";

     $message-&gt;{act} = "push";

 

     $content =  encode( "utf8", $content );

     $message-&gt;{content} = $content;

 

     my $APNS = Net::APNS-&gt;new; 

     # 提供相关证书，证书生成可参考[http://help.apple.com/xcode/mac/current/#/dev11b059073](http://help.apple.com/xcode/mac/current/#/dev11b059073)

     # 或者参考：[http://blog.sina.com.cn/s/blog\_4adf31ea010175wo.html](http://blog.sina.com.cn/s/blog_4adf31ea010175wo.html)

     my $Notifier = $APNS-&gt;notify({

          cert =&gt; "/var/www/apple/pushck.pem",

          key =&gt; "/var/www/apple/PushChatkey.pem",

          passwd =&gt; "123456"

     });

 

     $Notifier-&gt;devicetoken("$devicetoken"); 

     $Notifier-&gt;message("$content"); # 推送内容

     $Notifier-&gt;badge(1);     #ios手机里面的app右上角会出现红点且数字为1

     if(\_\_PACKAGE\__ eq "PRODUCT") { 

          $Notifier-&gt;sandbox(0);  # 是否使用沙盒测试环境， 0表示“否”

    } else {

          $Notifier-&gt;sandbox(1);  # 1表示“是”

     }

     $Notifier-&gt;sound('default'); 

     $Notifier-&gt;custom($message);  #用户自定义的内容

     # $Notifier-&gt;custom({custom\_key =&gt;'i am custom\_value'});

     my $result\_code = $Notifier-&gt;write;

     if ($result\_code) {

          return "send success";

     } else {

          return "send failed";

     } 

}