define('appid','1009*****'); //APP ID
define('appsec','c2910c5bcc905a5729fd********'); //APP SECRET
$tokenfile = fopen("token.txt", "r");
$token=fgets($tokenfile);
fclose($tokenfile);
$device=$_GET['device'];
$title=$_GET['title'];
$message=$_GET['message'];
if(empty($title)){exit('no message!');};
if(empty($token)){gettoken();};
if(empty($device)){$device='0866375047001440300****';}; //app获取到的设备码
$work=sendmsg($title,$message,$device);
if (strstr($work,'timeout')){
gettoken(); //先尝试发送消息,如果失败再重新获取令牌
$work=sendmsg($title,$message,$device);
};
exit($work);
function sendmsg($title,$message,$device){
$date=date_create();
$tokenfile = fopen("token.txt", "r");
$token=fgets($tokenfile);
fclose($tokenfile);
$push='access_token=' . urlencode($token) . '&nsp_svc=openpush.message.api.send&nsp_ts=' . date_timestamp_get($date) . '&device_token_list=' . urlencode('["' . $device . '"]') . '&payload=' . urlencode('{"hps":{"msg":{"type":1,"body":{"isAt":0,"senderType":"1","type":"Mojo-Sys","title":"' . $title . '","message":"' . $message . '","msgId":' . date_timestamp_get($date) . '}}}}');
$result=ssl_post($push,'https://api.push.hicloud.com/pushsend.do?nsp_ctx=' . urlencode('{"ver":"1","appId":"' . appid . '"}') );
return $result;
}
function gettoken(){
$token=json_decode(ssl_post('grant_type=client_credentials&client_secret=' . appsec . '&client_id=' . appid,'https://login.cloud.huawei.com/oauth2/v2/token'),true);
$tokenfile = fopen("token.txt", "w");
try{
fwrite($tokenfile, $token['access_token']);
}
catch(Exception $e){
exit($token);
}
fclose($tokenfile);
return $token['access_token'];
}
function ssl_post($data,$url,$post=1){
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_POST, $post);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$tmpInfo = curl_exec($curl);
if (curl_errno($curl)) {
echo 'Errno'.curl_error($curl);
}
curl_close($curl);
return $tmpInfo;
}