javascriptnode.jspayment-gatewaycybersource

Cybersource refund getting Not Authorized /401


I am integrating CyberSource payment gateway using JavaScript. The payment part is working and going through, However I am stuck at refunds. Always getting not authorized error. The API keys are correct. I have checked multiple times.

Note: I am using CyberSource's Secure Acceptance Hosted Checkout for Payment and for Refund, REST API endpoint, Location - Middle East Region.

From successful Payment Response I have saved the following transaction reference to my DB to initiate a refund - auth_trans_ref_no & auth_reconciliation_reference_number. In the below given code I am using auth_trans_ref_no. Tried both though

This is how I process a refund Request

after Extracting Booking details from DB under ticket

const refundEndpoint = `https://api.cybersource.com/pts/v2/payments/${ticket.cybersourceConfirmationId}/refunds`;

const refundPayload = {
  clientReferenceInformation: {
    code: ticket.transactionId,
  },
  orderInformation: {
    amountDetails: {
      totalAmount: Number(refundAmount).toFixed(2),
      currency: "QAR",
    },
  },
};

const payloadString = JSON.stringify(refundPayload);

const digest =
  "SHA-256=" +
  crypto
    .createHash("sha256")
    .update(payloadString)
    .digest("base64");

const vCDate = new Date().toUTCString();

const host = "api.cybersource.com";
const requestTarget = `post /pts/v2/payments/${ticket.cybersourceConfirmationId}/refunds`;

const vCMerchantId = process.env.CYBERSOURCE_MERCHANT_ID;
const keyId = process.env.CYBERSOURCE_SHARED_API_KEY_ID;
const secretKey = process.env.CYBERSOURCE_SHARED_API_SECRET;

const signingString =
  `host: ${host}\n` +
  `date: ${vCDate}\n` +
  `(request-target): ${requestTarget}\n` +
  `digest: ${digest}\n` +
  `v-c-merchant-id: ${vCMerchantId}`;

const computedSignature = crypto
  .createHmac("sha256", secretKey)
  .update(signingString)
  .digest("base64");

const signatureHeader = `keyid="${keyId}", algorithm="HmacSHA256", headers="host date (request-target) digest v-c-merchant-id", signature="${computedSignature}"`;

const headers = {
  host,
  signature: signatureHeader,
  digest,
  "v-c-merchant-id": vCMerchantId,
  date: vCDate,
  "Content-Type": "application/json",
};

try {
  const response = await axios.post(refundEndpoint, refundPayload, { headers });
    //If true
  } else {
    //If False
} catch (error) {
  //If Error
}

This is the Link to CyberSource Docs

Processor - Asia/Middle East and Africa Gateway API- Rest API

I have tried multiple formats to solve this.

Complete Response I am getting as requested in comments

