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 { 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; } }