调用php脚本作为插入db的新记录

时间:2014-08-27 10:05:26

标签: php mysql push-notification

我只是为推送通知创建一个Web服务。我这是我的代码 -

<?php


// gcm api KEY FOR PUSH NOTIFICATION
define( 'API_ACCESS_KEY', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ123456' );
// CONNECT DB
$dbhandle = mysql_connect("localhost", "admin", "admin") or die(mysql_error()) ; 
$selected =  mysql_select_db("bdname" ,$dbhandle) or die(mysql_error()); 

$query4=mysql_query("SELECT * FROM `table_name` ORDER BY id DESC LIMIT 0,1");
$row1=mysql_fetch_array($query4);

// static gcm registration id
$reg = 'APA91bF-A97EurJz7IlGFD85cBIWGPCJv7UhV1j19sp6nKEH-9He1GOZQ9ZPegqYmVw3q2OA-_XPpePQckr5o97s9wTTbzYjornXCOqcR3jmN1t1aHV8i4CfRZOWuBDXTixzA3JDnzleHVY3xCtHev8tG90ife05Pw';

$registrationIds = array($reg);

$title=$row1['title'];
$number=$row1['number'];
$id=$row1['id'];
$created_at=$row1['created_at'];

$mes1 = $id .',' . $title . ',' . $number .',' . $created_at;
$message = str_replace('""','',$mes1);
$mes = $message;
$message = array("price" => $mes);
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
            'registration_ids' => $registrationIds,
            'data' => $message,
        );

        $headers = array(
            'Authorization: key=' . API_ACCESS_KEY,
            'Content-Type: application/json'
        );
        // Open connection
        $ch = curl_init();
// Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));



// Execute post
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }

        // Close connection
        curl_close($ch);

        echo $result;
//}
mysql_free_result($query4);


mysql_close($dbhandle);

?>

我只想要在表中插入任何新行,此脚本将自动调用并发送给定gcm注册ID的通知。我怎样才能做到这一点。有没有任何PHP功能来做到这一点? 请帮忙。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

请使用此php方法发送GCM通知

function sendNotification( $apiKey, $registrationIdsArray, $messageData )
{   
    $headers = array("Content-Type:" . "application/json", "Authorization:" . "key=" . $apiKey);
    $data = array(
        'data' => $messageData,
        'registration_ids' => $registrationIdsArray
    );

    $ch = curl_init();

    curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers ); 
    curl_setopt( $ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send" );
    curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data) );

    $response = curl_exec($ch);
    curl_close($ch);

    return $response;
}

请参阅这些链接,了解有关使用php进行GCM实施的详细信息