AxiosError: Request failed with status code 401
    at settle (/home/ubuntu/code/dohabus_backend/node_modules/axios/dist/node/axios.cjs:2031:12)
    at IncomingMessage.handleStreamEnd (/home/ubuntu/code/dohabus_backend/node_modules/axios/dist/node/axios.cjs:3148:11)
    at IncomingMessage.emit (node:events:529:35)
    at endReadableNT (node:internal/streams/readable:1400:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
    at Axios.request (/home/ubuntu/code/dohabus_backend/node_modules/axios/dist/node/axios.cjs:4258:41)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async /home/ubuntu/code/dohabus_backend/src/controllers/refundController.js:211:24 {
  code: 'ERR_BAD_REQUEST',
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    adapter: [ 'xhr', 'http', 'fetch' ],
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    env: { FormData: [Function [FormData]], Blob: [class Blob] },
    validateStatus: [Function: validateStatus],
    headers: Object [AxiosHeaders] {
      Accept: 'application/json, text/plain, */*',
      'Content-Type': 'application/json',
      host: 'api.cybersource.com',
      signature: 'keyid="********-****-****-****-************", algorithm="HmacSHA256", headers="host date (request-target) digest v-c-merchant-id", signature="z5jyXi7mp3RJyZ0j74tFZuSsJWrShjeq0EK31/aZRCg="',
      digest: 'SHA-256=kp6YNoxNHKMW1Tzh73pqezAZ70v+QvTolYs5cNj5tGY=',
      'v-c-merchant-id': '*******',
      date: 'Mon, 24 Mar 2025 11:34:28 GMT',
      'User-Agent': 'axios/1.8.3',
      'Content-Length': '158',
      'Accept-Encoding': 'gzip, compress, deflate, br'
    },
    method: 'post',
    url: 'https://api.cybersource.com/pts/v2/payments/7419781136366848104258/refunds',
    data: '{"clientReferenceInformation":{"code":"5e8798a4-cd10-49d8-815e-369792c96515"},"orderInformation":{"amountDetails":{"totalAmount":"1300.00","currency":"QAR"}}}',
    allowAbsoluteUrls: true
  },
  request: <ref *1> ClientRequest {
    _events: [Object: null prototype] {
      abort: [Function (anonymous)],
      aborted: [Function (anonymous)],
      connect: [Function (anonymous)],
      error: [Function (anonymous)],
      socket: [Function (anonymous)],
      timeout: [Function (anonymous)],
      finish: [Function: requestOnFinish]
    },
    _eventsCount: 7,
    _maxListeners: undefined,
    outputData: [],
    outputSize: 0,
    writable: true,
    destroyed: false,
    _last: true,
    chunkedEncoding: false,
    shouldKeepAlive: false,
    maxRequestsOnConnectionReached: false,
    _defaultKeepAlive: true,
    useChunkedEncodingByDefault: true,
    sendDate: false,
    _removedConnection: false,
    _removedContLen: false,
    _removedTE: false,
    strictContentLength: false,
    _contentLength: '158',
    _hasBody: true,
    _trailer: '',
    finished: true,
    _headerSent: true,
    _closed: false,
    socket: TLSSocket {
      _tlsOptions: [Object],
      _secureEstablished: true,
      _securePending: false,
      _newSessionPending: false,
      _controlReleased: true,
      secureConnecting: false,
      _SNICallback: null,
      servername: 'api.cybersource.com',
      alpnProtocol: false,
      authorized: true,
      authorizationError: null,
      encrypted: true,
      _events: [Object: null prototype],
      _eventsCount: 10,
      connecting: false,
      _hadError: false,
      _parent: null,
      _host: 'api.cybersource.com',
      _closeAfterHandlingError: false,
      _readableState: [ReadableState],
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: false,
      _sockname: null,
      _pendingData: null,
      _pendingEncoding: '',
      server: undefined,
      _server: null,
      ssl: [TLSWrap],
      _requestCert: true,
      _rejectUnauthorized: true,
      parser: null,
      _httpMessage: [Circular *1],
      [Symbol(alpncallback)]: null,
      [Symbol(res)]: [TLSWrap],
      [Symbol(verified)]: true,
      [Symbol(pendingSession)]: null,
      [Symbol(async_id_symbol)]: 881,
      [Symbol(kHandle)]: [TLSWrap],
      [Symbol(lastWriteQueueSize)]: 0,
      [Symbol(timeout)]: null,
      [Symbol(kBuffer)]: null,
      [Symbol(kBufferCb)]: null,
      [Symbol(kBufferGen)]: null,
      [Symbol(kCapture)]: false,
      [Symbol(kSetNoDelay)]: false,
      [Symbol(kSetKeepAlive)]: true,
      [Symbol(kSetKeepAliveInitialDelay)]: 60,
      [Symbol(kBytesRead)]: 0,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(connect-options)]: [Object]
    },
    _header: 'POST /pts/v2/payments/7419781136366848104258/refunds HTTP/1.1\r\n' +
      'Accept: application/json, text/plain, */*\r\n' +
      'Content-Type: application/json\r\n' +
      'host: api.cybersource.com\r\n' +
      'signature: keyid="********-****-****-****-************", algorithm="HmacSHA256", headers="host date (request-target) digest v-c-merchant-id", signature="z5jyXi7mp3RJyZ0j74tFZuSsJWrShjeq0EK31/aZRCg="\r\n' +
      'digest: SHA-256=kp6YNoxNHKMW1Tzh73pqezAZ70v+QvTolYs5cNj5tGY=\r\n' +
      'v-c-merchant-id: *******\r\n' +
      'date: Mon, 24 Mar 2025 11:34:28 GMT\r\n' +
      'User-Agent: axios/1.8.3\r\n' +
      'Content-Length: 158\r\n' +
      'Accept-Encoding: gzip, compress, deflate, br\r\n' +
      'Connection: close\r\n' +
      '\r\n',
    _keepAliveTimeout: 0,
    _onPendingData: [Function: nop],
    agent: Agent {
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      defaultPort: 443,
      protocol: 'https:',
      options: [Object: null prototype],
      requests: [Object: null prototype] {},
      sockets: [Object: null prototype],
      freeSockets: [Object: null prototype] {},
      keepAliveMsecs: 1000,
      keepAlive: false,
      maxSockets: Infinity,
      maxFreeSockets: 256,
      scheduling: 'lifo',
      maxTotalSockets: Infinity,
      totalSocketCount: 1,
      maxCachedSessions: 100,
      _sessionCache: [Object],
      [Symbol(kCapture)]: false
    },
    socketPath: undefined,
    method: 'POST',
    maxHeaderSize: undefined,
    insecureHTTPParser: undefined,
    joinDuplicateHeaders: undefined,
    path: '/pts/v2/payments/7419781136366848104258/refunds',
    _ended: true,
    res: IncomingMessage {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 4,
      _maxListeners: undefined,
      socket: [TLSSocket],
      httpVersionMajor: 1,
      httpVersionMinor: 1,
      httpVersion: '1.1',
      complete: true,
      rawHeaders: [Array],
      rawTrailers: [],
      joinDuplicateHeaders: undefined,
      aborted: false,
      upgrade: false,
      url: '',
      method: null,
      statusCode: 401,
      statusMessage: 'Unauthorized',
      client: [TLSSocket],
      _consuming: false,
      _dumped: false,
      req: [Circular *1],
      responseUrl: 'https://api.cybersource.com/pts/v2/payments/7419781136366848104258/refunds',
      redirects: [],
      [Symbol(kCapture)]: false,
      [Symbol(kHeaders)]: [Object],
      [Symbol(kHeadersCount)]: 16,
      [Symbol(kTrailers)]: null,
      [Symbol(kTrailersCount)]: 0
    },
    aborted: false,
    timeoutCb: null,
    upgradeOrConnect: false,
    parser: null,
    maxHeadersCount: null,
    reusedSocket: false,
    host: 'api.cybersource.com',
    protocol: 'https:',
    _redirectable: Writable {
      _writableState: [WritableState],
      _events: [Object: null prototype],
      _eventsCount: 3,
      _maxListeners: undefined,
      _options: [Object],
      _ended: true,
      _ending: true,
      _redirectCount: 0,
      _redirects: [],
      _requestBodyLength: 158,
      _requestBodyBuffers: [],
      _onNativeResponse: [Function (anonymous)],
      _currentRequest: [Circular *1],
      _currentUrl: 'https://api.cybersource.com/pts/v2/payments/7419781136366848104258/refunds',
      [Symbol(kCapture)]: false
    },
    [Symbol(kCapture)]: false,
    [Symbol(kBytesWritten)]: 0,
    [Symbol(kNeedDrain)]: false,
    [Symbol(corked)]: 0,
    [Symbol(kOutHeaders)]: [Object: null prototype] {
      accept: [Array],
      'content-type': [Array],
      host: [Array],
      signature: [Array],
      digest: [Array],
      'v-c-merchant-id': [Array],
      date: [Array],
      'user-agent': [Array],
      'content-length': [Array],
      'accept-encoding': [Array]
    },
    [Symbol(errored)]: null,
    [Symbol(kHighWaterMark)]: 16384,
    [Symbol(kRejectNonStandardBodyWrites)]: false,
    [Symbol(kUniqueHeaders)]: null
  },
  response: {
    status: 401,
    statusText: 'Unauthorized',
    headers: Object [AxiosHeaders] {
      'strict-transport-security': 'max-age=31536000',
      'v-c-correlation-id': 'c3af5537-1a92-4d3b-b93e-94a85a887aad',
      'x-requestid': '7428160693236073104986',
      'content-type': 'application/json',
      'v-c-response-time': '1742816069',
      'content-length': '45',
      'x-opnet-transaction-trace': 'e199f8aa-0841-43d6-a231-3bba5ad438a6',
      connection: 'close'
    },
    config: {
      transitional: [Object],
      adapter: [Array],
      transformRequest: [Array],
      transformResponse: [Array],
      timeout: 0,
      xsrfCookieName: 'XSRF-TOKEN',
      xsrfHeaderName: 'X-XSRF-TOKEN',
      maxContentLength: -1,
      maxBodyLength: -1,
      env: [Object],
      validateStatus: [Function: validateStatus],
      headers: [Object [AxiosHeaders]],
      method: 'post',
      url: 'https://api.cybersource.com/pts/v2/payments/7419781136366848104258/refunds',
      data: '{"clientReferenceInformation":{"code":"5e8798a4-cd10-49d8-815e-369792c96515"},"orderInformation":{"amountDetails":{"totalAmount":"1300.00","currency":"QAR"}}}',
      allowAbsoluteUrls: true
    },
    request: <ref *1> ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      maxRequestsOnConnectionReached: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: true,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      strictContentLength: false,
      _contentLength: '158',
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      _closed: false,
      socket: [TLSSocket],
      _header: 'POST /pts/v2/payments/7419781136366848104258/refunds HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'Content-Type: application/json\r\n' +
        'host: api.cybersource.com\r\n' +
        'signature: keyid="********-****-****-****-************", algorithm="HmacSHA256", headers="host date (request-target) digest v-c-merchant-id", signature="z5jyXi7mp3RJyZ0j74tFZuSsJWrShjeq0EK31/aZRCg="\r\n' +
        'digest: SHA-256=kp6YNoxNHKMW1Tzh73pqezAZ70v+QvTolYs5cNj5tGY=\r\n' +
        'v-c-merchant-id: *******\r\n' +
        'date: Mon, 24 Mar 2025 11:34:28 GMT\r\n' +
        'User-Agent: axios/1.8.3\r\n' +
        'Content-Length: 158\r\n' +
        'Accept-Encoding: gzip, compress, deflate, br\r\n' +
        'Connection: close\r\n' +
        '\r\n',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: nop],
      agent: [Agent],
      socketPath: undefined,
      method: 'POST',
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      joinDuplicateHeaders: undefined,
      path: '/pts/v2/payments/7419781136366848104258/refunds',
      _ended: true,
      res: [IncomingMessage],
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: 'api.cybersource.com',
      protocol: 'https:',
      _redirectable: [Writable],
      [Symbol(kCapture)]: false,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype],
      [Symbol(errored)]: null,
      [Symbol(kHighWaterMark)]: 16384,
      [Symbol(kRejectNonStandardBodyWrites)]: false,
      [Symbol(kUniqueHeaders)]: null
    },
    data: { response: [Object] }
  },
  status: 401
}

Solution

  • It was an issue with how I was signing the request header.

    Finally I used the SDK provided by CyberSource.

    I got the link from their GitHub page - https://github.com/CyberSource

    I used the Node.JS one and followed their instructions exactly to construct and make the request for refund. It went through.