MonEspacePro/backend/src/wallet/google-wallet.service.ts
Tony AVERTY eec67bbf86 Inscription client et cartes Apple / Google Wallet
- Page d'inscription /c/<slug> aux couleurs du magasin (prénom, e-mail,
  consentement RGPD), carte déjà existante avec renvoi du lien, programme
  indisponible, page confidentialité
- Page de la carte /carte/<serial> avec lien secret, suppression RGPD
- Génération .pkpass (passkit-generator) et lien Google Wallet (JWT)
- E-mail de confirmation (SMTP, ou logs en développement)
- Affichette A5/A6 imprimable avec le QR d'inscription
- Activation du magasin conditionnée au logo

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 12:40:50 +02:00

101 lines
3.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { Injectable, Logger, ServiceUnavailableException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { readFileSync } from 'fs';
import { importPKCS8, SignJWT } from 'jose';
import { CardWithContext, rewardsText, unitLabel } from './wallet.types';
type ServiceAccount = { client_email: string; private_key: string };
/**
* 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).
*/
@Injectable()
export class GoogleWalletService {
private readonly logger = new Logger(GoogleWalletService.name);
private account: ServiceAccount | null | undefined;
constructor(private config: ConfigService) {}
get enabled() {
return this.loadAccount() !== null;
}
classId(storeId: string) {
return `${this.config.get('google.issuerId')}.store_${storeId}`;
}
objectId(serial: string) {
return `${this.config.get('google.issuerId')}.card_${serial}`;
}
async saveUrl(card: CardWithContext): Promise<string> {
const account = this.loadAccount();
if (!account) throw new ServiceUnavailableException('Google Wallet n’est pas encore configuré');
const design = card.store.cardDesign;
if (!design?.logoPath) throw new ServiceUnavailableException('Logo du magasin manquant');
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 } },
});
const loyaltyClass = {
id: this.classId(card.storeId),
issuerName: card.store.name,
programName: design.programName,
programLogo: image(design.logoPath, `Logo ${card.store.name}`),
...(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: [{ id: 'rewards', header: 'Récompenses', body: rewardsText(card) }],
linksModuleData: {
uris: [{ id: 'manage', uri: `${publicUrl}/carte/${card.serial}?k=${card.accessKey}`, description: 'Ma carte' }],
},
};
const key = await importPKCS8(account.private_key, 'RS256');
const jwt = await new SignJWT({
origins: [publicUrl],
typ: 'savetowallet',
payload: { loyaltyClasses: [loyaltyClass], loyaltyObjects: [loyaltyObject] },
})
.setProtectedHeader({ alg: 'RS256', typ: 'JWT' })
.setIssuer(account.client_email)
.setAudience('google')
.setIssuedAt()
.sign(key);
return `https://pay.google.com/gp/v/save/${jwt}`;
}
private loadAccount(): ServiceAccount | null {
if (this.account !== undefined) return this.account;
const file: string = this.config.get('google.serviceAccountFile')!;
if (!file || !this.config.get('google.issuerId')) {
this.account = null;
return null;
}
try {
this.account = JSON.parse(readFileSync(file, 'utf8')) as ServiceAccount;
} catch (e) {
this.logger.error(`Clé Google Wallet illisible : ${(e as Error).message}`);
this.account = null;
}
return this.account;
}
}