Initializing client

The easiest way to initialize an instance of AgentCash.SDK.PgClient is to call the Initialize method and provide your API key:

Task<string> Initialize(string apiKey);

apiKey is your API key for AgentCASH service, assigned to you by AgentCASH. You can find it at AgentCASH portal.

This will initialize PgClient with default settings. If you want to customize the behavior further, use Initialize overload which takes a Configuration object

Task<string> Initialize(Configuration config);

If the initialization fails, the method will throw an InitializationException so your code should look like this:

try
{
    var device = await pgClient.Initialize(API_KEY);
    Log("Connected to {0}", device);
}
catch (InitializationException e)
{
    Log("Initialization failed: {0}", e.Message);
}

Configuration object provides following properties, which control how the transactions are executed:

  • ApiKey: this is the same API key as explained before
  • Username: username or email used to log into AgentCASH server. This is only required if you need to search the transactions with FindTransactions()
  • Password: password used to log into AgentCASH server. This is only required if you need to search the transactions with FindTransactions()
  • AccessToken: If the user was already logged on in some other way, instead of specifying Username and Password properties client application can specify AccessToken which will be used to authenticate requests to AC server
  • UseProductionEnvironment: Specifies whether the SDK will target production or development environment. This property is by default set to false, i.e. the development environment is targeted.
  • Device: specifies which reader will be used. By default, it is set to Devices.LastUsed. Possible settings are:
    • Devices.LastUsed - will use the same reader as in last session. If it can’t find info for last session, it will try to find the default Bluetooth reader (see next item). If it can’t find it, initialization will fail.
    • Devices.DefaultBluetoothReader - will use the default BT reader, which is the one containing AgentCASH in its name.
    • If you want to use a custom BT device you can enumerate them with var devices = await Devices.FindBluetoothDevicesAsync(); and select the one you need with config.Device = devices.First(d => d.Name == "mydevice");
    • WiFi readers (actually, any IP based devices) can be specified by creating an instance of ReaderDevice like this: config.Device = Devices.NetworkedDevice("192.168.1.27", 7232);
  • TransactionTimeoutMs: Specifies timeout for communications between reader and gateway. If during the transaction processing, there is no traffic between reader and gateway for longer than specified, the transaction will be aborted. This value is specified in milliseconds. The default is 120000 (2 minutes).
  • Logger: an ILog instance being used to log low-level information. By default, an internal implementation is used which writes to system’s debug output. As ILog is very simple interface, you can provide your own implementation using e.g. log4net, NLog, serilog or any other logging library.
  • SerializeEvents: controls whether the events raised by PgClient are marshalled to main GUI thread. Default value is true.
  • ImportCertificate: specifies whether the payment gateway server certificate will be automatically loaded into certificate store during initialization. Default is true. If set to false, user should add the certificate to application assets and add it to the application manifest (Package.appxmanifest) `Declarations > Certificates section)

SerializeEvents is important if you are writing a GUI application.

PgClient events are internally fired from different threads. This can create problems for GUI applications which expect that GUI components are handled on main GUI thread. Thus, this property allows you to marshall events automatically to GUI thread, so you can safely manipulate GUI components.

As you will typically create a PgClient instance as a member of some GUI form or object owned directly or indirectly by the form, we suggest that you call the Initialize method when the form is already created.

This will enable the PgClient object to raise events on main GUI thread. This simplifies your code as most GUI controls don’t allow changing their state from background threads. As events are marshalled to the main GUI thread it is safe to call all methods on your GUI controls.

This marshalling can be disabled by setting the SerializeEvents property to false

Retrieving current user info

Once when the initialization is succesfully performed, current user info can be retrieved, if required:

var user = await client.GetUserAsync();
Log("Logged in as {0} ({1}) - role: {2}", user.Name, user.Email, user.Roles[0]);

This will output something like:

Logged in as John Doe (john.doe@test.com) - role: cashier

User object provides following properties:

  • Id: User’s unique ID
  • Name: User name, as defined during user creation
  • Email: User email
  • MerchantId: Merchant’s ID
  • CurrencyCode: Merchant’s default currency code
  • RegisterId: default register Id used to initiate transactions
  • Locale: User’s locale
  • Roles: Collection of roles assigned to the user (e.g. ‘cashier’, ‘admin’...)

Switching readers after initialization

Typically, the reader is specified in Configuration and selected during initialization (Initialize) method. Initialization also sets up connection to server and internal data required to execute payments.

In environments with multiple readers, it can be undesirable to perform full initialization in order to only switch to another reader. In this case, you can use SelectReader method of PgClient, which will select specified reader as active reader for subsequent transactions.

// initialization at startup

var cfg = new Configuration {
   ...
   Device = Devices.DefaultBluetoothReader
}
await pgClient.Initialize(cfg);   // initialize client with default BT reader

...

// later on we want to switch to another reader named 'AgentCASH 1234',
// without fully reinitializing the client:

var all_bt_devices = await Devices.FindBluetoothDevicesAsync();
var device = all_bt_devices.First(dev => dev.Name.Contains("1234"));
await pgClient.SelectReader(device);

// example of switching to from default BT reader to default serial reader which
// can actually be the same reader device but using different connection type.
// NOTE: serial connections are only supported on full .NET framework, and not
// on UWA/UWP:

await pgClient.SelectReader(Devices.DefaultSerialReader);

PgClient.SelectReader will throw InitializationException if it can’t connect to specified reader.

Error handling

As shown in the example above, if initialization fails, InitializationException will be thrown. The Message property of the exception carries the info about the reason why initialization failed.

A PgClient instance which failed initialization can not be used to execute transactions and needs to be initialized correctly.