postMessage API
게임은 iframe 안에서 실행됩니다. Kplay 부모 창과의 모든 통신은 window.parent.postMessage()를 통해 이루어집니다.
메시지 타입 요약
게임 → Kplay (요청)
| type | 설명 |
|---|---|
purchase-item | 크레딧으로 아이템 구매 요청 |
credit-shop | 크레딧 충전 모달 열기 |
login-required | 로그인 요구 (미로그인 상태일 때) |
submit-score | 리더보드에 점수 제출 |
Kplay → 게임 (응답)
| type | 설명 |
|---|---|
user-info | 유저 정보 + 크레딧 잔액 (게임 로드 시 자동 전송) |
purchase-result | 구매 요청 결과 (성공/실패) |
score-submitted | 점수 제출 결과 |
user-info
게임이 로드되면 Kplay가 자동으로 유저 정보를 전송합니다.
// 게임에서 수신
window.addEventListener('message', (e) => {
if (e.data.type === 'user-info') {
console.log(e.data.userId); // "user-abc123" 또는 null (미로그인)
console.log(e.data.name); // "홍길동" 또는 null
console.log(e.data.credits); // 150 (현재 크레딧 잔액)
}
});
필드:
| 필드 | 타입 | 설명 |
|---|---|---|
userId | string | null | 유저 ID (미로그인 시 null) |
name | string | null | 유저 이름 |
credits | number | 현재 크레딧 잔액 |
purchase-item
크레딧으로 아이템을 구매합니다.
// 게임에서 전송
window.parent.postMessage({
type: 'purchase-item',
itemId: 'power-up-123',
itemName: 'Triple Points',
price: 50,
}, '*');
필드:
| 필드 | 타입 | 설명 |
|---|---|---|
itemId | string | 아이템 고유 식별자 |
itemName | string | 표시용 아이템 이름 |
price | number | 차감할 크레딧 수량 |
purchase-result
구매 요청의 결과를 수신합니다.
window.addEventListener('message', (e) => {
if (e.data.type === 'purchase-result') {
if (e.data.success) {
// 구매 성공
console.log(e.data.transactionId); // "tx-uuid-456"
console.log(e.data.balance); // 100 (차감 후 잔액)
grantItem();
} else {
// 구매 실패
console.log(e.data.error); // "Insufficient credits"
}
}
});
성공 시 필드:
| 필드 | 타입 | 설명 |
|---|---|---|
success | true | |
transactionId | string | 거래 고유 ID |
balance | number | 차감 후 크레딧 잔액 |
실패 시 필드:
| 필드 | 타입 | 설명 |
|---|---|---|
success | false | |
error | string | 실패 사유 |
credit-shop
크레딧이 부족할 때 충전 모달을 엽니다.
window.parent.postMessage({ type: 'credit-shop' }, '*');
login-required
미로그인 유저에게 로그인을 유도합니다.
if (!userId) {
window.parent.postMessage({ type: 'login-required' }, '*');
}
submit-score
리더보드에 점수를 제출합니다.
window.parent.postMessage({
type: 'submit-score',
score: 15000,
}, '*');
결과:
window.addEventListener('message', (e) => {
if (e.data.type === 'score-submitted') {
if (e.data.success) {
console.log(`랭킹: ${e.data.rank}위`);
}
}
});