极光推送 java,php版demo

java实现简单的极光推送demo:

1,导入jpush-client-3.2.9.jar的jar包到WebContent/WEB-INFO/lib里面

2,导入util类;代码如下

package com.jstyle.utils.JPush;

import java.util.Date;

import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;  
 
import cn.jpush.api.JPushClient;  
import cn.jpush.api.common.resp.APIConnectionException;  
import cn.jpush.api.common.resp.APIRequestException;  
import cn.jpush.api.push.PushResult;  
import cn.jpush.api.push.model.Message;  
import cn.jpush.api.push.model.Options;  
import cn.jpush.api.push.model.Platform;  
import cn.jpush.api.push.model.PushPayload;  
import cn.jpush.api.push.model.audience.Audience;  
import cn.jpush.api.push.model.audience.AudienceTarget;  
import cn.jpush.api.push.model.notification.AndroidNotification;  
import cn.jpush.api.push.model.notification.IosNotification;  
import cn.jpush.api.push.model.notification.Notification;
import cn.jpush.api.report.MessagesResult;
import cn.jpush.api.report.ReceivedsResult;
import cn.jpush.api.schedule.ScheduleResult;  
 
public class SendMessage{  
     protected static final Logger LOG = LoggerFactory.getLogger(SendMessage.class);  
      
    public  static JPushClient jpushClient=null;  
    @SuppressWarnings("deprecation")
    public static void testSendPush(String appKey ,String masterSecret,String msg ) {  
         jpushClient = new JPushClient(masterSecret, appKey);
         PushPayload payload=null;
         Audience  ad=Audience.all();
         Platform plat=Platform.android();
         payload=buildPushObject_android_tag_alertWithTitle(plat,ad,msg);
        
         try {  
              System.out.println(payload.toString());  
              PushResult result = jpushClient.sendPush(payload);  
              System.out.println(result+"................................");  
              int num=result.sendno;
              long msg_id=result.msg_id;
             // jpushClient.g
              ReceivedsResult results = jpushClient.getReportReceiveds(msg_id+"");
              LOG.info("Got result - " + result);  
                
          } catch (APIConnectionException e) {  
              LOG.error("Connection error. Should retry later. ", e);
                
          } catch (APIRequestException e) {  
              LOG.error("Error response from JPush server. Should review and fix it. ", e);  
              LOG.info("HTTP Status: " + e.getStatus());  
              LOG.info("Error Code: " + e.getErrorCode());  
              LOG.info("Error Message: " + e.getErrorMessage());  
              LOG.info("Msg ID: " + e.getMsgId());  
          }
    }  
      
    
    /**
     * ios有url广播所有人
     */
    public static PushPayload pushData(Platform plat,Audience ad,String msg) {  
        PushPayload payload =
         PushPayload.newBuilder()  
                .setPlatform(plat)  
                .setAudience(ad)  //Audience.alias("12")
                .setNotification(Notification.newBuilder()  
                        .addPlatformNotification(IosNotification.newBuilder()  
                                .setAlert(msg)  
                                .setBadge(1)  
                                .setSound("happy")  
                                .addExtra("from", "JPush")
                                .build())  
                        .build())  
                 .setMessage(Message.content(msg))  
                 .setOptions(Options.newBuilder()  
                         .build())  
                 .build();  
        
        return payload;
    }
    public static PushPayload buildPushObject_all_alias_alert(String msg) {  
        return PushPayload.newBuilder()  
                .setPlatform(Platform.all())//设置接受的平台  
                .setAudience(Audience.all())//Audience设置为all,说明采用广播方式推送,所有用户都可以接收到  
                .setNotification(Notification.alert(msg))  
                .build();  
    }  
    public static PushPayload buildPushObject_android_tag_alertWithTitle(Platform plat,Audience ad,String msg) {  
        return PushPayload.newBuilder()  
                .setPlatform(Platform.android())  
                .setAudience(ad)  //Audience.alias("12")
                .setNotification(Notification.newBuilder()  
                        .addPlatformNotification(AndroidNotification.newBuilder()  
                                .setAlert(msg)  
                                .addExtra("from", "JPush")
                                .addExtra("url","http://www.baidu.com")
                                .build())  
                        .build())  
                 .setMessage(Message.content(msg))  
                /* .setOptions(Options.newBuilder()  
                         .setApnsProduction(isDev)  
                         .build())  */
                 .build();   /*PushPayload.newBuilder()  
                .setPlatform(Platform.android())  
                .setAudience(ad)  
                .setNotification(Notification.android(title, content, null))  
                .build();  */
    }  
      
    public static PushPayload buildPushObject_android_and_ios() {  
        return PushPayload.newBuilder()  
                .setPlatform(Platform.android_ios())  
                .setAudience(Audience.tag("tag1"))  
                .setNotification(Notification.newBuilder()  
                        .setAlert("alert content")  
                        .addPlatformNotification(AndroidNotification.newBuilder()  
                                .setTitle("Android Title").build())  
                        .addPlatformNotification(IosNotification.newBuilder()  
                                .incrBadge(1)  
                                .addExtra("extra_key", "extra_value").build())  
                        .build())  
                .build();  
    }  
      
