APNS有关于服务器端

如何制作apns证书在这里就不再说明了

从导出证书开始

首先导出两个 p12文件(cert.p12 key.p12) 把他们放在同一个文件夹(aaa)内

a.先打开终端,切换文件夹aaa下执行

openssl pkcs12 -clcerts -nokeys -out cert.pem -in cert.p12 

b.在执行的时候 将会让输入密码, 输入生成p12文件时对应的密码

openssl pkcs12 -nocerts -out key.pem -in key.p12

此时要注意终端的提示 第一次输入的密码 是生成p.12时候的密码,第二次第三次输入的密码是设置key.pem的密码。

c.如果需要对key不进行加密,执行下面语句

openssl rsa -in key.pem -out key.unencrypted.pem 

d.然后合并连个.pem文件,这个ck.pem就是服务端需要的证书了。

cat cert.pem key.unencrypted.pem > ck.pem 

此时,可以把生成的ck.pem 给服务器端的人员即可

这里我们要自己实现服务端 给客户端发送信息

下面我们生成php文件 ,这里不进行解释 直接上代码

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <title>APNS</title>
</head>
<body>
<?php
/**
 * @file apns.php
 * @synopsis  apple APNS class
 * @author Yee, <rlk002@gmail.com>
 * @version 1.0
 * @date 2012-09-17 11:27:59
 */
