How do I create a payment and check its status?

126 Views Asked by At

How do I implement the creation of a payment and check its status on the client (I'm trying to attach it to the discord bot (Python disnake))? I tried to do this using chatGPT, but to no avail, the server returns error 400 when trying to create. I read the documentation, it says that you can view the response body, but there was another problem, how to view this body if it outputs only an error code (the library itself sends the request to the server (yookassa)), which practically does not give any information. The yookassa v3 library. Yes, I'm a beginner. My code:

import disnake
from disnake.ext import commands
from colorama import Fore
import uuid
import var_dump as var_dump
from ids_list import admin
from yookassa import Payment, Configuration, Settings
from yookassa.domain.models.currency import Currency
from yookassa.domain.models.receipt import Receipt, ReceiptItem
from yookassa.domain.common.confirmation_type import ConfirmationType
from yookassa.domain.request.payment_request_builder import PaymentRequestBuilder
import json


Configuration.account_id = 'my super id'
Configuration.secret_key = 'super secret pay'


me = Settings.get_account_settings()
var_dump.var_dump(me)

class ls(commands.Cog):
    def __init__(self, bot: commands.bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.author == self.bot.user:
            return
        
        if isinstance(message.channel, disnake.DMChannel):
            if message.content == '2':
                if message.author.id == admin:
                        embed_1 = disnake.Embed(title="message1")
                        await message.channel.send(embed=embed_1, components=[
                            disnake.ui.Button(style=disnake.ButtonStyle.success, label="Create payment", custom_id="create_payment"),
                            disnake.ui.Button(style=disnake.ButtonStyle.danger, label="exit", custom_id="cancel"),
                            ],
                        )
                else:
                    embed = disnake.Embed(
                        title = "message",
                        description = "text",
                        colour = 0xFFD966)
                    embed.set_thumbnail(url=url_icon)
                    embed.set_image(url=url_image)
                    await message.channel.send(embed=embed)

    @commands.Cog.listener()
    async def on_button_click(self, interaction: disnake.MessageInteraction):
        if interaction.component.custom_id == "create_payment":
            with open('types.json') as f:
                types = json.load(f)
                payment = Payment.create({
                    "amount": {
                        "value": types['1']['amount']['value'],
                        "currency": types['1']['amount']['currency']
                    },
                    "confirmation": {
                        "type": "redirect",
                        "return_url": "https://google.com/"
                    },
                    "description": types['1']['description'],
                    "capture": true
                }, uuid.uuid4())
                var_dump.var_dump(payment)
                print(payment.content.decode())
                # payment_url = payment.confirmation.confirmation_url
                
            embed_2 = disnake.Embed(title="Payment create!", description=f"Pay: {payment.confirmation.confirmation_url}", colour=0x6AA84F)
            await interaction.message.edit(embed=embed_2, components=[
                disnake.ui.Button(style=disnake.ButtonStyle.success, label="Check payment status", custom_id="check_payment"),
                disnake.ui.Button(style=disnake.ButtonStyle.danger, label="Payment close", custom_id="cancel_payment"),
                ])
            payment_id = request.data['id']
            idempotence_key = str(uuid.uuid4())
            response = Payment.capture(
            payment_id,
            {
                "amount": {
                "value": "2.00",
                "currency": "RUB"
                }
            },
            idempotence_key
                )

        elif interaction.component.custom_id == "check_payment":

            res = Payment.find_one(self.payment.id)
            var_dump.var_dump(res)

            if res.status == 'succeeded':
                embed_3 = disnake.Embed(title="Nice buy!")
                await interaction.message.edit(content="Nice", embed=embed_3)
        
        elif interaction.component.custom_id == "cancel_payment":
            idempotence_key = str(uuid.uuid4())
            response = Payment.cancel(
            self.payment_id,
            idempotence_key
            )
            await interaction.message.edit(content="Payment close")

def setup(bot: commands.Bot):
    bot.add_cog(ls(bot))
    print(Fore.GREEN + "/////////////////////////////////\n")
    print("Cog Started!\n")
    print("/////////////////////////////////\n")

Error when clicking the Create payment button:

Traceback (most recent call last):
  File "C:\Users\L1te\AppData\Local\Programs\Python\Python311\Lib\site-packages\disnake\client.py", line 703, in _run_event        
    await coro(*args, **kwargs)
  File "d:\pek\modules\ls.py", line 171, in on_button_click
    payment = Payment.create({
              ^^^^^^^^^^^^^^^^
  File "C:\Users\L1te\AppData\Local\Programs\Python\Python311\Lib\site-packages\yookassa\payment.py", line 58, in create
    response = instance.client.request(HttpVerb.POST, path, None, headers, params_object)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\L1te\AppData\Local\Programs\Python\Python311\Lib\site-packages\yookassa\client.py", line 38, in request
    raw_response = self.execute(body, method, path, query_params, request_headers)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\L1te\AppData\Local\Programs\Python\Python311\Lib\site-packages\yookassa\client.py", line 59, in execute
    self.log_response(raw_response.content, self.get_response_info(raw_response), raw_response.headers)
                                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\L1te\AppData\Local\Programs\Python\Python311\Lib\site-packages\yookassa\client.py", line 119, in get_response_info
    "raise_for_status": response.raise_for_status(),
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\L1te\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\models.py", line 1021, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error:  for url: https://api.yookassa.ru/v3/payments

Read the documentation and examples. Working code

0

There are 0 best solutions below