版本 thinkphp5.0 jpush 3.5
描述:jpush结合thinkphp的安装与使用
范围:适合所有php开发者使用
一、安装jpush 极光推送
在composer的配置文件中加入
"require": {
"jpush/jpush": "^3.5"
}
使用composer 安装极光推送
cmd 命令
composer install 或者 composer update
安装依赖以后 进入步骤二。
二、新建极光推送服务 用于后续调用
<?php
/**
* 激光推送服务
*/
namespace service;
class JpushServer
{
/**
* @param $content 推送的内容。
* @param $receiver 接受者信息
* @param string $m_type 推送附加字段的类型(可不填) http,tips,chat....
* @param string $m_txt 推送附加字段的类型对应的内容(可不填) 可能是url,可能是一段文字。
* @return bool|mixed|string
*/
public static function send_msg($content='这是一条默认的信息,来自极光的推送!',$receiver='all',$m_type='',$m_txt=''){
vendor('jpush.jpush.autoload');//引入极光推送扩展 这里的jpush.jpush是你的vendor下极光推送的安装目录。
$config = '';//配置你的相关配置包括key secret 离线时间 发送环境等;注意是个数组。
$app_key = $config['jpush_key'];
$master_secret = $config['jpush_secret'];
$m_time = intval($config['jpush_time']);
$base64=base64_encode("$app_key:$master_secret");
$header=array("Authorization:Basic $base64","Content-Type:application/json");
$data = array();
$data['platform'] = 'all'; //目标用户终端手机的平台类型android,ios,winphone
$data['audience'] = $receiver; //目标用户
$data['notification'] = array(
//统一的模式--标准模式
"alert"=>$content,
//安卓自定义
"android"=>array(
"alert"=>$content,
"title"=>"",
"builder_id"=>1,
"extras"=>array("type"=>$m_type, "txt"=>$m_txt)
),
//ios的自定义
"ios"=>array(
// "alert"=>$content,
"badge"=>"1",
"sound"=>"default",
// "extras"=>array("type"=>$m_type, "txt"=>$m_txt)
),
);
//苹果自定义---为了弹出值方便调测
$data['message'] = array(
"msg_content"=>$content,
"extras"=>array("type"=>$m_type, "txt"=>$m_txt)
);
//附加选项
$data['options'] = array(
"sendno"=>time(),
"time_to_live"=>$m_time, //保存离线时间的秒数默认为一天
"apns_production"=>$config['jpush_ambient'], //指定 APNS 通知发送环境:0开发环境,1生产环境。
);
$param = json_encode($data);
$res = self::push_curl($param,$header,$config['jpush_url']);
if($res){ //得到返回值--成功已否后面判断
return $res;
}else{ //未得到返回值--返回失败
return false;
}
}
//推送的Curl方法
public static function push_curl($param="",$header="",$postUrl) {
if (empty($param)) { return false; }
$curlPost = $param;
$ch = curl_init(); //初始化curl
curl_setopt($ch, CURLOPT_URL,$postUrl); //抓取指定网页
curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
curl_setopt($ch, CURLOPT_HTTPHEADER,$header); // 增加 HTTP Header(头)里的字段
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 终止从服务端进行验证
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$data = curl_exec($ch); //运行curl
curl_close($ch);
return $data;
}
}
注释:位置 在extend中或自定义的目录下声明即可 也可以封装成函数调用
三、使用
首先引入空间
use server/JpushServer;
其次在方法中调用
JpushServer::send_msg();//记得传参数