s_key = $s_key; } /** * 发送消息 * @param $topic 分组 * @param $content 内容 * @return array|mixed */ public function sendMsg($topic,$content){ $param = [ 'body'=>$content ]; return $this->curl("/v1/messages/".$topic,"POST",json_encode($param)); } /** * 发送消息 * @param $topic 分组 * @param $content 内容 * @return array|mixed */ public function delMsg($topic,$uuid){ return $this->curl("/v1/historys/".$topic."/uuid/".$uuid,"DELETE"); } /** * 推送消息到某个用户 * @param $topic 分组 * @param $content 内容 * @return array|mixed */ public function sendMsgToUser($clientId,$content){ $param = [ 'body'=>$content ]; return $this->curl("/v1/messages/p2p/".$clientId,"POST",json_encode($param)); } /** * 获取在线用户 * 默认skip num 为0 只返回用户数量 * @param $topic * @param $skip 跳过多少条记录 * @param $num 查询多少条记录 * @return array|mixed */ public function getOnlineUser($topic,$skip=0,$num=0){ return $this->curl("/v1/topics/".$topic."/users?skip=".$skip."&num=".$num); } private function curl($path,$method="GET",$content="",$expire=3600,$timeout=60){ $ch = curl_init(); $expire = time() + $expire; if(($method == "POST" || $method == "PUT") && !empty($content)){ $contentMd5 = md5($content); $str = $method."\n".$path."\n".$expire."\n".$contentMd5."\n"; }else{ $str = $method."\n".$path."\n".$expire."\n"; } $query_url = $this->host.$path; curl_setopt($ch,CURLOPT_URL,$query_url); curl_setopt($ch,CURLOPT_HEADER,false); curl_setopt($ch,CURLOPT_AUTOREFERER,true); curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true); curl_setopt($ch,CURLOPT_FRESH_CONNECT,true); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); curl_setopt($ch,CURLOPT_TIMEOUT,$timeout); // curl_setopt($ch,CURLOPT_USERAGENT,$useragent); curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); curl_setopt($ch,CURLOPT_BINARYTRANSFER,true); curl_setopt($ch,CURLOPT_CUSTOMREQUEST,$method); // curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); if($method == 'POST') { curl_setopt($ch,CURLOPT_POST,true); curl_setopt($ch,CURLOPT_POSTFIELDS,$content); } else if($method == 'PUT') { curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_POSTFIELDS,$content); } $authorization = 'Authorization: dms '.$this->s_key; //print_r($authorization);exit(); $header = array($authorization,'AD-Expire: '.$expire,'Content-Type: application/json'); curl_setopt($ch,CURLOPT_HTTPHEADER, $header); //execute post $response = curl_exec($ch); //get response code $response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //close connection curl_close($ch); //return result if($response_code == 200 || $response_code == 201 || $response_code == 204) { $rst = json_decode(trim($response),true); } else { $rr = json_decode(trim($response),true); if($rr) { $rst = $rr; } else { $rst = array( 'Flag'=>$response_code, 'FlagString'=>trim($response) ); } } return $rst; } }