2. flutter 푸시발송 세팅 - php 로 푸시보내기

작성자 정보

  • 최고관리자 작성
  • 작성일

컨텐츠 정보

본문

php 로 푸시 발송하는 방법


push_send 함수를 호출해서 푸시를 발송하면 됨


$mb_pushkey : 푸시받을 대상자 fcm key ( 앱이 구동될때 사용자별로 fcm key 가 생성됨 )

$title : 푸시제목

$contents : 푸시내용

$target_url : 푸시 클릭시 이동할 url

$rich_plus_pic : 이미지 url 



1. flutter 푸시발송 세팅 - Firebase 설정


<?php
function push_send($mb_pushkey, $title, $contents, $target_url){

// FCM 프로젝트 ID와 서비스 계정 키 파일 경로 설정
$projectId = '파이어베이스 프로젝트 ID';
$serviceAccountKeyPath = 'jon 파일 절대 경로';

$fcmToken = $mb_pushkey;
$rich_push_pic = ''; // 이미지주소
sendPushNotification($fcmToken, $title, $contents, $rich_push_pic, $projectId, $serviceAccountKeyPath, $target_url);
}


function sendPushNotification($fcmToken, $title, $body, $imageUrl, $projectId, $serviceAccountKeyFile, $target_url) {
$accessToken = getAccessToken($serviceAccountKeyFile);

//var_dump($accessToken);

$message = [
'message' => [
'token' => $fcmToken,
'notification' => [
'title' => $title,
'body' => $body,
'image' => $imageUrl
],
'data' => [
'title' => $title,
'body' => $body,
'targetUrl' => $target_url
]
]
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://fcm.googleapis.com/v1/projects/$projectId/messages:send");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $accessToken,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($message));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($response === false) {
//echo "cURL Error: " . curl_error($ch) . "<hr/>";
} else {
//echo "HTTP Status Code: " . $httpcode . "<hr/>";
//echo "Response Body: " . $response . "<hr/>";
}

curl_close($ch);

if ($httpcode == 200) {
//echo "Push notification sent successfully";
} else {
//echo "Error sending push notification";
}
}



function getAccessToken($serviceAccountKeyFile) {
$now = time();
$key = file_get_contents($serviceAccountKeyFile);
$key = json_decode($key, true);

$header = [
'alg' => 'RS256',
'typ' => 'JWT',
'kid' => $key['private_key_id']
];
$claim = [
'iss' => $key['client_email'],
'exp' => $now + 3600,
'iat' => $now
];

$header = base64_encode(json_encode($header));
$claim = base64_encode(json_encode($claim));
$signature = '';
openssl_sign("$header.$claim", $signature, $key['private_key'], 'SHA256');
$jwt = "$header.$claim." . base64_encode($signature);

$response = file_get_contents('https://oauth2.googleapis.com/token', false, stream_context_create([
'http' => [
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded",
'content' => http_build_query([
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion' => $jwt
])
]
]));

return json_decode($response, true)['access_token'];
}



?>


 

Warning: file_get_contents(): https:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /push_send.php on line 101

Warning: file_get_contents(https://oauth2.googleapis.com/token): failed to open stream: no suitable wrapper could be found in /push_send.php on line 101. 


이런 에러가 발생한다면



function getAccessToken($serviceAccountKeyFile) {
$now = time();
$key = json_decode(file_get_contents($serviceAccountKeyFile), true);

$header = base64_encode(json_encode([
'alg' => 'RS256',
'typ' => 'JWT',
'kid' => $key['private_key_id']
]));
$claim = base64_encode(json_encode([
'iss' => $key['client_email'],
'exp' => $now + 3600,
'iat' => $now
]));

$signature = '';
openssl_sign("$header.$claim", $signature, $key['private_key'], 'SHA256');
$jwt = "$header.$claim." . base64_encode($signature);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://oauth2.googleapis.com/token');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion' => $jwt
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
if(curl_errno($ch)){
throw new Exception(curl_error($ch));
}
curl_close($ch);

$responseData = json_decode($response, true);
if (!isset($responseData['access_token'])) {
throw new Exception("Failed to get access token: " . print_r($responseData, true));
}

return $responseData['access_token'];
}

관련자료

댓글 0
등록된 댓글이 없습니다.