个推消息推送RestAPI版

2019-09-19 10:43:08 浏览数 (1)

1.权鉴获取Token

代码语言:javascript复制
 /**
     * 个推获取权鉴Token
     * @return bool
     */
    public static function getAuthToken()
    {
        require_once(__DIR__ . '/../../common/libs/requests/library/Requests.php');
        Requests::register_autoloader();
        $headers = array(
            'Content-Type' => 'application/json'
        );
        $appID = Yii::$app->params['gt_app_id'];
        $appKey = Yii::$app->params['gt_app_key'];
        $timestamp = Func::getMsecTime();
        $masterSecret = Yii::$app->params['gt_master_secret'];
        $sign = hash('sha256',$appKey.$timestamp.$masterSecret);
        $data = [
            'sign' => $sign,
            'timestamp' => $timestamp,
            'appkey' => $appKey
        ];
        $jsonData = json_encode($data);
        $postUrl = 'https://restapi.getui.com/v1/'.$appID.'/auth_sign';
        $response = Requests::post($postUrl, $headers, $jsonData);
        $postData = json_decode($response->body);
        if($postData->result == 'ok'){
            return $postData->auth_token;
        }else{
            return false;
        }
    }

2.向客户端推送消息

代码语言:javascript复制
/**
     * 向客户端推送消息
     * @param $title
     * @param $content
     * @return bool
     */
    public static function pushMessage($title,$content)
    {
        require_once(__DIR__ . '/../../common/libs/requests/library/Requests.php');
        Requests::register_autoloader();
        $authToken = Func::getAuthToken();
        $headers = array(
            'Content-Type' => 'application/json',
            'authtoken' => $authToken
        );
        $data = [
            'message' => [
                'appkey' => Yii::$app->params['gt_app_key'],
                'is_offline' => false,
                'msgtype' => 'notification',
            ],
            //参数:link notification
            'notification' => [
                'style' => [
                    'type' => 0,
                    'text' => $content,
                    'title' => $title,
                    'logourl' => 'https://img.yuanmabao.com/zijie/pic/2019/09/19/oqae1glgdma.png'
                ],
                //'url' => 'http://www.baidu.com',
            ],
            'requestid' => Func::GenSecret(20,1)
        ];
        $jsontData = json_encode($data);
        $response = Requests::post('https://restapi.getui.com/v1/'.Yii::$app->params['gt_app_id'].'/push_app', $headers, $jsontData);
        $postData = json_decode($response->body);
        if($postData->result == 'ok'){
            return true;
        }else{
            return false;
        }
    }

0 人点赞