Как интегрировать платежную систему в telegram bot на java?

Я пишу telegram bot на языке java и пытаясь внедрить систему оплаты. Я столкнулся с некоторыми проблемами, а именно: В основном все платежные провайдеры (Юкасса, Тинкофф, Сбербанк и тд) не имеют API для java, и иза этой проблемы возникает слудующая, более локальная, это payments 2.0 от телеграм. Моя попытка вставить эта в мой код увенчалась провалом, которая скорее всего связана моей рассеянностью и невнимательностью. Вставив пример кода payment в свой, меня ожидали одни ошибки связанные с SendResponse, bot.execute, chatID, pay() и тп. Вродe бы я вставил нужную библиотеку в maven но ошибки остались на месте. 6112dd15e4e61471227588.png Знаю, что вопрос для кого-то изищный, я перегорел и стал более рассеянным, когда делал этого бота. Не судите строго. ..
Вот всесь код бота
import java.io.*;
import org.telegram.telegrambots.api.methods.send.SendInvoice;
import org.telegram.telegrambots.api.methods.updatingmessages.EditMessageText;
import org.telegram.telegrambots.api.objects.payments.LabeledPrice;
import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboardMarkup;
import org.telegram.telegrambots.api.objects.replykeyboard.buttons.InlineKeyboardButton;
import org.telegram.telegrambots.api.objects.replykeyboard.buttons.KeyboardRow;
import com.vdurmont.emoji.EmojiParser;
import org.alicebot.ab.*;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import java.util.*;
import org.telegram.telegrambots.api.methods.send.SendMessage;
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.exceptions.TelegramApiException;

import static java.lang.Math.toIntExact;

class BotHandler extends TelegramLongPollingBot
{
    private static final boolean TRACE_MODE = false;
    private final static int SIZE = 2000;
    private String smiley_emoji = EmojiParser.parseToUnicode(":smiley:");
    private String wink_emoji = EmojiParser.parseToUnicode(":wink:");
    private String share_number_emoji = EmojiParser.parseToUnicode(":phone: share your number");
    private String money_emoji = EmojiParser.parseToUnicode(":moneybag:");
    static String botName = "super";
    String response;
    String textLine;
    Bot bot;
    Chat chatSession;
    String resourcesPath;
    public BotHandler()
    {
        String resourcesPath = getResourcesPath();
        bot = new Bot("super", resourcesPath);
        chatSession = new Chat(bot);
        bot.brain.nodeStats();
        MagicBooleans.trace_mode = TRACE_MODE;
    }



