import { Injectable, Logger, ServiceUnavailableException } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { readFileSync } from 'fs'; 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. * - 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) {} 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é'); 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 key = await importPKCS8(account.private_key, 'RS256'); const jwt = await new SignJWT({ origins: [publicUrl, webUrl], typ: 'savetowallet', payload: { loyaltyClasses: [this.buildClass(card.store)], loyaltyObjects: [this.buildObject(card)] }, }) .setProtectedHeader({ alg: 'RS256', typ: 'JWT' }) .setIssuer(account.client_email) .setAudience('google') .setIssuedAt() .sign(key); 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); } /** * Message de campagne sur toutes les cartes Google du magasin, avec notification. * Google limite les notifications à 3 par carte et par 24 h : nos campagnes sont limitées à 1 par jour. */ async addClassMessage(storeId: string, campaignId: string, header: string, body: string) { if (!this.enabled) return; await this.call('POST', `/loyaltyClass/${encodeURIComponent(this.classId(storeId))}/addMessage`, { message: { id: `campaign_${campaignId}`, header, body, messageType: 'TEXT_AND_NOTIFY' }, }); } /** Message avec notification sur la carte d'un seul client (relance). */ async addObjectMessage(serial: string, messageId: string, header: string, body: string) { if (!this.enabled) return; await this.call('POST', `/loyaltyObject/${encodeURIComponent(this.objectId(serial))}/addMessage`, { message: { id: messageId, header, body, messageType: 'TEXT_AND_NOTIFY' }, }); } 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')!; 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; } }