//------------------------------------------------------------------------------
// 푸쉬발송할 서버쪽 php 스크립트.
// 인터넷에서는 모두 curl 사용한 소스만 있는데.
// 우리서버에 curl 이 안깔려있어서, 그냥 fsockopen 으로 연결함.
//------------------------------------------------------------------------------
$msg = "푸쉬할 메세지...";
$send_time = date('YmdHis');
$timeout = 5;
$gcm_api_key = "API KEY. 알파벳+숫자로 이루어진거";

$gcm_data = array('registration_ids'=>array($push_key),
                  'time_to_live'=>60,
                  'data'=>array('msg'=>$msg,
                                'lecture_code'=>$lecture_code,
                                'teacher_code'=>$teacher_code,
                                'notice'=>"",
                                'send_time'=>$send_time));

$fp = fsockopen("ssl://android.googleapis.com", 443, $errno, $errstr, $timeout);
if(!$fp)
{
  echo "RET_CODE=FALSE\n";
  echo "RET_MSG=Fail to connect google [".$errno."] [".$errstr."]\n";
  writeLog("FALSE", "Fail to connect google  GCM [".$errno."] [".$errstr."]");
  exit;
}

fputs($fp, "POST /gcm/send HTTP/1.0\r\n".
           "Host: android.googleapis.com\r\n".
           "Content-Type: application/json\r\n".
           "Content-length: ".strlen(json_encode($gcm_data))."\r\n".
           "Authorization: key=".$gcm_api_key."\r\n\r\n".
           json_encode($gcm_data) . "\r\n\r\n");

$response = "";
while(!feof($fp))
{
  $response .= fgets($fp);
}
fclose($fp);

// GCM 응답에서, 헤더를 걷어낸다.
$body_index = strpos($response, "\r\n\r\n");
if($body_index === FALSE)
{
  echo "RET_CODE=FALSE\n";
  echo "RET_MSG=GCM response error\n";
  writeLog("FALSE", "GCM Send fail\n".$response);
  exit;
}

// GCM 응답에서, 푸쉬 성공한 갯수를 가져온다.
$response_body = substr($response, $body_index + 4);
$response_json = json_decode($response_body);
$success_count = $response_json->{'success'};
if($success_count <= 0)
{
  // 앱을 지운 사용자에게, gcm 을 보내면, 
  // NotRegistered 에러를 리턴받게 된다.
  $err_obj = $response_json->{'results'}[0];
  $err_msg = $err_obj->{'error'};
  echo "RET_CODE=FALSE\n";
  echo "RET_MSG=GCM Send fail\n";
  writeLog("FALSE", "GCM Send fail : ".$err_msg);
  exit;
}

echo "RET_CODE=TRUE\n";
echo "RET_MSG=\n";
writeLog("TRUE", "push send OK. android GCM");
exit;


반응형

'Android 초보' 카테고리의 다른 글

안드로이드, runOnUiThread, 배경화면설정  (0) 2014.07.04
HttpURLConnection getInputStream FileNotFoundException  (0) 2014.07.04
GCM. 안드로이드앱  (0) 2014.07.04
GCM 준비. 안드로이드앱  (0) 2014.07.04
GCM 준비  (0) 2014.07.04
Posted by 돌비
,