좋아요! 말씀하신 것처럼 **PG사 결제 관련 PHP 코드를 `main.php`에서 재사용**하려면 별도 파일로 만들어서 `include` 또는 `require`로 불러오면 됩니다. 이렇게 하면 코드 관리가 편하고 보안도 조금 더 나아집니다. 예시를 단계별로 보여드릴게요.
---
### 1️⃣ PG사 결제 코드 파일 만들기 (`pg_config.php`)
```php
<?php
// PG사에서 발급받은 상점 정보
$merchant_id = "12345678";
$api_key = "abcd1234secret";
/**
* 결제 데이터 배열 생성 함수
*/
function createPaymentData($order_id, $amount, $customer, $email){
global $merchant_id, $api_key;
$data = [
"merchant_id" => $merchant_id,
"order_id" => $order_id,
"amount" => $amount,
"customer" => $customer,
"email" => $email,
"timestamp" => time()
];
// 서명 생성
$signature_string = $merchant_id . $order_id . $amount . $api_key;
$data['signature'] = hash('sha256', $signature_string);
return $data;
}
/**
* PG사 결제 API 호출 함수
*/
function sendPayment($payment_data){
$ch = curl_init("https://pg.example.com/pay"); // PG사 API URL
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payment_data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
?>
```
---
### 2️⃣ `main.php`에서 include 하기
```php
<?php
// pg_config.php 파일 불러오기
include 'pg_config.php';
// 주문 정보 예시
$order_id = "ORDER20260318";
$amount = 50000;
$customer = "홍길동";
$email = "hong@example.com";
// 결제 데이터 생성
$payment_data = createPaymentData($order_id, $amount, $customer, $email);
// 결제 API 호출
$result = sendPayment($payment_data);
// 결과 확인
if($result['status'] == 'success'){
echo "결제 성공! 결제 ID: " . $result['payment_id'];
} else {
echo "결제 실패: " . $result['error_msg'];
}
?>
```
---
### ✅ 장점
1. `pg_config.php`를 수정하면 모든 페이지에 자동 적용
2. 상점 ID와 API Key를 한 곳에서 관리 → 보안 및 유지보수 용이
3. `createPaymentData()`와 `sendPayment()` 함수로 재사용 가능
---
💡 **Tip**:
* `pg_config.php`는 웹에서 직접 접근되지 않도록 웹 루트 밖에 두거나 `.htaccess`로 차단
* 테스트 환경과 실거래 환경용 상점 ID/Key를 구분해서 관리
---
원하면 제가 **`main.php`에서 버튼 클릭으로 결제 요청까지 연결되는 예시**도 만들어서 보여드릴 수 있습니다.
그거까지 만들어 드릴까요?