    /**
     * ios有url广播所有人
     */
    public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage(String msg,String url,Integer msgtype ,String isimage) {  
        return PushPayload.newBuilder()  
                .setPlatform(Platform.all())  
                .setAudience(Audience.alias("12"))  
                .setNotification(Notification.newBuilder()  
                        .addPlatformNotification(IosNotification.newBuilder()  
                                .setAlert(msg)  
                                .setBadge(1)  
                                .setSound("happy")  
                                .addExtra("from", "JPush")
                                .addExtra("url",url)
                               // .addExtra("gid", "2aa5db8481647000358218e35c35894b")
                                .addExtra("type", msgtype) //1 article 2 spu //0 我的信息界面
                                .addExtra("isimage", isimage)
                                .build())  
                        .build())  
                 .setMessage(Message.content(msg))  
                 .setOptions(Options.newBuilder()  
                         .setApnsProduction(false)  
                         .build())  
                 .build();  
    }  
    
    
   
    
    /**
     * 无别名ios
     * @return
     */
    public static PushPayload buildPushObject_ios_nonetagtWithExtrasAndMessage(String msg,String goodsorarticle,Integer msgtype) {  
        return PushPayload.newBuilder()  
                .setPlatform(Platform.all())  
               // .setAudience(Audience.alias("12"))  
                .setNotification(Notification.newBuilder()  
                        .addPlatformNotification(IosNotification.newBuilder()  
                                .setAlert(msg)  
                                .setBadge(1)  
                                .setSound("happy")  
                                .addExtra("from", "JPush")
                                .addExtra("url",goodsorarticle)
                               // .addExtra("gid", "2aa5db8481647000358218e35c35894b")
                                .addExtra("type", "2") //1 article 2 spu //0 我的信息界面
                                .build())  
                        .build())  
                 .setMessage(Message.content(msg))  
                 .setOptions(Options.newBuilder()  
                         .setApnsProduction(false)  
                         .build())  
                 .build();  
    }  
    
    
    
    
    
    
      
    public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras() {  
        return PushPayload.newBuilder()  
                .setPlatform(Platform.android_ios())  
                .setAudience(Audience.newBuilder()  
                        .addAudienceTarget(AudienceTarget.tag("tag1", "tag2"))  
                        .addAudienceTarget(AudienceTarget.alias("alias1", "alias2"))  
                        .build())  
                .setMessage(Message.newBuilder()
                        .addExtra("from", "JPush")  
                        .build())  
                .build();  
    }  
    
    
    public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras1(Integer [] arr) {  
        return PushPayload.newBuilder()  
                .setPlatform(Platform.android_ios())  
                .setAudience(Audience.newBuilder()  
                        .addAudienceTarget(AudienceTarget.tag("tag",arr.toString()))
                        
                        //.addAudienceTarget(AudienceTarget.alias("alias1", "alias2"))  
                        .build())  
                .setMessage(Message.newBuilder()  
                        .setMsgContent("视频即将开始,请您马上观看")  
                        .addExtra("from", "JPush")  
                        .build())  
                .build();  
    }  
}  

3,控制器调用:

package com.jstyle.web.controller.home.threepointzero;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jstyle.common.RequestConstants;
import com.jstyle.utils.JPush.SendMessage;

@Controller
@RequestMapping(value=RequestConstants.JPUSH)
public class SendMessageController {
	@RequestMapping(value = RequestConstants.SENDMSG, method = RequestMethod.GET)
	@ResponseBody
	public  String sendHeadMessage(HttpServletRequest request,String sendtime) {
		String appKey1="你的appkey";
		String masterSecret1="你的master_secret";
		
		/*if(jpushway==2){//定时推送
			SendScheduleMessage.sendSchedulePush(appKey, masterSecret, msg.getMsg(), msg.getEqutype(), msg.getTargetpsn(),ali,msgurl,msg.getMsgtype(), sendtime,isimage);
		}else if(jpushway==1){//及时推送
			SendMessage.testSendPush(appKey,masterSecret,msg.getMsg(),msg.getEqutype(),msg.getTargetpsn(),ali,msgurl,msg.getMsgtype(),isimage);
		}*/
		//SendMessage.testSendPush(appKey,masterSecret,msg.getMsg(),msg.getEqutype(),msg.getTargetpsn(),ali,msgurl,msg.getMsgtype());
		Map<String,Object> map=new HashMap<>();
		/*map.put("ctime", new Date());
		if(sendtime!=null && sendtime!="" && sendtime.length()>0){
			msg.setSendtime(sendtime);
		}else{
			msg.setSendtime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
		}*/
		SendMessage.testSendPush(appKey1,masterSecret1,"大家好啊");
		return "1";
	}
}

php简单的推送demo:

1,方法类文件放到Application\Home\Common中

