Invoice(opts, invoice)

A Cash Payment Server Invoice

Invoices can be created client-side or server-side. However, for security reasons, it is recommended that invoices are created server-side and passed back to the client-side.

Note: Any field that is prefixed with an underscore is private and should never be accessed directly.

Note: Any field that is not prefixed by an underscore is considered public and stable (hence there are no "getter" functions in this class). Only use setters to modify the parameters of an invoice - do not set values directly.

new Invoice(opts, invoice)

Parameters:
Name Type Description
opts object Options for invoice instance (use setters instead)
invoice object Invoice properties (use setters instead)
Properties:
Name Type Description
id String ID of the invoice
Example
//
// Server-side
//
let invoice = new CashPay.Invoice()
  .setAPIKey('your.site|SECURE_KEY_123')
  .addAddress('bitcoincash:qpfsrgdeq49fsjrg5qk4xqhswjl7g248950nzsrwvn', '1USD')
  .setWebhook('https://webhook.site/1aa1cc3b-8ee8-4f70-a4cd-abc0c9b8d1f2'. ['confirmed'])
await invoice.create()

// Send Payload JSON to browser
return invoice.payload()

//
// Client-side
//
let invoice = new CashPay.Invoice()
  .intoContainer(document.getElementById('invoice-container'))
  .on(['broadcasting', 'broadcasted'], (event) {
    console.log(event)
  })
await invoice.createFrom('https://your-endpoint-above', {
  items: ['ITEM-001', 'ITEM_002']
})

Methods

addAddress(address, amount)

Add an address output to Invoice.
Parameters:
Name Type Description
address String Bitcoin Cash address
amount String | Number Amount in satoshis or string with currency code suffix
Example
let invoice = new Invoice();
invoice.addAddress("bitcoincash:qzeup9lysjazfvqnv07ns9c846aaul7dtuqqncf6jg", 100000);

// Or specify a currency code for on-the-fly conversion
invoice.addAddress("bitcoincash:qzeup9lysjazfvqnv07ns9c846aaul7dtuqqncf6jg", "2.50USD");

addOutput(script, amountopt)

Add a script output to the Invoice.

Note that this is not supported by JSONPaymentProtocol.

Parameters:
Name Type Attributes Default Description
script string Raw output script (in ASM)
amount number <optional>
0 Amount in satoshis
Example
// Set OP_RETURN data to "TEST_OP_RETURN"
invoice.addOutput('OP_RETURN 544553545f4f505f52455455524e')
invoice.addOutput(`OP_RETURN ${Buffer.from('TEST_OP_RETURN').toString('hex')}`)

async create()

Create the invoice.

Browser Environment: Websocket and Expiry timers WILL be instantiated.

NodeJS Enviroment: Websocket and Expiry timers WILL NOT be instantiated.

Example
let invoice = new CashPay.Invoice()
  .intoContainer(document.getElementById('invoice-container'))
  .addAddress('bitcoincash:qpfsrgdeq49fsjrg5qk4xqhswjl7g248950nzsrwvn', '1USD')
  .on('broadcasted', e => {
    console.log(e)
  })
await invoice.create()

async createFrom(endpoint, paramsopt, optionopt)

Load a created invoice from a server-side endpoint.

Parameters:
Name Type Attributes Description
endpoint String The endpoint to use
params Object <optional>
POST parameters to send to endpoint
option Object <optional>
Options to pass to axios.post
Example
// Using default container
const invoice = new CashPay.Invoice()
  .intoContainer(document.getElementById('invoice-container'))
  .on('broadcasted', e => {
    console.log(e)
  })
await invoice.createFrom('https://api.your-site.com/request-invoice', {
  items: ['ITEM_001', 'ITEM_002']
})

async createFromExisting(paramsopt)

Instantiate the invoice from an existing invoice.

Similar to createFrom, but where you handle the AJAX request.

Parameters:
Name Type Attributes Description
params Object <optional>
POST parameters to send to endpoint
Example
const res = axios.post('https://api.your-site.com/request-invoice', {
  items: ['ITEM_001', 'ITEM_002']
})

let invoice = new CashPay.Invoice()
  .intoContainer(document.getElementById('invoice-container'))
  .on('broadcasted', e => {
    console.log(e)
  })
await invoice.createFromExisting(res.data.invoice)

async destroy()

Destroy the invoice instance.

This function should be used to clear all listeners from the invoice.

You will need to call this manually if you are not using the OOTB intoContainer function.

Note this does not destroy the container itself, but the timers/websocket listener.

Example
// Destroy the invoice to prevent memory-leaks/dangling references
invoice.destroy()

intoContainer(container)

Load the invoice into a DOM container.

If the DOM element is empty, default template will be used.

Note: If container is removed from DOM, invoice listeners will be destroyed by default. See destroyOnRemoved param in options.

