1- import crypto from 'crypto' ;
2-
31const API_BASE_URL = 'https://checkout.postfinance.ch/api' ;
42
53interface ApiConfig {
@@ -22,7 +20,7 @@ export class PostFinanceApiClient {
2220 this . config = config ;
2321 }
2422
25- private generateMacHeaders ( method : string , path : string ) : MacHeaders {
23+ private async generateMacHeaders ( method : string , path : string ) : Promise < MacHeaders > {
2624 const version = '1' ;
2725 const timestamp = Math . floor ( Date . now ( ) / 1000 ) . toString ( ) ;
2826 const userId = this . config . userId . toString ( ) ;
@@ -32,10 +30,17 @@ export class PostFinanceApiClient {
3230
3331 const dataToSign = [ version , userId , timestamp , method , resourcePath ] . join ( '|' ) ;
3432
35- const macValue = crypto
36- . createHmac ( 'sha512' , Buffer . from ( this . config . apiSecret , 'base64' ) )
37- . update ( dataToSign , 'utf8' )
38- . digest ( 'base64' ) ;
33+ // Use Web Crypto API instead of crypto.createHmac
34+ const secretBytes = Uint8Array . from ( atob ( this . config . apiSecret ) , ( c ) => c . charCodeAt ( 0 ) ) ;
35+ const key = await crypto . subtle . importKey (
36+ 'raw' ,
37+ secretBytes ,
38+ { name : 'HMAC' , hash : 'SHA-512' } ,
39+ false ,
40+ [ 'sign' ] ,
41+ ) ;
42+ const signature = await crypto . subtle . sign ( 'HMAC' , key , new TextEncoder ( ) . encode ( dataToSign ) ) ;
43+ const macValue = btoa ( String . fromCharCode ( ...new Uint8Array ( signature ) ) ) ;
3944
4045 return {
4146 'x-mac-version' : version ,
@@ -50,7 +55,7 @@ export class PostFinanceApiClient {
5055 const urlObj = new URL ( url ) ;
5156 // Include both pathname and search (query parameters) for MAC signature
5257 const pathWithQuery = urlObj . pathname + urlObj . search ;
53- const macHeaders = this . generateMacHeaders ( method , pathWithQuery ) ;
58+ const macHeaders = await this . generateMacHeaders ( method , pathWithQuery ) ;
5459
5560 const headers : Record < string , string > = {
5661 ...macHeaders ,
0 commit comments