From 877dd481eaaa0c45313254d81a97aafa601e0a32 Mon Sep 17 00:00:00 2001 From: Tony AVERTY Date: Wed, 7 Oct 2026 09:54:04 +0200 Subject: [PATCH] =?UTF-8?q?=C3=89tape=205=20:=20mise=20=C3=A0=20jour=20en?= =?UTF-8?q?=20direct=20des=20cartes=20Apple=20et=20Google=20Wallet?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Service web PassKit (/api/wallet/apple/v1) : enregistrement des iPhone, cartes modifiées depuis un tag, carte à jour (304 si inchangée), désinscription, logs - Notifications APNs HTTP/2 avec le certificat du Pass Type ID ; jetons expirés oubliés - Google : mise à jour REST du solde et de la prochaine récompense, et de la classe (design du magasin) ; jeton OAuth mis en cache - Chaque crédit / récompense et chaque modification du design de la carte déclenchent la mise à jour (non bloquante pour le comptoir) - WalletModule global ; champ LoyaltyCard.passUpdatedAt + migration SQL Co-Authored-By: Claude Opus 5.5 --- .../2026-10-07-wallet-en-direct.sql | 6 + backend/prisma/schema.prisma | 2 + backend/src/app.module.ts | 2 + .../src/card-design/card-design.service.ts | 9 +- backend/src/counter/counter.module.ts | 3 +- backend/src/enrollment/enrollment.module.ts | 7 +- backend/src/wallet/apns.service.ts | 86 ++++++++++ backend/src/wallet/apple-pass.service.ts | 4 + .../wallet/apple-web-service.controller.ts | 156 +++++++++++++++++ backend/src/wallet/card-updates.service.ts | 61 ++++++- backend/src/wallet/google-wallet.service.ts | 161 ++++++++++++------ backend/src/wallet/wallet.module.ts | 15 ++ 12 files changed, 453 insertions(+), 59 deletions(-) create mode 100644 backend/prisma/manual-migrations/2026-10-07-wallet-en-direct.sql create mode 100644 backend/src/wallet/apns.service.ts create mode 100644 backend/src/wallet/apple-web-service.controller.ts create mode 100644 backend/src/wallet/wallet.module.ts diff --git a/backend/prisma/manual-migrations/2026-10-07-wallet-en-direct.sql b/backend/prisma/manual-migrations/2026-10-07-wallet-en-direct.sql new file mode 100644 index 0000000..f80edcb --- /dev/null +++ b/backend/prisma/manual-migrations/2026-10-07-wallet-en-direct.sql @@ -0,0 +1,6 @@ +-- Mises à jour Wallet en direct (étape 5) — à exécuter UNE fois dans phpMyAdmin sur la base monespacepro, +-- AVANT de déployer le nouveau code. + +-- AlterTable +ALTER TABLE `LoyaltyCard` ADD COLUMN `passUpdatedAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3); + diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index dfbf343..c3330a4 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -134,6 +134,8 @@ model LoyaltyCard { /// Clé secrète des liens client (page de la carte, téléchargement du pass). accessKey String @unique balance Int @default(0) + /// Dernière modification visible dans le Wallet (solde, design du magasin) : sert aux mises à jour Apple. + passUpdatedAt DateTime @default(now()) lastCreditAt DateTime? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt diff --git a/backend/src/app.module.ts b/backend/src/app.module.ts index be46957..99868af 100644 --- a/backend/src/app.module.ts +++ b/backend/src/app.module.ts @@ -11,6 +11,7 @@ import { EnrollmentModule } from './enrollment/enrollment.module'; import { CounterModule } from './counter/counter.module'; import { ContactModule } from './contact/contact.controller'; import { BillingModule } from './billing/billing.controller'; +import { WalletModule } from './wallet/wallet.module'; import { HealthController } from './health.controller'; @Module({ @@ -21,6 +22,7 @@ import { HealthController } from './health.controller'; AuthModule, AdminModule, MailModule, + WalletModule, EnrollmentModule, CounterModule, ContactModule, diff --git a/backend/src/card-design/card-design.service.ts b/backend/src/card-design/card-design.service.ts index 6b47ab6..9020d3e 100644 --- a/backend/src/card-design/card-design.service.ts +++ b/backend/src/card-design/card-design.service.ts @@ -5,6 +5,7 @@ import { join } from 'path'; import { randomBytes } from 'crypto'; import { PrismaService } from '../prisma/prisma.service'; import { SaveCardDesignDto } from './dto/card-design.dto'; +import { CardUpdatesService } from '../wallet/card-updates.service'; export type ImageKind = 'logo' | 'strip'; @@ -13,7 +14,10 @@ export const UPLOADS_DIR = join(process.cwd(), 'uploads'); @Injectable() export class CardDesignService { - constructor(private prisma: PrismaService) {} + constructor( + private prisma: PrismaService, + private cardUpdates: CardUpdatesService, + ) {} async get(storeId: string) { await this.ensureStore(storeId); @@ -62,6 +66,8 @@ export class CardDesignService { } } }); + // Les cartes déjà dans les Wallets reprennent le nouveau design. + this.cardUpdates.notifyStore(storeId); return this.get(storeId); } @@ -84,6 +90,7 @@ export class CardDesignService { const previous = design[field]; await this.prisma.cardDesign.update({ where: { storeId }, data: { [field]: `stores/${storeId}/${name}` } }); if (previous) await unlink(join(UPLOADS_DIR, previous)).catch(() => undefined); + this.cardUpdates.notifyStore(storeId); return this.get(storeId); } diff --git a/backend/src/counter/counter.module.ts b/backend/src/counter/counter.module.ts index fe55c46..c0943cb 100644 --- a/backend/src/counter/counter.module.ts +++ b/backend/src/counter/counter.module.ts @@ -1,11 +1,10 @@ import { Module } from '@nestjs/common'; import { CounterController } from './counter.controller'; import { CounterService } from './counter.service'; -import { CardUpdatesService } from '../wallet/card-updates.service'; /** Comptoir : scan, crédit, récompenses, historique (app Pro). */ @Module({ controllers: [CounterController], - providers: [CounterService, CardUpdatesService], + providers: [CounterService], }) export class CounterModule {} diff --git a/backend/src/enrollment/enrollment.module.ts b/backend/src/enrollment/enrollment.module.ts index f99abaf..d5d460d 100644 --- a/backend/src/enrollment/enrollment.module.ts +++ b/backend/src/enrollment/enrollment.module.ts @@ -1,13 +1,10 @@ import { Module } from '@nestjs/common'; import { EnrollmentApiController, EnrollmentPagesController } from './enrollment.controller'; import { EnrollmentService } from './enrollment.service'; -import { ApplePassService } from '../wallet/apple-pass.service'; -import { GoogleWalletService } from '../wallet/google-wallet.service'; -/** Inscription des clients finaux et remise des cartes Wallet. */ +/** Inscription des clients finaux et remise des cartes Wallet (services : WalletModule). */ @Module({ controllers: [EnrollmentPagesController, EnrollmentApiController], - providers: [EnrollmentService, ApplePassService, GoogleWalletService], - exports: [ApplePassService, GoogleWalletService], + providers: [EnrollmentService], }) export class EnrollmentModule {} diff --git a/backend/src/wallet/apns.service.ts b/backend/src/wallet/apns.service.ts new file mode 100644 index 0000000..00fbb18 --- /dev/null +++ b/backend/src/wallet/apns.service.ts @@ -0,0 +1,86 @@ +import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { readFileSync } from 'fs'; +import { ClientHttp2Session, connect } from 'http2'; + +/** + * Notifications Apple Wallet (APNs). Pour un pass, la notification est vide : + * elle demande seulement à l'iPhone de redemander la carte au service web. + * Authentification par le certificat du Pass Type ID (le même que pour signer). + */ +@Injectable() +export class ApnsService implements OnModuleDestroy { + private readonly logger = new Logger(ApnsService.name); + private session: ClientHttp2Session | null = null; + + constructor(private config: ConfigService) {} + + get enabled() { + const a = this.config.get('apple'); + return !!(a.passTypeId && a.signerCert && a.signerKey); + } + + /** Renvoie les jetons à oublier (appareil désinscrit : réponse 410). */ + async push(pushTokens: string[]): Promise { + if (!this.enabled || !pushTokens.length) return []; + const gone: string[] = []; + await Promise.all( + pushTokens.map(async (token) => { + try { + const status = await this.send(token); + if (status === 410) gone.push(token); + else if (status !== 200) this.logger.warn(`APNs a répondu ${status} pour un appareil`); + } catch (e) { + this.logger.error(`APNs injoignable : ${(e as Error).message}`); + this.reset(); + } + }), + ); + return gone; + } + + private send(token: string): Promise { + return new Promise((resolve, reject) => { + const req = this.connection().request({ + ':method': 'POST', + ':path': `/3/device/${token}`, + 'apns-topic': this.config.get('apple.passTypeId'), + 'apns-push-type': 'alert', + 'apns-priority': '10', + 'content-type': 'application/json', + }); + req.setTimeout(10_000, () => req.close()); + req.on('response', (headers) => resolve(Number(headers[':status']))); + req.on('error', reject); + req.resume(); + req.end('{}'); + }); + } + + /** Connexion HTTP/2 réutilisée (Apple recommande de la garder ouverte). */ + private connection(): ClientHttp2Session { + if (this.session && !this.session.closed && !this.session.destroyed) return this.session; + const a = this.config.get('apple'); + this.session = connect('https://api.push.apple.com:443', { + cert: readFileSync(a.signerCert), + key: readFileSync(a.signerKey), + passphrase: a.signerKeyPassphrase, + }); + this.session.on('error', (e) => { + this.logger.error(`Session APNs : ${e.message}`); + this.reset(); + }); + this.session.on('goaway', () => this.reset()); + this.session.unref(); // ne retient pas l'arrêt du process + return this.session; + } + + private reset() { + this.session?.destroy(); + this.session = null; + } + + onModuleDestroy() { + this.reset(); + } +} diff --git a/backend/src/wallet/apple-pass.service.ts b/backend/src/wallet/apple-pass.service.ts index 63f0ed6..d8dc4d6 100644 --- a/backend/src/wallet/apple-pass.service.ts +++ b/backend/src/wallet/apple-pass.service.ts @@ -39,6 +39,8 @@ export class ApplePassService { const unit = unitLabel(card); const nextReward = nextRewardText(card); + const publicUrl: string = this.config.get('publicUrl')!; + const webServiceURL = publicUrl.startsWith('https://') ? `${publicUrl}/api/wallet/apple` : null; const passJson = { formatVersion: 1, passTypeIdentifier: this.config.get('apple.passTypeId'), @@ -51,6 +53,8 @@ export class ApplePassService { labelColor: rgb(design.labelColor), ...(design.logoPath ? {} : { logoText: card.store.name }), sharingProhibited: true, + // Service web des mises à jour en direct (Apple l'exige en HTTPS). + ...(webServiceURL && { webServiceURL, authenticationToken: card.authToken }), barcodes: [{ format: 'PKBarcodeFormatQR', message: card.serial, messageEncoding: 'iso-8859-1' }], storeCard: { headerFields: [{ key: 'balance-header', label: unit.toUpperCase(), value: card.balance }], diff --git a/backend/src/wallet/apple-web-service.controller.ts b/backend/src/wallet/apple-web-service.controller.ts new file mode 100644 index 0000000..d6632b0 --- /dev/null +++ b/backend/src/wallet/apple-web-service.controller.ts @@ -0,0 +1,156 @@ +import { + Body, + Controller, + Delete, + Get, + Headers, + HttpCode, + HttpStatus, + Logger, + Param, + Post, + Query, + Res, + UnauthorizedException, +} from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { SkipThrottle } from '@nestjs/throttler'; +import { IsString, Length } from 'class-validator'; +import type { Response } from 'express'; +import { timingSafeEqual } from 'crypto'; +import { PrismaService } from '../prisma/prisma.service'; +import { ApplePassService } from './apple-pass.service'; +import { CARD_WITH_CONTEXT } from './wallet.types'; + +class RegisterDto { + @IsString() @Length(1, 200) + pushToken!: string; +} + +/** + * Service web Apple Wallet (PassKit Web Service), appelé par les iPhone : + * https://developer.apple.com/documentation/walletpasses/adding-a-web-service-to-update-passes + * Adresse déclarée dans chaque carte : {PUBLIC_URL}/api/wallet/apple + */ +@Controller('wallet/apple/v1') +@SkipThrottle() +export class AppleWebServiceController { + private readonly logger = new Logger(AppleWebServiceController.name); + + constructor( + private prisma: PrismaService, + private config: ConfigService, + private passes: ApplePassService, + ) {} + + /** Un iPhone a ajouté la carte : on retient l'appareil pour lui envoyer les mises à jour. */ + @Post('devices/:deviceId/registrations/:passTypeId/:serial') + async register( + @Param('deviceId') deviceId: string, + @Param('passTypeId') passTypeId: string, + @Param('serial') serial: string, + @Headers('authorization') auth: string | undefined, + @Body() dto: RegisterDto, + @Res() res: Response, + ) { + const card = await this.authorizedCard(passTypeId, serial, auth); + const device = await this.prisma.appleDevice.upsert({ + where: { deviceLibraryId: deviceId }, + create: { deviceLibraryId: deviceId, pushToken: dto.pushToken }, + update: { pushToken: dto.pushToken }, + }); + const existing = await this.prisma.appleRegistration.findUnique({ + where: { deviceId_cardId: { deviceId: device.id, cardId: card.id } }, + }); + if (existing) return res.status(HttpStatus.OK).send(); + await this.prisma.appleRegistration.create({ data: { deviceId: device.id, cardId: card.id } }); + res.status(HttpStatus.CREATED).send(); + } + + /** Quelles cartes de cet appareil ont changé depuis la dernière fois ? */ + @Get('devices/:deviceId/registrations/:passTypeId') + async updatedSerials( + @Param('deviceId') deviceId: string, + @Param('passTypeId') passTypeId: string, + @Query('passesUpdatedSince') since: string | undefined, + @Res() res: Response, + ) { + if (passTypeId !== this.config.get('apple.passTypeId')) return res.status(HttpStatus.NOT_FOUND).send(); + const after = since && /^\d+$/.test(since) ? new Date(Number(since)) : null; + const cards = await this.prisma.loyaltyCard.findMany({ + where: { + devices: { some: { device: { deviceLibraryId: deviceId } } }, + ...(after && { passUpdatedAt: { gt: after } }), + }, + select: { serial: true, passUpdatedAt: true }, + }); + if (!cards.length) return res.status(HttpStatus.NO_CONTENT).send(); + // Le « tag » est l'horodatage (ms) de la modification la plus récente. + const lastUpdated = Math.max(...cards.map((c) => c.passUpdatedAt.getTime())); + res.status(HttpStatus.OK).json({ serialNumbers: cards.map((c) => c.serial), lastUpdated: String(lastUpdated) }); + } + + /** La carte a été retirée du Wallet de cet appareil. */ + @Delete('devices/:deviceId/registrations/:passTypeId/:serial') + @HttpCode(200) + async unregister( + @Param('deviceId') deviceId: string, + @Param('passTypeId') passTypeId: string, + @Param('serial') serial: string, + @Headers('authorization') auth: string | undefined, + ) { + const card = await this.authorizedCard(passTypeId, serial, auth); + const device = await this.prisma.appleDevice.findUnique({ where: { deviceLibraryId: deviceId } }); + if (device) { + await this.prisma.appleRegistration.deleteMany({ where: { deviceId: device.id, cardId: card.id } }); + const left = await this.prisma.appleRegistration.count({ where: { deviceId: device.id } }); + if (left === 0) await this.prisma.appleDevice.delete({ where: { id: device.id } }); + } + return {}; + } + + /** Carte à jour (après une notification, ou au rafraîchissement manuel). */ + @Get('passes/:passTypeId/:serial') + async latest( + @Param('passTypeId') passTypeId: string, + @Param('serial') serial: string, + @Headers('authorization') auth: string | undefined, + @Headers('if-modified-since') ifModifiedSince: string | undefined, + @Res() res: Response, + ) { + const card = await this.authorizedCard(passTypeId, serial, auth); + const modifiedSec = Math.floor(card.passUpdatedAt.getTime() / 1000); + if (ifModifiedSince) { + const sinceSec = Math.floor(new Date(ifModifiedSince).getTime() / 1000); + if (!Number.isNaN(sinceSec) && modifiedSec <= sinceSec) return res.status(HttpStatus.NOT_MODIFIED).send(); + } + const pkpass = await this.passes.generate(card); + res + .status(HttpStatus.OK) + .type('application/vnd.apple.pkpass') + .setHeader('Last-Modified', card.passUpdatedAt.toUTCString()) + .setHeader('Cache-Control', 'no-store') + .send(pkpass); + } + + /** Messages d'erreur envoyés par les iPhone (diagnostic). */ + @Post('log') + @HttpCode(200) + log(@Body() body: Record) { + const logs = Array.isArray(body?.logs) ? body.logs.slice(0, 20) : []; + for (const line of logs) this.logger.warn(`iPhone : ${String(line).slice(0, 500)}`); + return {}; + } + + /** Vérifie l'en-tête « Authorization: ApplePass » de la carte. */ + private async authorizedCard(passTypeId: string, serial: string, auth: string | undefined) { + if (passTypeId !== this.config.get('apple.passTypeId')) throw new UnauthorizedException(); + const token = auth?.startsWith('ApplePass ') ? auth.slice('ApplePass '.length) : ''; + const card = await this.prisma.loyaltyCard.findUnique({ where: { serial }, include: CARD_WITH_CONTEXT }); + if (!card || !token) throw new UnauthorizedException(); + const a = Buffer.from(card.authToken); + const b = Buffer.from(token); + if (a.length !== b.length || !timingSafeEqual(a, b)) throw new UnauthorizedException(); + return card; + } +} diff --git a/backend/src/wallet/card-updates.service.ts b/backend/src/wallet/card-updates.service.ts index 30b0f62..4f7c62b 100644 --- a/backend/src/wallet/card-updates.service.ts +++ b/backend/src/wallet/card-updates.service.ts @@ -1,14 +1,69 @@ import { Injectable, Logger } from '@nestjs/common'; +import { PrismaService } from '../prisma/prisma.service'; +import { ApnsService } from './apns.service'; +import { GoogleWalletService } from './google-wallet.service'; +import { CARD_WITH_CONTEXT } from './wallet.types'; /** - * Point d'entrée unique « le solde d'une carte a changé ». - * Étape 5 : pousse la mise à jour vers Apple (APNs) et Google Wallet. + * Point d'entrée unique « une carte a changé » : pousse la mise à jour vers + * Apple Wallet (notification APNs → l'iPhone redemande la carte) et Google + * Wallet (mise à jour de l'objet). Jamais bloquant : appelé après la réponse + * à l'employé, une erreur ici n'annule pas l'opération au comptoir. */ @Injectable() export class CardUpdatesService { private readonly logger = new Logger(CardUpdatesService.name); + constructor( + private prisma: PrismaService, + private apns: ApnsService, + private google: GoogleWalletService, + ) {} + + /** Solde ou récompense d'une carte modifiés. */ notify(cardId: string) { - this.logger.debug(`Carte ${cardId} modifiée — mise à jour Wallet à brancher (étape 5)`); + void this.run(`carte ${cardId}`, async () => { + const card = await this.prisma.loyaltyCard.update({ + where: { id: cardId }, + data: { passUpdatedAt: new Date() }, + include: { ...CARD_WITH_CONTEXT, devices: { include: { device: true } } }, + }); + await Promise.all([ + this.pushApple(card.devices.map((r) => r.device.pushToken)), + this.google.updateObject(card), + ]); + }); + } + + /** Design du magasin modifié (logo, couleurs, récompenses) : toutes ses cartes. */ + notifyStore(storeId: string) { + void this.run(`magasin ${storeId}`, async () => { + await this.prisma.loyaltyCard.updateMany({ where: { storeId }, data: { passUpdatedAt: new Date() } }); + const store = await this.prisma.store.findUniqueOrThrow({ + where: { id: storeId }, + include: CARD_WITH_CONTEXT.store.include, + }); + const devices = await this.prisma.appleDevice.findMany({ + where: { registrations: { some: { card: { storeId } } } }, + select: { pushToken: true }, + }); + await Promise.all([this.pushApple(devices.map((d) => d.pushToken)), this.google.updateClass(store)]); + // Les récompenses apparaissent sur chaque carte Google (objet) : on les met à jour aussi. + const cards = await this.prisma.loyaltyCard.findMany({ where: { storeId }, include: CARD_WITH_CONTEXT }); + for (const card of cards) await this.google.updateObject(card).catch((e) => this.logger.warn(e.message)); + }); + } + + private async pushApple(tokens: string[]) { + const gone = await this.apns.push([...new Set(tokens)]); + if (gone.length) await this.prisma.appleDevice.deleteMany({ where: { pushToken: { in: gone } } }); + } + + private async run(label: string, task: () => Promise) { + try { + await task(); + } catch (e) { + this.logger.error(`Mise à jour Wallet (${label}) : ${(e as Error).message}`); + } } } diff --git a/backend/src/wallet/google-wallet.service.ts b/backend/src/wallet/google-wallet.service.ts index 37226df..d21528e 100644 --- a/backend/src/wallet/google-wallet.service.ts +++ b/backend/src/wallet/google-wallet.service.ts @@ -5,18 +5,22 @@ import { importPKCS8, SignJWT } from 'jose'; import { CardWithContext, nextRewardText, rewardsText, unitLabel } from './wallet.types'; type ServiceAccount = { client_email: string; private_key: string }; +type StoreForClass = CardWithContext['store']; + +const API = 'https://walletobjects.googleapis.com/walletobjects/v1'; /** - * Google Wallet : lien « Ajouter à Google Wallet » sous forme de JWT signé - * par le compte de service, qui embarque la classe (le programme du - * magasin) et l'objet (la carte du client). Aucun appel à l'API Google - * n'est nécessaire à l'inscription ; les mises à jour du solde passeront - * par l'API REST (étape 5). + * Google Wallet. + * - Ajout : lien « Ajouter à Google Wallet » (JWT signé par le compte de + * service) qui embarque la classe (le programme du magasin) et l'objet + * (la carte du client) ; aucun appel à l'API à l'inscription. + * - Mises à jour : API REST (solde, prochaine récompense, design du magasin). */ @Injectable() export class GoogleWalletService { private readonly logger = new Logger(GoogleWalletService.name); private account: ServiceAccount | null | undefined; + private token: { value: string; expiresAt: number } | null = null; constructor(private config: ConfigService) {} @@ -35,56 +39,15 @@ export class GoogleWalletService { async saveUrl(card: CardWithContext): Promise { const account = this.loadAccount(); if (!account) throw new ServiceUnavailableException('Google Wallet n’est pas encore configuré'); - const design = card.store.cardDesign; - if (!design) throw new ServiceUnavailableException('Carte non conçue'); + if (!card.store.cardDesign) throw new ServiceUnavailableException('Carte non conçue'); const publicUrl: string = this.config.get('publicUrl')!; const webUrl: string = this.config.get('webUrl')!; - const image = (path: string, description: string) => ({ - sourceUri: { uri: `${publicUrl}/uploads/${path}` }, - contentDescription: { defaultValue: { language: 'fr-FR', value: description } }, - }); - // Google exige un logo : sans logo du magasin, on met le symbole MonEspacePro. - const programLogo = design.logoPath - ? image(design.logoPath, `Logo ${card.store.name}`) - : { - sourceUri: { uri: `${publicUrl}/static/logo-defaut.png` }, - contentDescription: { defaultValue: { language: 'fr-FR', value: card.store.name } }, - }; - - const loyaltyClass = { - id: this.classId(card.storeId), - issuerName: card.store.name, - programName: design.programName, - programLogo, - ...(design.stripPath && { heroImage: image(design.stripPath, card.store.name) }), - hexBackgroundColor: design.backgroundColor, - reviewStatus: 'UNDER_REVIEW', - countryCode: 'FR', - multipleDevicesAndHoldersAllowedStatus: 'ONE_USER_ALL_DEVICES', - }; - const loyaltyObject = { - id: this.objectId(card.serial), - classId: loyaltyClass.id, - state: 'ACTIVE', - accountId: card.serial, - accountName: card.customer.firstName, - loyaltyPoints: { label: unitLabel(card), balance: { int: card.balance } }, - barcode: { type: 'QR_CODE', value: card.serial }, - textModulesData: [ - ...(nextRewardText(card) ? [{ id: 'next_reward', header: 'Prochaine récompense', body: nextRewardText(card)! }] : []), - { id: 'rewards', header: 'Toutes les récompenses', body: rewardsText(card) }, - ], - linksModuleData: { - uris: [{ id: 'manage', uri: `${webUrl}/carte/${card.serial}?k=${card.accessKey}`, description: 'Ma carte' }], - }, - }; - const key = await importPKCS8(account.private_key, 'RS256'); const jwt = await new SignJWT({ origins: [publicUrl, webUrl], typ: 'savetowallet', - payload: { loyaltyClasses: [loyaltyClass], loyaltyObjects: [loyaltyObject] }, + payload: { loyaltyClasses: [this.buildClass(card.store)], loyaltyObjects: [this.buildObject(card)] }, }) .setProtectedHeader({ alg: 'RS256', typ: 'JWT' }) .setIssuer(account.client_email) @@ -94,6 +57,108 @@ export class GoogleWalletService { return `https://pay.google.com/gp/v/save/${jwt}`; } + /** + * Met à jour la carte du client (solde, prochaine récompense). + * Carte jamais ajoutée à Google Wallet → 404, rien à faire. + */ + async updateObject(card: CardWithContext) { + if (!this.enabled || !card.store.cardDesign) return; + const o = this.buildObject(card); + await this.call('PATCH', `/loyaltyObject/${encodeURIComponent(o.id)}`, { + loyaltyPoints: o.loyaltyPoints, + textModulesData: o.textModulesData, + accountName: o.accountName, + }); + } + + /** Répercute le design du magasin (nom, logo, couleur, bandeau) sur toutes ses cartes Google. */ + async updateClass(store: StoreForClass) { + if (!this.enabled || !store.cardDesign) return; + const c = this.buildClass(store); + await this.call('PATCH', `/loyaltyClass/${encodeURIComponent(c.id)}`, c); + } + + private buildClass(store: StoreForClass) { + const design = store.cardDesign!; + const publicUrl: string = this.config.get('publicUrl')!; + const image = (path: string, description: string) => ({ + sourceUri: { uri: `${publicUrl}/uploads/${path}` }, + contentDescription: { defaultValue: { language: 'fr-FR', value: description } }, + }); + return { + id: this.classId(store.id), + issuerName: store.name, + programName: design.programName, + // Google exige un logo : sans logo du magasin, on met le symbole MonEspacePro. + programLogo: design.logoPath + ? image(design.logoPath, `Logo ${store.name}`) + : { + sourceUri: { uri: `${publicUrl}/static/logo-defaut.png` }, + contentDescription: { defaultValue: { language: 'fr-FR', value: store.name } }, + }, + ...(design.stripPath && { heroImage: image(design.stripPath, store.name) }), + hexBackgroundColor: design.backgroundColor, + reviewStatus: 'UNDER_REVIEW', + countryCode: 'FR', + multipleDevicesAndHoldersAllowedStatus: 'ONE_USER_ALL_DEVICES', + }; + } + + private buildObject(card: CardWithContext) { + const webUrl: string = this.config.get('webUrl')!; + const next = nextRewardText(card); + return { + id: this.objectId(card.serial), + classId: this.classId(card.storeId), + state: 'ACTIVE', + accountId: card.serial, + accountName: card.customer.firstName, + loyaltyPoints: { label: unitLabel(card), balance: { int: card.balance } }, + barcode: { type: 'QR_CODE', value: card.serial }, + textModulesData: [ + ...(next ? [{ id: 'next_reward', header: 'Prochaine récompense', body: next }] : []), + { id: 'rewards', header: 'Toutes les récompenses', body: rewardsText(card) }, + ], + linksModuleData: { + uris: [{ id: 'manage', uri: `${webUrl}/carte/${card.serial}?k=${card.accessKey}`, description: 'Ma carte' }], + }, + }; + } + + /** Appel REST authentifié ; 404 (carte ou classe jamais créée chez Google) n'est pas une erreur. */ + private async call(method: string, path: string, body: unknown) { + const res = await fetch(`${API}${path}`, { + method, + headers: { Authorization: `Bearer ${await this.accessToken()}`, 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }); + if (res.status === 404) return; + if (!res.ok) throw new Error(`Google Wallet ${method} ${path} → ${res.status} ${(await res.text()).slice(0, 300)}`); + } + + /** Jeton OAuth du compte de service, mis en cache jusqu'à 5 min avant expiration. */ + private async accessToken(): Promise { + if (this.token && this.token.expiresAt > Date.now() + 5 * 60_000) return this.token.value; + const account = this.loadAccount()!; + const key = await importPKCS8(account.private_key, 'RS256'); + const assertion = await new SignJWT({ scope: 'https://www.googleapis.com/auth/wallet_object.issuer' }) + .setProtectedHeader({ alg: 'RS256', typ: 'JWT' }) + .setIssuer(account.client_email) + .setAudience('https://oauth2.googleapis.com/token') + .setIssuedAt() + .setExpirationTime('1h') + .sign(key); + const res = await fetch('https://oauth2.googleapis.com/token', { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', assertion }), + }); + if (!res.ok) throw new Error(`Jeton Google refusé : ${res.status}`); + const data = (await res.json()) as { access_token: string; expires_in: number }; + this.token = { value: data.access_token, expiresAt: Date.now() + data.expires_in * 1000 }; + return this.token.value; + } + private loadAccount(): ServiceAccount | null { if (this.account !== undefined) return this.account; const file: string = this.config.get('google.serviceAccountFile')!; diff --git a/backend/src/wallet/wallet.module.ts b/backend/src/wallet/wallet.module.ts new file mode 100644 index 0000000..53b6fa1 --- /dev/null +++ b/backend/src/wallet/wallet.module.ts @@ -0,0 +1,15 @@ +import { Global, Module } from '@nestjs/common'; +import { ApplePassService } from './apple-pass.service'; +import { AppleWebServiceController } from './apple-web-service.controller'; +import { ApnsService } from './apns.service'; +import { CardUpdatesService } from './card-updates.service'; +import { GoogleWalletService } from './google-wallet.service'; + +/** Cartes Apple / Google Wallet et leurs mises à jour en direct. */ +@Global() +@Module({ + controllers: [AppleWebServiceController], + providers: [ApplePassService, GoogleWalletService, ApnsService, CardUpdatesService], + exports: [ApplePassService, GoogleWalletService, CardUpdatesService], +}) +export class WalletModule {}