javascriptlaraveltelegram-bot

Get referral code from telegram bot start parameter with JavaScript landing page, and send to Laravel backend


I am making a telegram miniapp, it have options for users to refere others to the app and get reward, I have completed the authentication and many functions/logics of the app. But extracting the referral code from the ref link eg: https://t.me/my_bot?start=RefC0d3, I have tried a lot of things that did not work

Please can someone help me out, Im stcucked here. Thanks.

My js code is below:

const telegramWebApp = await loadTelegramSdk();
                if (telegramWebApp) {
                    const { id, first_name, username, start_param } = telegramWebApp.initDataUnsafe;
                    console.log('Telegram User Info:', { id, first_name, username, start_param });
    
                    const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
    
                    const headers = {
                        'Content-Type': 'application/json',
                    };
    
                    if (csrfToken) {
                        headers['X-CSRF-TOKEN'] = csrfToken;
                    }
                    
                    const requestBody = {
                        ...telegramWebApp.initDataUnsafe,
                        referral_code: start_param // Add referral_code to the request body
                    };
    
                    const response = await fetch("{{ route('tg.authenticate') }}", {
                        method: 'POST',
                        headers: headers,
                        body: JSON.stringify(requestBody) // Send referral_code in the request body
                    });
    
                    const data = await response.json();
                    if (data.message === 'Logged in successfully' || data.message === 'User created and logged in') {
                        console.log(`Welcome ${first_name || username}!`);
                        setTimeout(() => {
                            window.location.href = '{{ route('tg.dashboard') }}'; // Redirect after 1.5 seconds
                        }, 1500);
                    } else {
                        console.error('Authentication failed:', data.message);
                    }
                }

In my controller I used Log::info('Request Input:', $request->all()); to check the inputs but the javasacipt is not sending the refferral code.


Solution

  • you should send in web hook requests' data what you need.