    public void onUpdateReceived(Update update)
    {
        if (update.hasMessage() && update.getMessage().hasText()) {

            String textLine = update.getMessage().getText();
            long chat_id = update.getMessage().getChatId();
            if ((textLine == null) || (textLine.length() < 1))
                textLine = MagicStrings.null_input;
            String request = textLine;
            ///////Just for Log memes :p Disabled by default
            if (MagicBooleans.trace_mode)
                System.out.println("STATE=" + request + ":THAT=" + ((History) chatSession.thatHistory.get(0)).get(0) + ":TOPIC=" + chatSession.predicates.get("topic"));
            else if (request.equals("/start")) {
                response=" ";
                SendMessage message = new SendMessage() // Create a message object object
                        .setChatId(chat_id)
                        .setText("Hello!");
                // Create ReplyKeyboardMarkup object
                ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup();
                keyboardMarkup.setResizeKeyboard(true);
                // Create the keyboard (list of keyboard rows)
                List<KeyboardRow> keyboard = new ArrayList<>();
                // Create a keyboard row
                KeyboardRow row = new KeyboardRow();
                // Set each button, you can also use KeyboardButton objects if you need something else than text
                row.add("/Email");
                row.add("/Buy");
                // Add the first row to the keyboard
                keyboard.add(row);

                keyboardMarkup.setKeyboard(keyboard);
                // Add it to the message
                message.setReplyMarkup(keyboardMarkup);
                try {
                    sendMessage(message); // Sending our message object to user
                } catch (TelegramApiException e) {
                    e.printStackTrace();
                }
            }


            else if(request.contains("/Email") ||request.contains("/Buy")) {

                {

                    response=" ";
                    if (update.getMessage().getText().equals("/Email")) {
                        SendMessage message = new SendMessage() // Create a message object object
                                .setChatId(chat_id)
                                .setText("Thank you so much for leaving feedback on me. It means a lot to my creators and to me.");
                        InlineKeyboardMarkup markupInline = new InlineKeyboardMarkup();
                        List<List<InlineKeyboardButton>> rowsInline = new ArrayList<>();
                        List<InlineKeyboardButton> rowInline = new ArrayList<>();
                        rowInline.add(new InlineKeyboardButton().setUrl("https://mail.google.com").setCallbackData("Feed Back").setText("Email"));
                        // Set the keyboard to the markup
                        rowsInline.add(rowInline);
                        // Add it to the message
                        markupInline.setKeyboard(rowsInline);
                        message.setReplyMarkup(markupInline);
                        try {
                            sendMessage(message); // Sending our message object to user
                        } catch (TelegramApiException e) {
                            e.printStackTrace();
                        }

                    }
                }if (update.getMessage().getText().equals("/Buy")) {
                    SendMessage message = new SendMessage(); // Create a message object object
                        SendResponse response = bot.execute(new SendInvoice(chatID, "title", "desc", "my_payload",
                                "284685063:TEST:NThlNWQ3NDk0ZDQ5", "my_start_param", "USD", new LabeledPrice("label", 200))
                                .providerData("{\"foo\" : \"bar\"}")
                                .photoUrl("https://telegram.org/img/t_logo.png").photoSize(100).photoHeight(100).photoWidth(100)
                                .needPhoneNumber(true).needShippingAddress(true).needEmail(true).needName(true)
                                .isFlexible(true)
                                .replyMarkup(new InlineKeyboardMarkup(new InlineKeyboardButton[]{
                                        new InlineKeyboardButton("just pay").pay(),
                                        new InlineKeyboardButton("google it").url("www.google.com")
                                }))
                        );
                        InvoiceCheck.check(response.message().invoice());
                    }

                    try {
                        sendMessage(message); // Sending our message object to user
                    } catch (TelegramApiException e) {
                        e.printStackTrace();
                    }}

            } else if (update.hasCallbackQuery()) {
                // Set variables
                String call_data = update.getCallbackQuery().getData();
                long message_id = update.getCallbackQuery().getMessage().getMessageId();
                long chat_id1 = update.getCallbackQuery().getMessage().getChatId();
                response=" ";
                if (call_data.equals("Email")) {
                    String answer = "Updated message text";
                    EditMessageText new_message = new EditMessageText()
                            .setChatId(chat_id1)
                            .setMessageId(toIntExact(message_id))
                            .setText(answer);
                    try {
                        editMessageText(new_message);
                    } catch (TelegramApiException e) {
                        e.printStackTrace();
                    }
                }

            }else if(request.equals("/help"))
            {
                response="What's wrong man? ";
            }
            else
            {
                response = chatSession.multisentenceRespond(request);
                if(response.contains("<"))
                {
                    response="Sorry, there was some error! "+ wink_emoji;
                }

            }

            SendMessage message = new SendMessage().setChatId(chat_id).setText(response);
            try {
                execute(message);
            }
            catch (TelegramApiException e)
            {
                e.printStackTrace();
            }
        }
    }


    public String getBotUsername()
    {
        return "Talk_to_me_Bot";
    }

    @Override
    public String getBotToken()
    {
        return "170925sdzxfhcgvfgcdxy34567-sdvhgsdcwcw";
    }

    private static String getResourcesPath()
    {
        File currDir = new File(".");
        String path = currDir.getAbsolutePath();
        path = path.substring(0, path.length() - 2);
        System.out.println(path);
        String resourcesPath = path + File.separator + "src" + File.separator + "main" + File.separator + "resources";
        return resourcesPath;
    }
}
  • Вопрос задан
  • 1037 просмотров
Пригласить эксперта
Ответы на вопрос 1
profesor08
@profesor08
Придется почитать документацию и вручную обрабатывать http запросы.

Или порыть на гитхабе: https://github.com/search?l=Java&q=yookassa+java&t...
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
Bell Integrator Ульяновск
До 400 000 ₽
Bell Integrator Хабаровск
До 400 000 ₽
Bell Integrator Ижевск
До 400 000 ₽
18 апр. 2024, в 01:12
150000 руб./за проект
18 апр. 2024, в 00:10
50000 руб./за проект