<?php
namespace Home\Common;  
class Jpush{  
    
    private $app_key = '你的appkey';            //待发送的应用程序(appKey),只能填一个。  
    private $master_secret = '你的master_secret';      //主密码  
    private $url = "https://api.jpush.cn/v3/push";            //推送的地址  
   
    //若实例化的时候传入相应的值则按新的相应值进行  
    public function __construct($app_key=null, $master_secret=null,$url=null) {  
        if ($app_key) $this->app_key = $app_key;  
        if ($master_secret) $this->master_secret = $master_secret;  
        if ($url) $this->url = $url;  
    }  
   
    /*  $receiver 接收者的信息 
        all 字符串 该产品下面的所有用户. 对app_key下的所有用户推送消息 
        tag(20个)Array标签组(并集): tag=>array('昆明','北京','曲靖','上海'); 
        tag_and(20个)Array标签组(交集): tag_and=>array('广州','女'); 
        alias(1000)Array别名(并集): alias=>array('93d78b73611d886a74*****88497f501','606d05090896228f66ae10d1*****310'); 
        registration_id(1000)注册ID设备标识(并集): registration_id=>array('20effc071de0b45c1a**********2824746e1ff2001bd80308a467d800bed39e'); 
     
        $content 推送的内容。 
        $extras  附加字段  array类型 
        $m_time 保存离线时间的秒数默认为一天(可不传)单位为秒 
    */  
    public function push($receiver='all', $title='', $content='', $extras, $m_time='86400'){  
        $base64=base64_encode("$this->app_key:$this->master_secret");  
        $header=array("Authorization:Basic $base64","Content-Type:application/json");  
        $data = array();  
        $data['platform'] = 'android';          //目标用户终端手机的平台类型android,ios,winphone  
        $data['audience'] = $receiver;          //目标用户  
        //发送通知  
        $data['notification'] = array(  
            //统一的模式--标准模式  
            //"alert"=>$content,     
            //安卓自定义  
            "android"=>array(  
                "alert"=>$content,  
                "title"=>$title,  
                "builder_id"=>1,  
                "extras"=>$extras  
            ),  
            //ios的自定义  
            /*"ios"=>array(  
                // "alert"=>$content,  
                "badge"=>"1",  
                "sound"=>"default",  
                // "extras"=>array("type"=>$m_type, "txt"=>$m_txt)  
            ),*/  
        );  
   
        //自定义信息  
        $data['message'] = array(  
            "msg_content"=>$content,  
            "extras"=>$extras  
        );  
   		//echo $m_time;die;
        //附加选项  
        $data['options'] = array(  
            "sendno"=>time(),  
            "time_to_live"=>$m_time,      //保存离线时间的秒数默认为一天  
            "apns_production"=>0,        //指定 APNS 通知发送环境:0开发环境,1生产环境。  
        );  
        $param = json_encode($data);  
        $res = $this->push_curl($param,$header);  
        //var_dump($res);die;  
        if($res){       //得到返回值--成功已否后面判断  
            return $res;  
        }else{          //未得到返回值--返回失败  
            return false;  
        }  
    }  
   
    //推送的Curl方法  
    public function push_curl($param,$header) {  
        if (empty($param)) { return false; }  
        $postUrl = $this->url;  
        $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;  
    }  
}  
  
?>  

2,控制器调用:

<?php
namespace Home\Controller;
use Think\Controller;
use Home\Common\JPush;
class JPushController extends Controller {
	public function pushMess(){  
	    //vendor('Jpush/Jpush');  
	    $pushObj = new Jpush();  
	    //组装需要的参数  
	    $receive = 'all';     //全部  
	    //$receive = array('tag'=>array('1','2','3'));      //标签  
	    //$receive = array('alias'=>array('111'));    //别名  
	    $title = "闲聊话题"; //推送标题 (java会默认报名)
	    $content = "啥时候下班啊";  //推送内容
	    $m_time = '86400';        //离线保留时间  
	    $extras = array("url"=>"http://www.baidu.com","type"=>"1");   //自定义数组  
	    //调用推送,并处理  
	    $result = $pushObj->push($receive,$title,$content,$extras,$m_time);  
	   // var_dump($result);die;
	    if($result){  
	        $res_arr = json_decode($result, true);

	        if(isset($res_arr['error'])){   //如果返回了error则证明失败  
	            //错误信息 错误码  
	            echo $res_arr['error']['message'];die;
	            $this->error($res_arr['error']['message'].':'.$res_arr['error']['code'],U('Jpush/index'));      
	        }else{  
	            //处理成功的推送......  
	            //可执行一系列对应操作~ 
	            echo "推送成功";die; 
	            $this->success('推送成功~');  
	        }  
	    }else{      //接口调用失败或无响应  
	        $this->error('接口调用失败或无响应~');
	    }  
	}
	public function a(){
		echo time();
	}
}
3,运行ok

demo下载地址:点击打开链接 

猜你喜欢

转载自blog.csdn.net/m0_37865510/article/details/79925748