Parameters:
Name Type Attributes Default Description
container DOMElement Container to load into
options.lang.expiresIn String Text to use for Expires In
options.lang.invoiceHasExpired String Text to use when Invoice has expired
options.destroyOnRemoved Boolean <optional>
true Destroy invoice listeners when DOM element removed
Example
// No options
const invoice = new CashPay.Invoice()
  .intoContainer(document.getElementById('invoice-container')

// Change Invoice Expired Text for Captcha
const invoice = new CashPay.Invoice()
  .intoContainer(document.getElementById('invoice-container', {
    lang: {
      invoiceHasExpired: 'Captcha has expired'
    }
  })

on(events, callback)

Add an event handler.

Most of these events will be sent by the WebSocket connection.

Supported events are:

  • created
  • broadcasting
  • broadcasted
  • expired
  • failed
Parameters:
Name Type Description
events string | array Event to handle (or array of events)
callback Callback function
Example
// Add listener for failed event
let invoice = new CashPay.Invoice()
  .addAddress('bitcoincash:qpfsrgdeq49fsjrg5qk4xqhswjl7g248950nzsrwvn', '1AAAA')
  .on('failed', err => {
    alert(err.message)
  }

// Add event listener for broadcasting and broadcasted event
let invoice = new CashPay.Invoice()
  .addAddress('bitcoincash:qpfsrgdeq49fsjrg5qk4xqhswjl7g248950nzsrwvn', '1AAAA')
  .on(['broadcasting', 'broadcasted'], e => {
    console.log(e)
  }

payload()

Get the payload of the invoice.

This function can be used to pass the invoice back to the browser from the server-side.

The fields [apiKey, privateData, webhook, events] will be omitted from the payload

Example
// Get JSON payload
let payload = invoice.payload()

setAPIKey()

Sets the API Key

An arbitrary API Key that can be used to later retrieve invoice information.

This field will not be included in WebSocket events and omitted in the payload() function.

This should never be used if the invoice is created client-side (in the browser).

Example
invoice.setAPIKey('https://t.me/yourname|SECURE_STRING')

setData(data)

Sets (Public) Data against the invoice.

Parameters:
Name Type Description
data string | object If an object is passed, this will be converted to a string.
Example
// Using a string
invoice.setData("https://your-site.com/some-url-to-redirect-to");

// Using an object
invoice.setData({
 redirectURL: 'https://your-site.com/some-url-to-redirect-to'
})

setExpires(seconds)

Set expiration time
Parameters:
Name Type Description
seconds number Seconds from time of creation that Payment Request expires
Example
// 15 minutes
invoice.setExpires(15 * 60)

setMemo(memo)

Sets a BIP70/JPP memo
Parameters:
Name Type Description
memo string Memo text
Example
// Memos are not supported by all wallets
invoice.setMemo("Payment to YOUR_SERVICE_NAME")

setMemoPaid(memoPaid)

Sets a BIP70/JPP memo to show AFTER payment
Parameters:
Name Type Description
memoPaid string Memo text
Example
// Memos are not supported by all wallets
invoice.setMemoPaid('Thank you for your payment')

setMerchantData(data)

Sets Merchant Data associated with invoice

This must be Base64 encoded

Parameters:
Name Type Description
data string Base64 encoded string
Example
// Node
invoice.setMerchantData(Buffer.from('INVOICE_001', 'base64'))

// Browser
invoice.setMerchantData(btoa('INVOICE_001'))

setNetwork(network)

Set network
Parameters:
Name Type Description
network string Network to use
Example
// Use testnet
invoice.setNetwork('test')

setPrivateData(data)

Sets Private Data against the invoice.

This field will not be included in WebSocket events and omitted in the payload() function.

Parameters:
Name Type Description
data string | object If an object is passed, this will be converted to a string.
Example
// Using a string
invoice.setPrivateData("ORDERID: 12345");

// Using an object
invoice.setPrivateData({
 orderId: '12345'
})

setUserCurrency(currency)

The unit of fiat (e.g. USD) that will be displayed to the user
Parameters:
Name Type Description
currency string The currency code
Example
// Show invoice total in Australian Dollars
invoice.setUserCurrency('AUD')

setWebhook(endpoint, events)

Set Webhook

Used to notify server endpoint of transaction event.

Note that a JSON response can be returned by the server to modify the fields: "data" and "privateData".

Parameters:
Name Type Description
endpoint String The endpoint that should be hit
events Array | String The type of Webhook (broadcasting, broadcasted, confirmed)
Example
// Set Webhook (defaults to broadcasting, broadcasted and confirmed)
let invoice = new CashPay.Invoice();
  .setWebhook('https://webhook.site/1aa1cc3b-8ee8-4f70-a4cd-abc0c9b8d1f2');

// Only trigger on "broadcasting" and "broadcasted"
let invoice = new CashPay.Invoice();
  .setWebhook('https://webhook.site/1aa1cc3b-8ee8-4f70-a4cd-abc0c9b8d1f2', ['broadcasting', 'broadcasted'])