Я использую следующий код для реализации уведомлений Apple Server, но он дает мне ошибку «неверный заголовок JWT». Я использую Storekit2 для покупки подписок в приложении, и я использую бэкэнд js js для отслеживания обновлений подписки. SignedPayload в ответ от Apple. Как заставить его отправить v2? < /P>
const APPLE_JWKS_URL = "https://appleid.apple.com/auth/keys";
const getApplePublicKey = async (kid) => {
try {
const response = await axios.get(APPLE_JWKS_URL);
const keys = response.data.keys;
const key = keys.find((k) => k.kid === kid);
if (!key) {
throw new Error("Matching key not found");
}
return jwksClient.certToPEM({
kty: key.kty,
n: key.n,
e: key.e,
});
} catch (error) {
console.error("Failed to fetch Apple's public key:", error);
throw new Error("Could not get Apple public key");
}
};
// Function to verify Apple's JWT signature
const verifyAppleJWT = async (token) => {
try {
const decodedHeader = jwt.decode(token, { complete: true });
if (!decodedHeader || !decodedHeader.header.kid) {
throw new Error("Invalid JWT header");
}
const publicKey = await getApplePublicKey(decodedHeader.header.kid);
return jwt.verify(token, publicKey, { algorithms: ["RS256"] });
} catch (error) {
console.error("JWT verification failed:", error);
return null;
}
};
// Apple Server Notification Endpoint
router.post("/apple-server-notifications", async (req, res) => {
try {
const { signedPayload } = req.body;
if (!signedPayload) {
return res.status(400).json({ error: "Missing signedPayload" });
}
// Verify the JWT signature with Apple's public key
const payload = await verifyAppleJWT(signedPayload);
if (!payload) {
return res.status(400).json({ error: "Invalid notification" });
}
console.log("Verified Notification:", JSON.stringify(payload, null, 2));
// Extract relevant data
const eventType = payload.notificationType;
const originalTransactionId = payload.data.originalTransactionId;
// Handle subscription events
switch (eventType) {
case "SUBSCRIBED":
case "DID_RENEW":
await updateSubscription(originalTransactionId, "active");
break;
case "EXPIRED":
await updateSubscription(originalTransactionId, "expired");
break;
case "CANCEL":
await updateSubscription(originalTransactionId, "canceled");
break;
case "DID_REVOKE":
await updateSubscription(originalTransactionId, "revoked");
break;
default:
console.log(`Unhandled event type: ${eventType}`);
}
res.status(200).json({ message: "Notification processed" });
} catch (error) {
console.error("Error handling notification:", error);
res.status(500).json({ error: "Internal Server Error" });
}
});
Подробнее здесь: https://stackoverflow.com/questions/794 ... lid-header
Уведомления Apple Server Jwt Invalid Loader ⇐ IOS
Программируем под IOS
-
Anonymous
1749980439
Anonymous
Я использую следующий код для реализации уведомлений Apple Server, но он дает мне ошибку «неверный заголовок JWT». Я использую Storekit2 для покупки подписок в приложении, и я использую бэкэнд js js для отслеживания обновлений подписки. SignedPayload в ответ от Apple. Как заставить его отправить v2? < /P>
const APPLE_JWKS_URL = "https://appleid.apple.com/auth/keys";
const getApplePublicKey = async (kid) => {
try {
const response = await axios.get(APPLE_JWKS_URL);
const keys = response.data.keys;
const key = keys.find((k) => k.kid === kid);
if (!key) {
throw new Error("Matching key not found");
}
return jwksClient.certToPEM({
kty: key.kty,
n: key.n,
e: key.e,
});
} catch (error) {
console.error("Failed to fetch Apple's public key:", error);
throw new Error("Could not get Apple public key");
}
};
// Function to verify Apple's JWT signature
const verifyAppleJWT = async (token) => {
try {
const decodedHeader = jwt.decode(token, { complete: true });
if (!decodedHeader || !decodedHeader.header.kid) {
throw new Error("Invalid JWT header");
}
const publicKey = await getApplePublicKey(decodedHeader.header.kid);
return jwt.verify(token, publicKey, { algorithms: ["RS256"] });
} catch (error) {
console.error("JWT verification failed:", error);
return null;
}
};
// Apple Server Notification Endpoint
router.post("/apple-server-notifications", async (req, res) => {
try {
const { signedPayload } = req.body;
if (!signedPayload) {
return res.status(400).json({ error: "Missing signedPayload" });
}
// Verify the JWT signature with Apple's public key
const payload = await verifyAppleJWT(signedPayload);
if (!payload) {
return res.status(400).json({ error: "Invalid notification" });
}
console.log("Verified Notification:", JSON.stringify(payload, null, 2));
// Extract relevant data
const eventType = payload.notificationType;
const originalTransactionId = payload.data.originalTransactionId;
// Handle subscription events
switch (eventType) {
case "SUBSCRIBED":
case "DID_RENEW":
await updateSubscription(originalTransactionId, "active");
break;
case "EXPIRED":
await updateSubscription(originalTransactionId, "expired");
break;
case "CANCEL":
await updateSubscription(originalTransactionId, "canceled");
break;
case "DID_REVOKE":
await updateSubscription(originalTransactionId, "revoked");
break;
default:
console.log(`Unhandled event type: ${eventType}`);
}
res.status(200).json({ message: "Notification processed" });
} catch (error) {
console.error("Error handling notification:", error);
res.status(500).json({ error: "Internal Server Error" });
}
});
Подробнее здесь: [url]https://stackoverflow.com/questions/79449316/apple-server-notifications-jwt-invalid-header[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия