«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Archives
Today
Total
관리 메뉴

올해는 머신러닝이다.

텔레그램 미니앱 + 테스트 결제 튜토리얼 (Step-by-Step) 본문

코인

텔레그램 미니앱 + 테스트 결제 튜토리얼 (Step-by-Step)

행복한 수지아빠 2025. 2. 21. 09:32

텔레그램 미니앱 + 테스트 결제 튜토리얼 (Step-by-Step)

이 튜토리얼에서는 텔레그램 미니앱을 개발하고, 스타(Stars) 테스트 결제까지 연동하는 방법을 단계별로 진행합니다.


🛠️ 1. 준비사항

📌 필요한 것

  • 텔레그램 봇 생성
  • 웹 서버(Node.js + Express)
  • Stripe 결제 시스템 (테스트 모드)
  • Webhook (결제 상태 확인)

🚀 2. 텔레그램 봇 생성 및 설정

1️⃣ BotFather로 봇 생성

텔레그램에서 BotFather와 채팅 후,
아래 명령어를 입력하여 새 봇을 생성합니다.

/newbot

BotFather가 요청하는 정보 입력

  1. 봇 이름 설정 → (예: MyMiniAppBot)
  2. 사용자명(username) 설정 → (예: my_miniapp_bot)

2️⃣ API Token 복사

BotFather가 생성해 준 **봇 API 키(Token)**을 메모해 둡니다.

Use this token to access the HTTP API:
1234567890:ABCDEFGHIJKLmnopqrstuvwxyz

👉 이 API 키는 서버에서 텔레그램과 통신할 때 사용됩니다.


💻 3. 웹서버 (Node.js) 생성

1️⃣ Node.js 프로젝트 생성

mkdir telegram-miniapp && cd telegram-miniapp
npm init -y

2️⃣ 필수 패키지 설치

npm install express axios body-parser dotenv cors

🌍 4. 미니앱 웹페이지 만들기

미니앱은 웹 페이지로 동작하므로 HTML + JavaScript로 작성됩니다.

1️⃣ 웹앱 HTML 파일 만들기 (public/index.html)

    
    

Telegram Mini App

스타 구매
        let tg = window.Telegram.WebApp;
        tg.expand(); // 전체화면 활성화

        function requestPayment() {
            fetch("/create-payment", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ userId: tg.initDataUnsafe.user.id })
            })
            .then(res => res.json())
            .then(data => {
                if (data.ok) {
                    alert("결제 요청이 전송되었습니다.");
                } else {
                    alert("결제 요청 실패");
                }
            });
        }
    

설명:

  • Telegram.WebApp을 사용하여 유저 정보를 가져오고 UI를 설정.
  • 버튼 클릭 시 /create-payment API 호출하여 스타 결제 요청.

🖥️ 5. 서버 개발 (Express.js)

1️⃣ server.js 파일 생성

require('dotenv').config();
const express = require('express');
const axios = require('axios');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(express.static('public'));

const BOT_TOKEN = process.env.BOT_TOKEN;  // .env에서 가져옴
const PROVIDER_TOKEN = process.env.PROVIDER_TOKEN;  // 테스트 결제 키

// 📌 테스트 결제 요청 API
app.post('/create-payment', async (req, res) => {
    const { userId } = req.body;

    try {
        const response = await axios.post(
            `https://api.telegram.org/bot${BOT_TOKEN}/sendInvoice`,
            {
                chat_id: userId,
                title: "스타 결제",
                description: "100개 스타를 테스트 결제합니다.",
                payload: "test_stars_payment_100",
                provider_token: PROVIDER_TOKEN,  // 테스트 결제 키
                currency: "USD",
                prices: [{ label: "100 Stars", amount: 10000 }],
                start_parameter: "test-stars-payment",
                need_email: false
            }
        );
        res.json(response.data);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// 📌 결제 완료 후 웹훅
app.post('/payment-webhook', (req, res) => {
    console.log("💰 결제 정보:", req.body);
    res.sendStatus(200);
});

app.listen(3000, () => {
    console.log('✅ 서버 실행 중: http://localhost:3000');
});

🛠️ 6. 환경 변수 설정 (.env 파일)

BOT_TOKEN=1234567890:ABCDEFGHIJKLmnopqrstuvwxyz
PROVIDER_TOKEN=TEST_PROVIDER_TOKEN  # Stripe 테스트 키

🚀 7. 서버 실행 및 테스트

1️⃣ 서버 실행

node server.js

2️⃣ 브라우저에서 미니앱 실행

  • 텔레그램에서 봇과 채팅 후 아래 명령어 실행
  • /setdomain
  • 봇에게 /start 입력 → 웹앱 실행 버튼 클릭
  • 웹앱이 실행되면 "스타 구매" 버튼 클릭
  • 테스트 결제 창이 나타나면 진행 후 로그 확인

✅ 8. 결제 완료 후 확인

1️⃣ 결제 성공 로그

💰 결제 정보: {
  invoice_id: "test_invoice_12345",
  status: "paid",
  total_amount: 10000,
  currency: "USD",
  payment_provider: "stripe"
}

🎉 최종 요약

1️⃣ 텔레그램 봇 생성 (BotFather)
2️⃣ 웹앱 (index.html) 구현 → Telegram WebApps API 사용
3️⃣ Express 서버 개발 → sendInvoice API 호출
4️⃣ 결제 요청 후 웹훅에서 성공 로그 확인
5️⃣ Stripe 테스트 결제 사용하여 실제 카드 입력 없이 결제 테스트 완료


이제 텔레그램 미니앱에서 실제로 결제 테스트까지 해볼 수 있음! 🚀

'코인' 카테고리의 다른 글

신규 텔레그램 무료 채굴 MegaMine을 소개합니다  (0) 2025.02.20