class APNS
{
const ENVIRONMENT_PRODUCTION = 0;
const ENVIRONMENT_SANDBOX = 1;
const DEVICE_BINARY_SIZE = 32;
const CONNECT_RETRY_INTERVAL = 1000000;
const SOCKET_SELECT_TIMEOUT = 1000000;
const COMMAND_PUSH = 1;
const STATUS_CODE_INTERNAL_ERROR = 999;
const ERROR_RESPONSE_SIZE = 6;
const ERROR_RESPONSE_COMMAND = 8;
const PAYLOAD_MAXIMUM_SIZE = 256;
const APPLE_RESERVED_NAMESPACE = 'aps';
protected $_environment;
protected $_providerCertificateFile;
protected $_rootCertificationAuthorityFile;
protected $_connectTimeout;
protected $_connectRetryTimes = 3;
protected $_connectRetryInterval;
protected $_socketSelectTimeout;
protected $_hSocket;
protected $_deviceTokens = array();
protected $_text;
protected $_badge;
protected $_sound;
protected $_customProperties;
protected $_expiryValue = 604800;
protected $_customIdentifier;
protected $_autoAdjustLongPayload = true;
protected $asurls = array('ssl://gateway.push.apple.com:2195','ssl://gateway.sandbox.push.apple.com:2195');
protected $_errorResponseMessages = array
(
    0   => 'No errors encountered',
    1 => 'Processing error',
    2 => 'Missing device token',
    3 => 'Missing topic',
    4 => 'Missing payload',
    5 => 'Invalid token size',
    6 => 'Invalid topic size',
    7 => 'Invalid payload size',
    8 => 'Invalid token',
    self::STATUS_CODE_INTERNAL_ERROR => 'Internal error'
);

function __construct($environment,$providerCertificateFile)
{
    if($environment != self::ENVIRONMENT_PRODUCTION && $environment != self::ENVIRONMENT_SANDBOX)
    {
        throw new Exception(
            "Invalid environment '{$environment}'"
        );
    }
    $this->_environment = $environment;

    if(!is_readable($providerCertificateFile))
    {
        throw new Exception(
            "Unable to read certificate file '{$providerCertificateFile}'"
        );
    }
    $this->_providerCertificateFile = $providerCertificateFile;

    $this->_connectTimeout = @ini_get("default_socket_timeout");
    $this->_connectRetryInterval = self::CONNECT_RETRY_INTERVAL;
    $this->_socketSelectTimeout = self::SOCKET_SELECT_TIMEOUT;
}

public function setRCA($rootCertificationAuthorityFile)
{
    if(!is_readable($rootCertificationAuthorityFile))
    {
        throw new Exception(
            "Unable to read Certificate Authority file '{$rootCertificationAuthorityFile}'"
        );
    }
    $this->_rootCertificationAuthorityFile = $rootCertificationAuthorityFile;
}

public function getRCA()
{
    return $this->_rootCertificationAuthorityFile;
}

protected function _connect()
{
    $sURL = $this->asurls[$this->_environment];
    $streamContext = stream_context_create(
        array
        (
            'ssl' => array
            (
                'verify_peer' => isset($this->_rootCertificationAuthorityFile),
                'cafile' => $this->_rootCertificationAuthorityFile,
                'local_cert' => $this->_providerCertificateFile
            )
        )
    );

    $this->_hSocket = @stream_socket_client($sURL,$nError,$sError,$this->_connectTimeout,STREAM_CLIENT_CONNECT, $streamContext);

    if (!$this->_hSocket)
    {
        throw new Exception
        (
            "Unable to connect to '{$sURL}': {$sError} ({$nError})"
        );
    }
    stream_set_blocking($this->_hSocket, 0);
    stream_set_write_buffer($this->_hSocket, 0);
    return true;
}

public function connect()
{
    $bConnected = false;
    $retry = 0;
    while(!$bConnected)
    {
        try
        {
            $bConnected = $this->_connect();
        }catch (Exception $e)
        {
            if ($nRetry >= $this->_connectRetryTimes)
            {
                throw $e;
            }else
            {
                usleep($this->_nConnectRetryInterval);
            }
        }
        $retry++;
    }
}

public function disconnect()
{
    if (is_resource($this->_hSocket))
    {
        return fclose($this->_hSocket);
    }
    return false;
}

protected function getBinaryNotification($deviceToken, $payload, $messageID = 0, $Expire = 604800)
{
    $tokenLength = strlen($deviceToken);
    $payloadLength = strlen($payload);

    $ret  = pack('CNNnH*', self::COMMAND_PUSH, $messageID, $Expire > 0 ? time() + $Expire : 0, self::DEVICE_BINARY_SIZE, $deviceToken);
    $ret .= pack('n', $payloadLength);
    $ret .= $payload;
    return $ret;
}

protected function readErrorMessage()
{
    $errorResponse = @fread($this->_hSocket, self::ERROR_RESPONSE_SIZE);
    if ($errorResponse === false || strlen($errorResponse) != self::ERROR_RESPONSE_SIZE)
    {
        return;
    }
    $errorResponse = $this->parseErrorMessage($errorResponse);
    if (!is_array($errorResponse) || empty($errorResponse))
    {
        return;
    }
    if (!isset($errorResponse['command'], $errorResponse['statusCode'], $errorResponse['identifier']))
    {
        return;
    }
    if ($errorResponse['command'] != self::ERROR_RESPONSE_COMMAND)
    {
        return;
    }
    $errorResponse['timeline'] = time();
    $errorResponse['statusMessage'] = 'None (unknown)';
    if (isset($this->_aErrorResponseMessages[$errorResponse['statusCode']]))
    {
        $errorResponse['statusMessage'] = $this->_errorResponseMessages[$errorResponse['statusCode']];
    }
    return $errorResponse;
}

protected function parseErrorMessage($errorMessage)
{
    return unpack('Ccommand/CstatusCode/Nidentifier', $errorMessage);
}

public function send()
{
    if (!$this->_hSocket)
    {
        throw new Exception
        (
            'Not connected to Push Notification Service'
        );
    }
    $sendCount = $this->getDTNumber();
    $messagePayload = $this->getPayload();
    foreach($this->_deviceTokens AS $key => $value)
    {
        $apnsMessage = $this->getBinaryNotification($value, $messagePayload, $messageID = 0, $Expire = 604800);
        $nLen = strlen($apnsMessage);
        $aErrorMessage = null;
        if ($nLen !== ($nWritten = (int)@fwrite($this->_hSocket, $apnsMessage)))
        {
            $aErrorMessage = array
            (
                'identifier' => $key,
                'statusCode' => self::STATUS_CODE_INTERNAL_ERROR,
                'statusMessage' => sprintf('%s (%d bytes written instead of %d bytes)',$this->_errorResponseMessages[self::STATUS_CODE_INTERNAL_ERROR], $nWritten, $nLen)
            );
        }
    }
}

public function addDT($deviceToken)
{
    if (!preg_match('~^[a-f0-9]{64}$~i', $deviceToken))
    {
        throw new Exception
        (
            "Invalid device token '{$deviceToken}'"
        );
    }
    $this->_deviceTokens[] = $deviceToken;
}

public function getDTNumber()
{
    return count($this->_deviceTokens);
}

public function setText($text)
{
    $this->_text = $text;
}

public function getText()
{
    return $this->_text;
}

public function setBadge($badge)
{
    if (!is_int($badge))
    {
        throw new Exception
        (
            "Invalid badge number '{$badge}'"
        );
    }
    $this->_badge = $badge;
}

public function getBadge()
{
    return $this->_badge;
}

public function setSound($sound = 'default')
{
    $this->_sound = $sound;
}

public function getSound()
{
    return $this->_sound;
}

public function setCP($name, $value)
{
    if ($name == self::APPLE_RESERVED_NAMESPACE)
    {
        throw new Exception
        (
            "Property name '" . self::APPLE_RESERVED_NAMESPACE . "' can not be used for custom property."
        );
    }
    $this->_customProperties[trim($name)] = $value;
}

protected function _getPayload()
{
    $aPayload[self::APPLE_RESERVED_NAMESPACE] = array();

    if (isset($this->_text))
    {
        $aPayload[self::APPLE_RESERVED_NAMESPACE]['alert'] = (string)$this->_text;
    }
    if (isset($this->_badge) && $this->_badge > 0)
    {
        $aPayload[self::APPLE_RESERVED_NAMESPACE]['badge'] = (int)$this->_badge;
    }
    if (isset($this->_sound))
    {
        $aPayload[self::APPLE_RESERVED_NAMESPACE]['sound'] = (string)$this->_sound;
    }

    if (is_array($this->_customProperties))
    {
        foreach($this->_customProperties as $propertyName => $propertyValue)
        {
            $aPayload[$propertyName] = $propertyValue;
        }
    }
    return $aPayload;
}

public function setExpiry($expiryValue)
{
    if (!is_int($expiryValue))
    {
        throw new Exception
        (
            "Invalid seconds number '{$expiryValue}'"
        );
    }
    $this->_expiryValue = $expiryValue;
}

public function getExpiry()
{
    return $this->_expiryValue;
}

public function setCustomIdentifier($customIdentifier)
{
    $this->_customIdentifier = $customIdentifier;
}

public function getCustomIdentifier()
{
    return $this->_customIdentifier;
}

public function getPayload()
{
    $sJSONPayload = str_replace
    (
        '"' . self::APPLE_RESERVED_NAMESPACE . '":[]',
        '"' . self::APPLE_RESERVED_NAMESPACE . '":{}',
        json_encode($this->_getPayload())
    );
    $nJSONPayloadLen = strlen($sJSONPayload);

    if ($nJSONPayloadLen > self::PAYLOAD_MAXIMUM_SIZE)
    {
        if ($this->_autoAdjustLongPayload)
        {
            $maxTextLen = $textLen = strlen($this->_text) - ($nJSONPayloadLen - self::PAYLOAD_MAXIMUM_SIZE);
            if ($nMaxTextLen > 0)
            {
                while (strlen($this->_text = mb_substr($this->_text, 0, --$textLen, 'UTF-8')) > $maxTextLen);
                return $this->getPayload();
            }else
            {
                throw new Exception
                (
                    "JSON Payload is too long: {$nJSONPayloadLen} bytes. Maximum size is " .
                    self::PAYLOAD_MAXIMUM_SIZE . " bytes. The message text can not be auto-adjusted."
                );
            }
        }else
        {
            throw new Exception
            (
                "JSON Payload is too long: {$nJSONPayloadLen} bytes. Maximum size is " .
                self::PAYLOAD_MAXIMUM_SIZE . " bytes"
            );
        }
    }
    return $sJSONPayload;
}
}

