Étape 5 : mise à jour en direct des cartes Apple et Google Wallet
- 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 <noreply@anthropic.com>
This commit is contained in:
parent
bc55f7148d
commit
877dd481ea
12 changed files with 453 additions and 59 deletions
|
|
@ -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);
|
||||||
|
|
||||||
|
|
@ -134,6 +134,8 @@ model LoyaltyCard {
|
||||||
/// Clé secrète des liens client (page de la carte, téléchargement du pass).
|
/// Clé secrète des liens client (page de la carte, téléchargement du pass).
|
||||||
accessKey String @unique
|
accessKey String @unique
|
||||||
balance Int @default(0)
|
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?
|
lastCreditAt DateTime?
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,7 @@ import { EnrollmentModule } from './enrollment/enrollment.module';
|
||||||
import { CounterModule } from './counter/counter.module';
|
import { CounterModule } from './counter/counter.module';
|
||||||
import { ContactModule } from './contact/contact.controller';
|
import { ContactModule } from './contact/contact.controller';
|
||||||
import { BillingModule } from './billing/billing.controller';
|
import { BillingModule } from './billing/billing.controller';
|
||||||
|
import { WalletModule } from './wallet/wallet.module';
|
||||||
import { HealthController } from './health.controller';
|
import { HealthController } from './health.controller';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
|
|
@ -21,6 +22,7 @@ import { HealthController } from './health.controller';
|
||||||
AuthModule,
|
AuthModule,
|
||||||
AdminModule,
|
AdminModule,
|
||||||
MailModule,
|
MailModule,
|
||||||
|
WalletModule,
|
||||||
EnrollmentModule,
|
EnrollmentModule,
|
||||||
CounterModule,
|
CounterModule,
|
||||||
ContactModule,
|
ContactModule,
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@ import { join } from 'path';
|
||||||
import { randomBytes } from 'crypto';
|
import { randomBytes } from 'crypto';
|
||||||
import { PrismaService } from '../prisma/prisma.service';
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
import { SaveCardDesignDto } from './dto/card-design.dto';
|
import { SaveCardDesignDto } from './dto/card-design.dto';
|
||||||
|
import { CardUpdatesService } from '../wallet/card-updates.service';
|
||||||
|
|
||||||
export type ImageKind = 'logo' | 'strip';
|
export type ImageKind = 'logo' | 'strip';
|
||||||
|
|
||||||
|
|
@ -13,7 +14,10 @@ export const UPLOADS_DIR = join(process.cwd(), 'uploads');
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class CardDesignService {
|
export class CardDesignService {
|
||||||
constructor(private prisma: PrismaService) {}
|
constructor(
|
||||||
|
private prisma: PrismaService,
|
||||||
|
private cardUpdates: CardUpdatesService,
|
||||||
|
) {}
|
||||||
|
|
||||||
async get(storeId: string) {
|
async get(storeId: string) {
|
||||||
await this.ensureStore(storeId);
|
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);
|
return this.get(storeId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -84,6 +90,7 @@ export class CardDesignService {
|
||||||
const previous = design[field];
|
const previous = design[field];
|
||||||
await this.prisma.cardDesign.update({ where: { storeId }, data: { [field]: `stores/${storeId}/${name}` } });
|
await this.prisma.cardDesign.update({ where: { storeId }, data: { [field]: `stores/${storeId}/${name}` } });
|
||||||
if (previous) await unlink(join(UPLOADS_DIR, previous)).catch(() => undefined);
|
if (previous) await unlink(join(UPLOADS_DIR, previous)).catch(() => undefined);
|
||||||
|
this.cardUpdates.notifyStore(storeId);
|
||||||
return this.get(storeId);
|
return this.get(storeId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,10 @@
|
||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { CounterController } from './counter.controller';
|
import { CounterController } from './counter.controller';
|
||||||
import { CounterService } from './counter.service';
|
import { CounterService } from './counter.service';
|
||||||
import { CardUpdatesService } from '../wallet/card-updates.service';
|
|
||||||
|
|
||||||
/** Comptoir : scan, crédit, récompenses, historique (app Pro). */
|
/** Comptoir : scan, crédit, récompenses, historique (app Pro). */
|
||||||
@Module({
|
@Module({
|
||||||
controllers: [CounterController],
|
controllers: [CounterController],
|
||||||
providers: [CounterService, CardUpdatesService],
|
providers: [CounterService],
|
||||||
})
|
})
|
||||||
export class CounterModule {}
|
export class CounterModule {}
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,10 @@
|
||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { EnrollmentApiController, EnrollmentPagesController } from './enrollment.controller';
|
import { EnrollmentApiController, EnrollmentPagesController } from './enrollment.controller';
|
||||||
import { EnrollmentService } from './enrollment.service';
|
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({
|
@Module({
|
||||||
controllers: [EnrollmentPagesController, EnrollmentApiController],
|
controllers: [EnrollmentPagesController, EnrollmentApiController],
|
||||||
providers: [EnrollmentService, ApplePassService, GoogleWalletService],
|
providers: [EnrollmentService],
|
||||||
exports: [ApplePassService, GoogleWalletService],
|
|
||||||
})
|
})
|
||||||
export class EnrollmentModule {}
|
export class EnrollmentModule {}
|
||||||
|
|
|
||||||
86
backend/src/wallet/apns.service.ts
Normal file
86
backend/src/wallet/apns.service.ts
Normal file
|
|
@ -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<string[]> {
|
||||||
|
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<number> {
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -39,6 +39,8 @@ export class ApplePassService {
|
||||||
|
|
||||||
const unit = unitLabel(card);
|
const unit = unitLabel(card);
|
||||||
const nextReward = nextRewardText(card);
|
const nextReward = nextRewardText(card);
|
||||||
|
const publicUrl: string = this.config.get('publicUrl')!;
|
||||||
|
const webServiceURL = publicUrl.startsWith('https://') ? `${publicUrl}/api/wallet/apple` : null;
|
||||||
const passJson = {
|
const passJson = {
|
||||||
formatVersion: 1,
|
formatVersion: 1,
|
||||||
passTypeIdentifier: this.config.get('apple.passTypeId'),
|
passTypeIdentifier: this.config.get('apple.passTypeId'),
|
||||||
|
|
@ -51,6 +53,8 @@ export class ApplePassService {
|
||||||
labelColor: rgb(design.labelColor),
|
labelColor: rgb(design.labelColor),
|
||||||
...(design.logoPath ? {} : { logoText: card.store.name }),
|
...(design.logoPath ? {} : { logoText: card.store.name }),
|
||||||
sharingProhibited: true,
|
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' }],
|
barcodes: [{ format: 'PKBarcodeFormatQR', message: card.serial, messageEncoding: 'iso-8859-1' }],
|
||||||
storeCard: {
|
storeCard: {
|
||||||
headerFields: [{ key: 'balance-header', label: unit.toUpperCase(), value: card.balance }],
|
headerFields: [{ key: 'balance-header', label: unit.toUpperCase(), value: card.balance }],
|
||||||
|
|
|
||||||
156
backend/src/wallet/apple-web-service.controller.ts
Normal file
156
backend/src/wallet/apple-web-service.controller.ts
Normal file
|
|
@ -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<string, unknown>) {
|
||||||
|
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 <jeton> » 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,14 +1,69 @@
|
||||||
import { Injectable, Logger } from '@nestjs/common';
|
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é ».
|
* Point d'entrée unique « une carte a changé » : pousse la mise à jour vers
|
||||||
* Étape 5 : pousse la mise à jour vers Apple (APNs) et Google Wallet.
|
* 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()
|
@Injectable()
|
||||||
export class CardUpdatesService {
|
export class CardUpdatesService {
|
||||||
private readonly logger = new Logger(CardUpdatesService.name);
|
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) {
|
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<void>) {
|
||||||
|
try {
|
||||||
|
await task();
|
||||||
|
} catch (e) {
|
||||||
|
this.logger.error(`Mise à jour Wallet (${label}) : ${(e as Error).message}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -5,18 +5,22 @@ import { importPKCS8, SignJWT } from 'jose';
|
||||||
import { CardWithContext, nextRewardText, rewardsText, unitLabel } from './wallet.types';
|
import { CardWithContext, nextRewardText, rewardsText, unitLabel } from './wallet.types';
|
||||||
|
|
||||||
type ServiceAccount = { client_email: string; private_key: string };
|
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é
|
* Google Wallet.
|
||||||
* par le compte de service, qui embarque la classe (le programme du
|
* - Ajout : lien « Ajouter à Google Wallet » (JWT signé par le compte de
|
||||||
* magasin) et l'objet (la carte du client). Aucun appel à l'API Google
|
* service) qui embarque la classe (le programme du magasin) et l'objet
|
||||||
* n'est nécessaire à l'inscription ; les mises à jour du solde passeront
|
* (la carte du client) ; aucun appel à l'API à l'inscription.
|
||||||
* par l'API REST (étape 5).
|
* - Mises à jour : API REST (solde, prochaine récompense, design du magasin).
|
||||||
*/
|
*/
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class GoogleWalletService {
|
export class GoogleWalletService {
|
||||||
private readonly logger = new Logger(GoogleWalletService.name);
|
private readonly logger = new Logger(GoogleWalletService.name);
|
||||||
private account: ServiceAccount | null | undefined;
|
private account: ServiceAccount | null | undefined;
|
||||||
|
private token: { value: string; expiresAt: number } | null = null;
|
||||||
|
|
||||||
constructor(private config: ConfigService) {}
|
constructor(private config: ConfigService) {}
|
||||||
|
|
||||||
|
|
@ -35,56 +39,15 @@ export class GoogleWalletService {
|
||||||
async saveUrl(card: CardWithContext): Promise<string> {
|
async saveUrl(card: CardWithContext): Promise<string> {
|
||||||
const account = this.loadAccount();
|
const account = this.loadAccount();
|
||||||
if (!account) throw new ServiceUnavailableException('Google Wallet n’est pas encore configuré');
|
if (!account) throw new ServiceUnavailableException('Google Wallet n’est pas encore configuré');
|
||||||
const design = card.store.cardDesign;
|
if (!card.store.cardDesign) throw new ServiceUnavailableException('Carte non conçue');
|
||||||
if (!design) throw new ServiceUnavailableException('Carte non conçue');
|
|
||||||
|
|
||||||
const publicUrl: string = this.config.get('publicUrl')!;
|
const publicUrl: string = this.config.get('publicUrl')!;
|
||||||
const webUrl: string = this.config.get('webUrl')!;
|
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 key = await importPKCS8(account.private_key, 'RS256');
|
||||||
const jwt = await new SignJWT({
|
const jwt = await new SignJWT({
|
||||||
origins: [publicUrl, webUrl],
|
origins: [publicUrl, webUrl],
|
||||||
typ: 'savetowallet',
|
typ: 'savetowallet',
|
||||||
payload: { loyaltyClasses: [loyaltyClass], loyaltyObjects: [loyaltyObject] },
|
payload: { loyaltyClasses: [this.buildClass(card.store)], loyaltyObjects: [this.buildObject(card)] },
|
||||||
})
|
})
|
||||||
.setProtectedHeader({ alg: 'RS256', typ: 'JWT' })
|
.setProtectedHeader({ alg: 'RS256', typ: 'JWT' })
|
||||||
.setIssuer(account.client_email)
|
.setIssuer(account.client_email)
|
||||||
|
|
@ -94,6 +57,108 @@ export class GoogleWalletService {
|
||||||
return `https://pay.google.com/gp/v/save/${jwt}`;
|
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<string> {
|
||||||
|
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 {
|
private loadAccount(): ServiceAccount | null {
|
||||||
if (this.account !== undefined) return this.account;
|
if (this.account !== undefined) return this.account;
|
||||||
const file: string = this.config.get('google.serviceAccountFile')!;
|
const file: string = this.config.get('google.serviceAccountFile')!;
|
||||||
|
|
|
||||||
15
backend/src/wallet/wallet.module.ts
Normal file
15
backend/src/wallet/wallet.module.ts
Normal file
|
|
@ -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 {}
|
||||||
Loading…
Reference in a new issue