← Back
Editing: newskurly-uv.php
<?php /** * Plugin Name: 뉴스컬리 자외선지수 위젯 * Description: 기상청 생활기상지수 API 프록시와 읍면동 지역 데이터를 제공합니다. * Version: 1.4.0 * Author: newskurly */ // ── 인증키 (공공데이터포털 일반 인증키) ── if ( ! defined( 'NK_KMA_SERVICE_KEY' ) ) { define( 'NK_KMA_SERVICE_KEY', 'fJAqcEIgPekLuQbKV1SVf6hTwI8fq48Hsh9DLQACUzPRdLcY+bEj8JoN/3Mc6JUOddNK8fYX+WtAjCkxnS62kg==' ); } // ──────────────────────────────────────── if ( ! defined( 'ABSPATH' ) ) { exit; } // 엔드포인트 (활용가이드 기준). 포털에서 V4로 안내되면 아래 두 줄만 교체하세요. define( 'NK_UV_BASE', 'https://apis.data.go.kr/1360000/LivingWthrIdxServiceV5/getUVIdxV5' ); /** * 인증키를 아래 순서로 찾는다. 하나만 쓰면 된다. * 1) 상수 NK_KMA_SERVICE_KEY (wp-config.php / mu-plugins / functions.php 어디든) * 2) DB 옵션 nk_kma_service_key * 3) 필터 nk_kma_service_key * * Encoding 키(%2B %2F %3D 포함)를 넣어도 자동으로 Decoding 키로 되돌린다. */ function nk_uv_service_key() { $key = ''; if ( defined( 'NK_KMA_SERVICE_KEY' ) ) { $key = NK_KMA_SERVICE_KEY; } if ( '' === $key ) { $key = (string) get_option( 'nk_kma_service_key', '' ); } $key = (string) apply_filters( 'nk_kma_service_key', $key ); $key = trim( $key ); // 퍼센트 인코딩이 섞여 있으면 원본(Decoding) 형태로 되돌린다. if ( false !== strpos( $key, '%' ) ) { $decoded = rawurldecode( $key ); if ( '' !== $decoded ) { $key = $decoded; } } return $key; } add_action( 'rest_api_init', function () { register_rest_route( 'newskurly/v1', '/uv', array( 'methods' => 'GET', 'permission_callback' => '__return_true', 'callback' => 'nk_uv_endpoint', 'args' => array( 'areaNo' => array( 'required' => true ), ), ) ); } ); /** * 현재 시각(KST) 기준으로 최근 발표시각부터 과거로 내려가는 후보 목록을 만든다. * 발표는 00,03,06,09,12,15,18,21시. 생산 직후에는 아직 자료가 없을 수 있어 최대 4회 되짚는다. */ function nk_uv_base_times( $tries = 4 ) { $kst = time() + 9 * HOUR_IN_SECONDS; $hour = (int) gmdate( 'H', $kst ); $slot = $hour - ( $hour % 3 ); $anchor = gmmktime( $slot, 0, 0, (int) gmdate( 'n', $kst ), (int) gmdate( 'j', $kst ), (int) gmdate( 'Y', $kst ) ); $list = array(); for ( $i = 0; $i < $tries; $i++ ) { $list[] = gmdate( 'YmdH', $anchor - ( $i * 3 * HOUR_IN_SECONDS ) ); } return $list; } function nk_uv_endpoint( WP_REST_Request $req ) { $area = preg_replace( '/[^0-9]/', '', (string) $req->get_param( 'areaNo' ) ); if ( strlen( $area ) !== 10 ) { return new WP_REST_Response( array( 'ok' => false, 'msg' => '지역코드 형식이 올바르지 않습니다.' ), 400 ); } $service_key = nk_uv_service_key(); if ( '' === $service_key ) { return new WP_REST_Response( array( 'ok' => false, 'msg' => '서버에 인증키가 설정되지 않았습니다.' ), 500 ); } $times = nk_uv_base_times( 4 ); // 2026-07-01 개편 신코드에 자료가 없으면 구코드로 자동 재시도 $areas = array( $area ); $legacy = nk_uv_legacy_map(); if ( isset( $legacy[ $area ] ) ) { $areas[] = $legacy[ $area ]; } $cache_key = 'nk_uv_' . $area . '_' . $times[0]; $cached = get_transient( $cache_key ); if ( false !== $cached ) { $cached['cached'] = true; return new WP_REST_Response( $cached, 200 ); } $last_msg = '자료를 가져오지 못했습니다.'; $debug = array(); foreach ( $areas as $use_area ) { foreach ( $times as $t ) { // ★ add_query_arg()/build_query()는 값을 URL 인코딩하지 않는다. // 인증키의 '+' 가 공백으로 해석돼 인증이 깨지므로 직접 rawurlencode 한다. $url = NK_UV_BASE . '?serviceKey=' . rawurlencode( $service_key ) . '&areaNo=' . rawurlencode( $use_area ) . '&time=' . rawurlencode( $t ) . '&dataType=JSON&numOfRows=10&pageNo=1'; $res = wp_remote_get( $url, array( 'timeout' => 10, 'sslverify' => false ) ); if ( is_wp_error( $res ) ) { $last_msg = '기상청 서버에 연결하지 못했습니다. (' . $res->get_error_message() . ')'; $debug[] = array( 'area' => $use_area, 'time' => $t, 'err' => $res->get_error_message() ); continue; } $status = (int) wp_remote_retrieve_response_code( $res ); $body = wp_remote_retrieve_body( $res ); $json = json_decode( $body, true ); $debug[] = array( 'area' => $use_area, 'time' => $t, 'status' => $status, 'body' => mb_substr( (string) $body, 0, 400 ) ); // 인증 오류 등은 JSON이 아닌 XML로 떨어지는 경우가 있다. if ( ! is_array( $json ) ) { $last_msg = '응답이 JSON이 아닙니다 (HTTP ' . $status . '). 인증키 승인 상태를 확인하세요.'; continue; } $code = isset( $json['response']['header']['resultCode'] ) ? $json['response']['header']['resultCode'] : ''; if ( '00' !== $code && 'NORMAL_SERVICE' !== $code ) { if ( isset( $json['response']['header']['resultMsg'] ) ) { $last_msg = (string) $json['response']['header']['resultMsg']; } elseif ( isset( $json['resultMsg'] ) ) { $last_msg = (string) $json['resultMsg']; } else { $last_msg = '기상청 응답 구조를 해석하지 못했습니다.'; } continue; // NODATA_ERROR 포함 → 이전 발표시각으로 재시도 } $item = isset( $json['response']['body']['items']['item'] ) ? $json['response']['body']['items']['item'] : null; if ( isset( $item[0] ) ) { $item = $item[0]; } if ( ! is_array( $item ) ) { $last_msg = '해당 지역의 예보 자료가 없습니다.'; continue; } // h0 ~ h78 중 실제로 내려온 값만 수집 (문서상 h0~h75 / 샘플 h3~h78 로 표기가 엇갈려 둘 다 대응) $values = array(); for ( $h = 0; $h <= 78; $h += 3 ) { $k = 'h' . $h; if ( ! isset( $item[ $k ] ) ) { continue; } $v = trim( (string) $item[ $k ] ); if ( '' === $v ) { continue; } if ( ! is_numeric( $v ) ) { continue; } $values[ (string) $h ] = (float) $v; } if ( empty( $values ) ) { $last_msg = '예보값이 비어 있습니다.'; continue; } $out = array( 'ok' => true, 'areaNo' => $use_area, 'legacy' => ( $use_area !== $area ), 'date' => isset( $item['date'] ) ? (string) $item['date'] : $t, 'values' => $values, 'cached' => false, ); // 다음 발표시각까지 보관 (넉넉히 3시간 10분) set_transient( $cache_key, $out, 3 * HOUR_IN_SECONDS + 600 ); return new WP_REST_Response( $out, 200 ); } } $fail = array( 'ok' => false, 'msg' => $last_msg, 'tried' => $areas, 'times' => $times ); if ( $req->get_param( 'debug' ) ) { $fail['debug'] = $debug; } return new WP_REST_Response( $fail, 200 ); } /** * 읍면동 지역 데이터 제공 (플러그인 폴더 안의 JSON을 그대로 내보냄) * /wp-json/newskurly/v1/uv-areas */ add_action( 'rest_api_init', function () { register_rest_route( 'newskurly/v1', '/uv-areas', array( 'methods' => 'GET', 'permission_callback' => '__return_true', 'callback' => 'nk_uv_areas_endpoint', ) ); } ); function nk_uv_areas_endpoint() { $file = plugin_dir_path( __FILE__ ) . 'data/uv-areas-emd.json'; if ( ! file_exists( $file ) ) { return new WP_REST_Response( array(), 200 ); } $raw = file_get_contents( $file ); $data = json_decode( $raw, true ); if ( ! is_array( $data ) ) { return new WP_REST_Response( array( 'error' => 'json decode failed', 'bytes' => strlen( $raw ) ), 500 ); } $res = new WP_REST_Response( $data, 200 ); $res->header( 'Cache-Control', 'public, max-age=86400' ); return $res; } /** 신코드 → 구코드 매핑 로드 */ function nk_uv_legacy_map() { static $map = null; if ( null !== $map ) { return $map; } $file = plugin_dir_path( __FILE__ ) . 'data/legacy-area-map.php'; $map = file_exists( $file ) ? (array) include $file : array(); return $map; }
Save File
Cancel