Загрузка...

Ошибка при работе с апи Твича

Тема в разделе Python создана пользователем Стаффи 29 мар 2025. 141 просмотр

Загрузка...
  1. Стаффи
    Стаффи Автор темы 29 мар 2025 Купить домен анонимно - t.me/FastDomainBot
    При попытке оформить бесплатную сабку на канал твича с подпиской Amazon Prime приходит ответ:
    Код
    {'errors': [{'message': 'failed integrity check', 'path': ['purchaseOffer']}], 'data': {'purchaseOffer': None}, 'extensions': {'challenge': {'type': 'integrity'}, 'durationMilliseconds': 3, 'operationName': 'PurchaseOrderContext_PurchaseOffer', 'requestID': '01JQF6K2TPYCZN7STWRR8PPJTX'}}
    Как можно исправить эту ошибку?
    Python
    from curl_cffi.requests import AsyncSession
    from datetime import datetime
    import pycountry


    class InvalidToken(Exception):
    pass


    class Twitch:
    def __init__(
    self,
    token: str,
    client_id: str = "xxxxxxxxxx",
    ):
    self.token = token
    self.client_id = client_id

    self._session = AsyncSession(
    impersonate="chrome",
    allow_redirects=False,
    timeout=10,
    )

    async def _gql_request(
    self, operation_name: str, operation_hash: str, variables: dict
    ):
    headers = {
    "Client-Id": self.client_id,
    "Authorization": f"OAuth {self.token}",
    }

    data = {
    "extensions": {
    "persistedQuery": {
    "version": 1,
    "sha256Hash": operation_hash,
    }
    },
    "operationName": operation_name,
    "variables": variables,
    }

    response = await self._session.post(
    "https://gql.twitch.tv/gql",
    headers=headers,
    json=data,
    )

    if response.status_code == 401:
    raise InvalidToken("Invalid token")

    return response.json()

    async def get_current_user(self):
    response = await self._gql_request(
    "CoreActionsCurrentUser",
    "6b5b63a013cf66a995d61f71a508ab5c8e4473350c5d4136f846ba65e8101e95",
    {},
    )
    return response["data"]["currentUser"]

    async def get_subscription_id(self, login: str):
    response = await self._gql_request(
    "SupportPanelSubscribeViewFooterPrime",
    "02d85dc601efbdf6ac4583bc7e7b1c4b9855dadf1f8f051eef1d76adeb84eac6",
    {"login": login},
    )
    return response

    async def purchase_subscription(
    self, user_id: str, offer_id: str, product_id: str, channel_id: str
    ):
    variables = {
    "input": {
    "offerID": offer_id,
    "paymentSession": {
    "deviceID": "VDTv0bBkeRcFXcqme...",
    "localStorageDeviceID": "e5257d...",
    "tabSessionID": "97ce11c1...",
    "pageSessionID": "6e21fd9ab...",
    "checkoutSessionID": "3c5a33f6-83ba-408e-...",
    },
    "purchasingUserID": user_id,
    "quantity": 1,
    "tagBindings": [
    {"key": "product_id", "value": product_id},
    {"key": "channel_id", "value": channel_id},
    ],
    }
    }

    response = await self._gql_request(
    operation_name="PurchaseOrderContext_PurchaseOffer",
    operation_hash="703342a16f143f21b238ddab53d1668c8b1fa8cf515310a9c9c3481a88a93b05",
    variables=variables,
    )

    return response
    Python
    import asyncio
    from infrastructure.twitch.api import Twitch


    async def main():
    token = "xxxxxxxxxxx"
    twitch = Twitch(token=token)

    response = await twitch.get_subscription_id("xrespectrd")
    user = await twitch.get_current_user()
    node = response["data"]["userResultByLogin"]["subscriptionProductsResult"][
    "nodes"
    ][0]
    offer = node["offers"][1]
    product_id = node["id"]
    offer_id = offer["id"]
    channel_id = None
    user_id = user["id"]

    for tag in offer["tagBindings"]:
    if tag["key"] == "channel_id":
    channel_id = str(tag["value"])

    print(product_id, offer_id, channel_id, user_id)
    print()

    r = await twitch.purchase_subscription(
    user_id, offer_id, product_id, channel_id
    )
    print(r)


    if __name__ == "__main__":
    asyncio.run(main())
     
  2. противоположник
    чекни как ты получаешь deviceid и tabSessionid, мб их нужно динамически извлекать
     
    1. противоположник
      а вообще, пробуй выводить channel_id, product_id и offer_id перед оформлением сабки
      Python
      print(f"Product ID: {product_id}, Offer ID: {offer_id}, Channel ID: {channel_id}")
      если channel_id или product_id выдает none, значит запрос get_subscription_id бэкает некорректные данные
  3. Yandex
    Yandex 5 апр 2025 :obcool: 8357 15 дек 2019
    Если не ошибаюсь, то тебе нужно через браузер получить integrity токен, через запрос не получится. el9in может подсказать
     
    5 апр 2025 Изменено
    1. el9in
      Yandex, не предоставляю поддержку.
Top