오르다 보면 언젠가는 정상에 다다르게 된다.

iOS

Apple iOS PUSH php jwt 방식 전송.

Looplian 2021. 12. 28. 10:32
반응형

 

우선 애플 개발자 센터에서 APNs 키 파일을 발급받는다.

  1. https://developer.apple.com/account/ 에 접속한다.
  2. Certificates, Identifiers & Profiles 페이지로 이동한다.
  3. Keys 탭으로 이동한다.
  4. +를 눌러 새키를 생성한다.

5. 새 APN key 를 생성하고 Download 를 눌러 키 아이디와 .p8 파일을 다운로드 받는다.

 

이때 .p8 파일은 추가로 다운로드 할 수 없으니 분실에 주의 하자.

적당한 디렉토리에 .p8 파일을 업로드 한다.

 

6.  https://github.com/firebase/php-jwt  에서 JWT 라이브러리를 다운로드 받는다.

 

아래 php 함수로 푸시를 발송한다.

 

전송값 예시.

$bundleId = "com.looplian.testApp";

$device_token = 'e2c48ed32ef9b018........';
$msg = '{"aps":{"alert":"Hi there!","sound":"default"}}';

// jwt 최신버전에서 사용
// use Firebase\JWT\JWT;
// use Firebase\JWT\Key;

function sendPush($bundleId, $device_token, $msg, $isTest = true)
{
    $result = false;
    $teamId = "team id";
    $keyId = "key_id";
    $keyFilename = "key_id.p8";

    $keyfile = "file://" . $keyFilename; // absolute path
    $key = openssl_pkey_get_private($keyfile);

    $data = ['iss' => $teamId,'iat' => time()];
    $client_secret = JWT::encode($data, $keyId, $key, "ES256");
	
    // jwt 최신버전에서 사용시 keyId 위치가 변경.
	// $client_secret = JWT::encode($data, $key, 'HS256', $keyId);

    if ($isTest)
    {
        $url = 'https://api.sandbox.push.apple.com';
    }
    else
    {
        $url = 'https://api.push.apple.com';
    }

	// only needed for PHP prior to 5.5.24
    if (!defined('CURL_HTTP_VERSION_2_0'))
    {
        define('CURL_HTTP_VERSION_2_0', 3);
    }
    $ch = curl_init("$url/3/device/$device_token");
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_PORT, 443);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["apns-topic: {$bundleId}","Authorization: Bearer $client_secret"]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $msg);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    $response = curl_exec($ch);
    if ($response === FALSE)
    {
        $result = false;
		// echo curl_error($ch); // error
    }
    else
    {
        $result = true;
        // echo $response;
    }
    return $result;
}

 

반응형