?>
<?php
date_default_timezone_set('PRC');
echo "we are young,test apns.  -".date('Y-m-d h:i:s',time());

$rootpath = 'entrust_root_certification_authority.pem';  //ROOT证书地址  
$cp = 'ck.pem';  //provider证书地址  
$apns = new APNS(1,$cp);
try
{
    //$apns->setRCA($rootpath);  //设置ROOT证书  
$apns->connect(); //连接  
$apns->addDT('输入你的deviceToken');  //加入deviceToken  
$apns->setText('这是一条测试信息');  //发送内容  
$apns->setBadge(1);  //设置图标数  
$apns->setSound();  //设置声音  
$apns->setExpiry(3600);  //过期时间  
$apns->setCP('custom operation',array('type' => '1','url' => 'http://www.baidu.com'));  //自定义操作  
$apns->send();  //发送  
echo ' sent ok';
}catch(Exception $e)
{
    echo $e;
  }
 ?>

</body>
</html>  

把生成好的apnsServer.php文件和ck.pem文件放到一个文件夹内

打开终端 执行 php apnsServer.php

php文件中需要更换成自己的deviceToken
php文件中需要更换成自己的deviceToken
php文件中需要更换成自己的deviceToken

重要的事情说三遍

这时候你的app将受到发来的推送

开始调试吧 小伙伴们

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,841评论 5 472
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,415评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,904评论 0 333
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,051评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,055评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,255评论 1 278
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,729评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,377评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,517评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,420评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,467评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,144评论 3 317
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,735评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,812评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,029评论 1 256
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,528评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,126评论 2 341

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,566评论 18 139
  • 前言:现在第三方推送也很多 ,比如极光,融云,信鸽,其原理也是相同利用APNS推送机制 ,前段公司让做自己的推送,...
    _方丈阅读 21,219评论 15 133
  • 前言:现在第三方推送也很多 ,比如极光,融云,信鸽,其原理也是相同利用APNS推送机制 ,前段公司让做自己的推送,...
    OliviaZqy阅读 2,915评论 0 5
  • 小的时候,我们村里有个孩子王,村里的孩子都是他带着玩。他鬼点子多,发明了一种暗号,用一种学狼叫的声音来聚集村里的孩...
    莫名就有风阅读 161评论 0 0
  • 这是一份迟到的总结,本以为2014的总结能够在2014的最后几个小时内完成;却没想到因为凑热闹想去外滩看个跨年灯光...
    17号冷锋阅读 198评论 0 2