Tutorial

In this section, we will walk you through the most frequent MARTA applications step by step. Each use case is introduced descriptively and then detailed with technical specifications.

This documentation section is continuously updated and enriched, reflecting the wide range of possibilities and flexibility that MARTA can offer.

Approfondisci:

Tutorial Authentication

Examples of authenticating using the POST /auth endpoint to obtain a valid session token

To obtain a valid session token, you must make a call to the endpoint POST /auth.

Backoffice Access Request

For login authentication Backoffice, in the request enter the parameters:

          • username (username of the operator requesting access),

          • passwords (password associated with the operator requesting access),

          • campaignid (the campaign id of your brand related to the production environment | empty if the operator has network access),

          • devicetype (type of device from which the customer tries to log in 1=Browser 2=Android device 3=iOS Device)

          • scope (type of access required, in this case 'backoffice').

Request for Terminal Access

For login authentication Terminal, in the request enter the parameters:

          • username (username of the operator requesting access),

          • passwords (password associated with the operator requesting access),

          • serialnumber (serial number linked to the terminal associated with the operator requesting access),

          • campaignid (the campaign id of your brand related to the production environment),

          • devicetype (type of device from which the customer tries to log in 1=Browser 2=Android device 3=iOS Device)

          • scope (type of access required, in this case 'terminal').

Customer Access Request

For login authentication customersynchro, in the request enter the parameters:
(access to be used if the actions to be performed are before or during the customer registration phase, then before logging in)

          • username (field not to be inserted),

          • passwords (field not to be inserted),

          • campaignid (the campaign id of your brand related to the production environment),

          • devicetype (type of device from which the customer tries to log in 1=Browser, 2=Android device, 3=iOS Device)

          • scope (type of access required, in this case 'customersynchro').

For login authentication Customer, in the request enter the parameters:

          • username (username of the customer's account),

          • passwords (customer account password),

          • campaignid (the campaign id of your brand related to the production environment),

          • devicetype (type of device from which the customer tries to log in 1=Browser 2=Android device 3=iOS Device)

          • scope (type of access required, in this case 'customer').

If the outcome of the call to the POST /auth endpoint was http 200, a JSON object is obtained in response where the 'token' and 'refreshtoken' fields will be present.

For more details and errors, see the POST /Auth endpoint.

Onboarding con Marta

Example of accessing or registering a customer in a dedicated reserved area

To execute the log in of registered customer, follow the flow:

          1. Logging in.

To execute the sign in of a new customer, follow the flows:

          1. Signing in,

          2. New user,

          3. Data entry.

To execute the sign in of a not registered customer that already has a card, follow the flows:

          1. Signing in,

          2. User with card,

          3. if necessary, Data entry.

Logging in

If the user intends to access his private area, these are the steps to follow:

1. Make the authentication call for customer access through the endpoint POST /auth to obtain a valid session token.

The response, if successful, will return the token and a “customer” json object with the information of the referring customer.

2. Verify that in the “customer” object, all the mandatory data for your campaign are filled in.

If there is no data, it means that the customer aborted the registration before the end of the procedure and it is necessary to redirect him to an error page.

If successful, however, the customer has completed the login.

Signing in

If the user interacts with the “Register” button, these are the steps to follow:

1. Ask the user for a value to enter for 'mobile number' or 'email' and register it.

2. Make the authentication call for customersynchro access through the endpoint POST /auth to obtain a valid session token.

3. Check if the customer already exists, that is, if they already have a card, and if they have completed the personal data.

To get this information, make a call through the endpoint GET /customer/checkcard inserting in addition to the entered token the fields:

card (to be entered if the value requested and entered during registration is the code of the owned card),

email (to be entered if the value requested and entered during registration is an email address),

mobile (to be entered if the value requested and entered during registration is a mobile number).

The possible response cases are:

> If the result returned with status 402 and 53 on 'AnswerCode', the customer is a new user and must register it following the 'New User' flow;

> If the result returned with status 200, the customer has a card but the “registered_customer” field is false, register the obtained “customerid” field and follow the “User with card” flow;

> The result returned with status 200 and the “registered_customer” field is true, the user is already registered, so you have to return to the login page following the “Sign In” flow;

> The result returned with a different status from the previous ones, so report an error and return to the home page.

To see more technical details and errors, explore the API Reference section.

New user

To register a new user, the steps to follow are:

1. Allow the user to enter the new password and register it.

2. If it hasn't already been validated, make the authentication call for customersynchro access through the endpoint POST /auth to obtain a valid session token.

3. Send a validation code for OTP verification when the customer clicks on the reference icon.

Then make a call through the endpoint POST /customer/verifyemail by entering the following parameters:

campaignid (the campaign id of your brand related to the production environment),

emails (to be inserted if the value requested and entered during the “Register” flow is an email address),

mobile (to be entered if the value requested and entered during the “Register” flow is a telephone number),

devicetype (type of device from which the customer tries to log in 1=Browser 2=Android device 3=iOS Device).

If the result is positive, then it has http 200 status, continue. Otherwise, report that the sending of the OTP code was not successful and stay on this page.

4. Sent the code, make a call through the endpoint put/customer/registrationVCWithVerificationCode to verify the OTP (verification code), and, if appropriate, register the user directly, entering the following parameters:

verificationcode (OTP code obtained),

passwords (the password entered earlier),

devicetype (1=Browser, 2=Android Device, 3=iOS Device),

campaignid (the campaign id of your brand related to the production environment),

categoryID (the id of the virtual card category to be activated),

username (the value entered on the 'Register' page whether it is a mobile number or email),

mailcontactdata (to be inserted if the value entered on the “Register” page is an email address),

mobilecontactdata (to be entered if the value entered on the 'Register' page is a mobile phone number).

If the outcome is positive (http status 200), the user has been created and we have obtained in response the account info including the associated card number. Continue on the 'Data Insertion' flow.

In case of an error, show the error and stay on the page, otherwise go to the next page.

User with card

To register a new user who already has a card, the steps to follow are:

1. Allow the user to enter the new password and register it.

2. If it hasn't already been validated, make the authentication call for customersynchro access through the endpoint POST /auth to obtain a valid session token.

3. Send a validation code for OTP verification when the customer clicks on the reference icon.

Then make a call through the endpoint POST /customer/generateverificationcode by entering the following parameters:

customerid (the customer id obtained during the “Register” flow),

emails (to be inserted if the value requested and entered during the “Register” flow is an email address),

mobile (to be entered if the value requested and entered during the “Register” flow is a telephone number),

devicetype (type of device from which the customer tries to log in 1=Browser 2=Android device 3=iOS Device).

If the result is positive, then it has http 200 status, continue. Otherwise, report that the sending of the OTP code was not successful and stay on this page.

4. Once the code has been sent, verify the OTP (verification code), and, if appropriate, change the user's credentials.
To do this, make a call through the endpoint put/customer/changeUAPByVerificationCode, entering the following parameters:

customerid (the customer id obtained during the “Register” flow),

username (the value entered on the 'Register' page whether it is a mobile number or email),

passwords (the password entered earlier),

verificationcode (OTP code obtained).

If the outcome is positive (http status 200), the user has been created and we have obtained in response the account info including the associated card number.

Then we can continue on the 'Data Insertion' flow.

In case of an error, show the error that occurred and stay on the page, otherwise go to the next page.

To see more technical details and errors, explore the API Reference section.

Data entry

The account has been created and we have obtained the username (the mobile number) and the user's password.

To request the entry of the new user's personal data, the steps to follow are:

1. Make the authentication call for customer access through the endpoint POST /auth to obtain a valid session token, with the username and password obtained.

If the result is negative, return to the error page and contact support.

2. Get the list of fields (personal data) to fill in by making a call through the endpoint GET /customer/customerdatafields/ {campaignid} inserting the parameter:

          • campaignid (your brand's campaign id related to the production environment).

In response, we get the list of fixed fields on the platform. There are two objects: 'CustomDataFields', containing the list of customer personal data, and 'PrivacyCustomDataFields', containing the list of privacy permissions.

For each field within these objects, visibility (so if it is necessary to show it during compilation) and the mandatory nature of the field are specified, through two Booleans.

3. Make a call through the endpoint GET /customer, inserting no parameters.

In response, we obtain all the customer data that has already been registered, allowing us to pre-fill the data of the proposed form with the data collected from the call.
Through this call, we also obtain the 'card' field (card number) and the 'FidelyCode' field (relative barcode).

4. Show the fields received and wait for the entry, checking for mandatory fields and other possible errors.

5. At the end of entering the data by the customer, it is necessary to update the fields on the customer's personal data.

For this, make a call through the endpoint PUT /customer, entering the following parameters:

name (name entered, if required),

surname (last name entered, if required),

gender (gender inserted, if required),

birthdate (date of birth entered, if required),

usedforpromotions (choice of interaction with consent required (true or false),

•... Possible other consents to be set if required by the campaign,

mobilecontactdata (mobile number registered for the user),

mailcontactdata (registered email address for the user),

•... Possible other types of contacts and geolocation to be set if required by the campaign.

To see more technical details and errors, explore the API Reference section.

Tutorial reserved area

Sviluppa un'area risevrata completa con i tutorial di Marta

Viewing the Home

Within the home of your private area you can show:
> the information relating to the card, the points and the loyalty path that the customer is carrying out,
> the news in the foreground,
> the promotions in the foreground,
> the additional services of your brand in the foreground.

> Card

To request all the useful information related to the card, the points and the user's journey, two steps are necessary:

1. Make a call to the endpoint GET /customer, without entering any parameters.
In response, we obtain the customer's personal information, their point balance in the field customer->balance_points And the category of the card held in the field customer->category.

2. Make a call to the endpoint GET /customer/category/ {categoryid}, entering the parameter:

CategoryID (category id obtained in the previous call).

If the outcome is positive, in response we obtain the “CategoryDTO” object containing the characteristics of the customer's card, including the value of the cash points.

The fields of the 'CategotyDTo' object affected for viewing are:

CategoryDTO->WeightPointValuePoints,

CategoryDTO->WeightPointValueMoney,

and together they define the points-to-money ratio available.

Based on these values and the points balance, it is possible to calculate how many points are left until the next objectives and show the path that the user is taking.

> News

To get and show the list of news in the foreground, you need this step:

1. Make a call to the endpoint GET /customer/news passing the following parameters:

Infocus (value that defines the type of news to receive || 0=all news 1=only news in the foreground 2=only news NOT in the foreground),

•... Possible other values to add to better filter the news to receive.

If the outcome is positive, in response we obtain an array of “news” objects, which will be those visible to the customer, already ordered.

The fields of the “news” object affected for viewing are:

news->title (news title)

News->Summary text (short description that will be shown on homescreen)

News->expiredate (expiration date to check before showing the news)

News->NewsCategory (array that highlights the news category for possible filtering on the homescreen)

news->image (URL image of the news).

> Additional Services

To obtain the list of additional services, you need to:

1. Make the call to the endpoint Get/Customer/AvailableServices, entering the parameters:

Campaignid (the campaign id of your brand related to the production environment | required),

CategoryID (id of the service category to be inserted only if we want the services of that specific category),

Initlim and RowCount (parameters for pagination).

If the result is positive, an array of “AdditionalServices” objects is obtained in response.

The fields of the “AdditionalServices” object affected for viewing are:

AdditionalServices->title (title of service),

AdditionalServices->Summary (the short description to show on the homescreen),

AdditionalServices->VisibleFrom and AdditionalServices->visibleTo (range of effective dates of the service to check before showing the service),

AdditionalServices->Enable (Boolean that describes whether the service is active or not).

> Promotions

To obtain the list of valid promotions for the customer, this step is necessary:

1. Make a call to the endpoint GET /customer/promotionsoftarget, entering the parameter:

standings (the status of the promotions to receive || 0=Promo starting in thefuture 1=In execution 2=Stopped 3=Ended).

In this case, the status must be set to 1=In execution.

If the outcome is positive, in response we obtain a series of information, including the array of “promotions” objects containing the main data relating to promotions.

The fields of the “promotions” object affected for viewing are:

Description (name of the promotion),

Summary Text (short description of the promotion),

DateTo (end of the promotion),

URLImage (image of the promotion),

standings (promotion status).

In addition, for each promo item, there is an array of “prizes” items, which represent the prizes obtained by winning the promotion.

The fields of the “prizes” object affected for viewing are:

Kind (the type of prize),

Value (the description of the prize).

For more details and errors explore the API Reference section.

Personal profile

On the profile page, the personal data, consents and contacts registered by the user are shown.

To obtain and then then show all the customer's information, it is necessary:

1. Make the call to the endpoint GET /customer, without entering any parameters, receiving in response a “customer” object from which to record and show the information of interest.

To update personal data, if the customer enters new data or modifies existing data, it is necessary to follow these steps:

1. Make the call to the endpoint PUT /customer, entering the following parameters:

Name (name, unchanged if not changed or new name if entered),

Surname (last name unchanged if not changed or new last name if entered),

• gender (gender unchanged if not modified or new gender if inserted),

Birthdate (date of birth unchanged if not changed or new date of birth if inserted)

used for promotions (choice of interaction unchanged or in accordance with the changes made),

•... Possible other campaign consents to be able to manage,

mobilecontactdata (cell phone number unchanged if not changed or new number if entered),

mailcontactdata (email address unchanged if not modified or new email address if entered)

•... Possible other types of contacts and geolocation related to the campaign that you can manage.

For more details and errors explore the API Reference section.

Detail pages

> Detail page for promotions

To prepare the detail page dedicated to the list of valid promotions, it is necessary to:

1. Make the call to the endpoint GET /customer/promotionsoftarget, entering the parameter:

standings (0=Promo starting in thefuture 1=In execution 2=Stopped 3=Ended).

To obtain the list of active promotions, validate the status = 1 field and to view an archive instead, validate the status = 3 field.

If the outcome is positive, in response, we obtain, among other information, an array of “promotions” objects containing the main data of each promotion.

The object 'promotions' consists mainly of:

Description (name of the promotion),

Summary Text (short description of the promotion),

FullText (detailed description of the promotion),

DateTo (end date of the promotion),

URLImage (URL of the promotion image),

standings (promotion status),

• [Prizes] (array of “prizes” objects that describe the prizes related to the promotion).

The 'prizes' object consists mainly of:

Kind (the type of prize),

Value (the description of the prize).

Kind's list of awards is many, some of the most common awards are:

> kind=3 (prize: points with multiplier, and consequently in the field Value the value by which to multiply the customer's points will be indicated),

> kind 4 (prize: fixed points, and consequently in the field) Value the fixed value of points won will be indicated),

> kind=7 (event: message to appear on the terminal in case of winning),

> kind=9 (prize: a discount coupon in%, and consequently in the field Value the percentage discount value will be indicated),

> kind=10 (prize: a discount coupon in a fixed amount, and consequently in the field Value the amount of the voucher will be indicated),

> kind=11 (event: message to appear on the terminal if a voucher is won),

> kind=37 (event: image to be shown on the terminal in case of winning),

> kind=21 (prize: prize in the catalog, followed by an instant win promotion, and consequently the description of the prize will be indicated in the value field).

Except in the case of an InstantWin type promotion, which allows the option of winning a consolation prize, for each promotion it is possible to define only one type of winning benefit.


> Detail page for the Card

To process the detail page dedicated to the customer's Card information, it is necessary to:

1. Make a call to the endpoint GET /customer (if it hasn't been done before) without entering any parameters.
If the result is positive, we get the “customer” object.

The fields of the “customer” object affected for viewing are:

customer->name,

customer->surname,

customer->balance_points (points balance),

customer->card (card number),

Customer->FidelyCode (barcode or fidelycode of the card),

customer->status (card status, where 1=active, 2=blocked, 3=deleted).

> Detail page for additional services

To process the detail page dedicated to the list of additional services, it is necessary to:

1. Make the call to the endpoint GET /customer/availableservices, entering the parameters:

Campaignid (required | the campaign id of your brand related to the production environment),

CategoryID (id of the services category to be inserted only if we want the services of that specific category),

Initlim and RowCount (parameters for pagination).

If the result is positive, an array of “AdditionalServices” objects is obtained in response.

The “AdditionalServices” object consists of:

AdditionalServices->categoryID (category of services),

AdditionalServices->PathImage (url of the service image),

AdditionalServices->title (title of service),

AdditionalServices->Summary (the short description to show on the homescreen),

AdditionalServices->Description (detailed description of the service),

AdditionalServices->VisibleFrom and AdditionalServices->visibleTo (range of effective dates of the service to check before showing the service),

AdditionalServices->Enable (Boolean that describes whether the service is active or not).


> Detail page for coupons

To process the detail page dedicated to the list of coupons obtained and available to the customer, it is necessary to:

1. Make the call to the endpoint GET /customer/vouchers, entering the parameters for the pagination:

initlimit (start of list),

Rowscount (number of records to display).

If the outcome is positive, in response we obtain various information, including an array of “VoucherList” json objects, which contains all the information related to the voucher, the promotion to which it is associated and the usage details.

To complete the list of available coupons, the fields of the “VoucherList” object concerned are:

Voucherlist->title,

VoucherList -> Description,

Voucherlist->used (which specifies whether the coupon has been used or not),

VoucherList -> ExpirationDate,

Voucherlist -> Kind,

VoucherList->value,

VoucherList - > netinuseList - > name (in case CanUseVoucherOnlyInnet is validated to true).

> Privacy consents

To show the current states of the consents and possibly modify them, it is necessary to:

1. Check the value of the consent fields in the 'customer' object obtained following the call to the endpoint GET /customer.


The fields related to consents are:

customer->privacy->usedforpromotions,

Customer->privacy->usedforStatistics,

customer->privacy->used by others,

Customer->privacy->CangetCurrentLocation,

Customer->Privacy->CAN Communicate Verification.

The first three fields are consents related to the use of data.

2. To update the consents, make a call to the endpoint PUT /customer, entering the following parameters:

Name (customer name),

Surname (customer's last name),

Gender (customer gender),

Birthdate (customer's date of birth)

Used for Promotions,

Used for Statistics,

Used by Others,

mobilecontactdata (cell phone number unchanged if not changed or new number if entered),

mailcontactdata (email address unchanged if not modified or new email address if entered)

•... Possible other types of contacts and geolocation related to the campaign that you can manage.


> To disable and re-enable push notifications, you must rely directly on the onesignal API. Verify their documentation.

Store locator

The Customer API section contains four different endpoints that allow you to request store details based on various needs.

> Store by distance

Obtain the list of stores near the current position of the active device using the endpoin GET /customer/shops/bydistance.

It’s important to note that if the customer does not allow geolocation, this service will not be enabled.

          1. Call the endpoint GET /customer/shops/bydistance, providing the following parameters:

  • lat (latitude of the device performing the operation),
  • long (longitude of the device performing the operation).

If successful, the response will contain an array of "shops" objects, associated with the netAndShop model, already sorted by distance.

The useful fields of “shops” objects for listing are:

  • shops->name (store name)
  • shops->distance (distance in km)
  • shop->addressPrefix
  • shops->address
  • shops->addressNumber (street address)
  • shops->zip (postal code)
  • shops->geoLevel3Name (city)
  • shops->telephone (phone number)
  • shops->mail (email address)

The fields required for map display are:

  • shops->geoLat (latitude for geolocation),
  • shops->geoLong (longitude for geolocation).

the fields for displaying detailed store info are:

  • shops->openingHours,
  • shops->description.

Both fields may contain HTML code to customize opening hours and services.

> Store by filters

Search for stores using filters in the query, through the endpoint GET /customer/shops.

Possible search filters include store or network code or name, category, and geolocation data of the device.

  1. Call the endpoint GET /customer/shops, with the following query parameters:
    • shopcategory (store category code | number)
    • netid (network code | number)
    • shopgroupid (store group code | number)
    • name (store name | string)
    • companyname (company name | string)
    • country (country code | number)
    • geolevel1 to geolevel5 (geo-level codes | number)
    • zip (postal code | string)
    • taxnumber (tax ID | string)
    • enabled (only show enabled stores | boolean)
    • visible (only show visible stores | boolean)
    • geolat and geolong (latitude and longitude | number)
    • radiusinmeters (radius of interest in meters | number)
    • initlimit (pagination index | number)
    • rowcount (pagination index | number)

If successful, the response will contain an array of "shops" objects, associated with the shopDTO model, already sorted by distance.

The fields useful for listing are:

  • shops->name
  • shops->distance
  • shop->addressPrefix
  • shops->address
  • shops->addressNumber
  • shops->zip
  • shops->telephone
  • shops->mail
  • shops->facebookFanPage
  • shops->twitterProfile
  • shops->instagramProfile
  • shops->youtubeChannel

The fields for map display are:

  • shops->geoLat
  • shops->geoLong

The fields for store details are:

  • shops->openingHours
  • shops->description.

> Store by radius and address

Request the list of stores within a defined radius starting from an entered address, via the endpoint GET /customer/shops/byradiusandaddress.

  1. Call the endpoint with these query parameters:
    • geolat and geolong (latitude and longitude | number)
    • radius (area radius | number)
    • visible (only show visible stores | boolean)
    • initlimit (pagination index | number)
    • rowcount (pagination index | number)

If successful, the response will contain an array of "shops" objects, associated with the shopDTO model, already sorted by distance.

Same listing, mapping, and detail fields apply as in the previous method.

> Store by radius and geoposition

Request the list of stores within a defined radius based on address coordinates, using the endpoint GET /customer/shops/byradiusandgeoposition.

  1. Call the endpoint with these query parameters:
    • address (starting address | string)
    • address_number (starting address number | number)
    • city (starting city | string)
    • country (country code | number)
    • radius (area radius | number)
    • visible (only show visible stores | boolean)
    • initlimit (pagination index | number)
    • rowcount (pagination index | number)

If successful, the response will contain an array of "shops" objects, associated with the shopDTO model, already sorted by distance.

Same listing, mapping, and detail fields apply as in the previous methods.


For more details and errors explore the API Reference section.

Integrazione front-end di cassa

Integra i tuoi front-end di cassa con i tutorial di Marta

Per avviare l'integrazione base con il front-end di cassa, seguire il flusso:

              -Autenticazione,

              -Avvio cassa, recupero regole epermessi campagna.

Per registrazione una card, seguire il flusso:

              -Autenticazione,

              -Registrazione Card.

Per effettuare un movimento di vendita, seguire il flusso:

              -Autenticazione,

              -Lettura Card,

              -Chiusura scontrino,

              -Acquisto.

Per integrare e gestire la feature Gift Card, seguire il flusso:

              -Autenticazione,              

              -Gift Card lettura e uso.

Eliminazione ultimo movimento

              -Autenticazione,

              -Eliminazione ultimo movimento.

Autenticazione

Per eseguire un accesso terminal, effettuare la chiamata all’endpoint POST /auth, inserendo i seguenti parametri:

• username (username dell’operatore che richiede l’accesso),

• password (password associata all’operatore che richiedel’accesso),

• serialnumber (numero seriale legato al terminaleassociato all’operatore che richiede l’accesso),

• campaignid (l'id della campagna del tuo brand relativoall’ambiente di produzione),

• devicetype (tipo di device da cui il cliente tenta difare l’accesso 1=Browser 2=Android device 3=iOS Device)

          • scope (‘terminal’ o ‘terminal-backoffice’).

In caso di esitopositivo, nella risposta otterremo anche il bearer token (tokenautorizzativo) che dovrà essere inserito nell’header delle successive chiamatealle API di tipo Terminal.

Ecco un esempiodel body in una request all’endpoint POST /auth per effettuareun’autenticazione terminal:

{

              "username":"opwsDemo",

              "password":"123456",

               "serialnumber": 444001,

              "foreignid": "",

              "scope": "terminal"

}'

Avvio cassa, recupero regole epermessi campagna

Per eseguirel’integrazione di front-end di cassa, è necessario registrare le regole e ipermessi della campagna associata al terminale interessato.

              1.Effettuare una chiamataall’endpoint GET /terminal/ campaign/{campaignid}, specificando nell’url ilvalore “campaignid”, ovvero l’id della campagna.

In caso di esitopositivo, in risposta otterremo un oggetto JSON “campaign” che mostra tutte leinformazioni relative e un oggetto “terminal” contenente i dettagli delterminale.

Le informazionicontenute nell’oggetto “campaign” ci interesseranno per le successive azioni.

 

Per permettere alfront-end di cassa di gestire la movimentazione, è importante ottenere leponderazioni di tutte le categorie di card che possono essere utilizzatedall’account terminal loggato.

              2.Effettuare una chiamataall’endpoint GET /terminal/cardcategories.

In caso di esitopositivo, in risposta otterremo un oggetto JSON “category” contenente un arraycon tutte le categorie di card utilizzabili e le corrispettive informazioni.

Quelle piùrilevanti sono quelle relative alle ponderazioni, ovvero la corrispondenzapunti/denaro.

I campiinteressati sono:

·       weightChargePointMoney  e weightChargePointPoints (definiscono i punti da ottenere inbase ai soldi spesi)

·       weightPointValueMoney e weightPointValuePoint (definisconolo sconto ottenibile in base ai punti caricati sulla card)

Ecco un esempiodi risposta all’endpoint GET /terminal/cardcategories:

{

"answerCode": 0,

"category": [

   {

     "id":463,

    "shopId": 1112,

    "weightPointValueMoney": 0.01,

    "weightPointValuePoint": 1,

    "weightChargeCreditMoney": 0,

    "weightChargeCreditPoints": 0,

    "weightChargePointMoney": 0.1,

    "weightChargePointPoints": 0.01,

    "weightDischargeCreditMoney": 0,

    "weightDischargeCreditPoints": 0,

    "weightExchangePrizePoints": 1,

    "weightExchangePrizeMoney": 1,

    "pointsInActivation": 0,

    "initialCharge": 0,

    "currencyId": 0,

    "currencySymbol": "",

    "minLimitDischargePoint": 0,

     "weightPointValueMoneyCashBack":0,

    "weightPointValuePointsCashBack": 0,

    "code": 83,

    "campaign": 362,

    "name": "Categoria Card Test",

    "flags": {

      "flags": 34952,

      "isGIFT": false,

      "deliverPointsInChargeCredits": false,

      "deliverPointsInDischargeCredits": false,

      "deliverPointsInSale": true,

      "deliverPointsInActivation": false,

      "showPointsInActivationTicket": false,

      "showMoney4PointsInTicket": false,

      "useExpirationCard": true,

      "customerOnlyAllowInActivationShop": false,

      "registerActivationPointsInCampaign": false,

      "onlyOneUse": false,

      "sellerCategory": false,

      "checkMinimalLimitDischargePoints": false,

      "checkCanNotTransaction": false,

      "dealerCategory": false,

      "deliverPointsInCashback": false

     },

    "urlImage": ""

   }

 ],

"pagination": {

  "initLimit": 0,

   "rowCount":100,

  "recordsTotal": 10,

   "actualPage":1,

   "totalPages": 1

 }

}

Se la campagnainteressata include la presenza di campi dinamici nell’anagrafe del customer, ènecessario:

              3. Effettuare una chiamataall’endpoint GET /terminal/dynamicfields/{campaignid}, specificando nell’url ilvalore “campaignid”, ovvero l’id della campagna.

In caso di esitopositivo, in risposta otterremo un array di oggetti JSON “dynamicFields”,rappresentante la lista di campi dinamici definiti all’interno della campagna.

 

Se la campagnainteressata include la gestione di prodotti, è necessario:

              4.Effettuare una chiamataall’endpoint GET /terminal/product, specificando nell’url solo i dettagli perl’impaginazione, ovvero:

·       initlimit (limite iniziale),

rowcount (numero di record da mostrare).

Registrazione Card

              Card anonima ???

              Card con inserimento dati congestione consensi privacy

Per registrare eattivare una nuova card, è necessario:

1.Effettuare una chiamata all’endpoint POST /terminal/customers, inserendo idati anagrafici di interesse.

Tramite front-enddi cassa è possibile creare e attivare una card fisica oppure una cardvirtuale. I campi che ci interessano in questa fase sono  “card”, “fidelycode” e “categoryid”, dainserire nel body della request.

Nel caso in cuiintendiamo attivare una card fisica, è necessario valorizzare i campi “card” e“fidelycode” con i codici indicati sulla card interessata, lasciando vuoto ilcampo “categoryid”.

Se inveceintendiamo attivare una card virtuale, i campi “card” e “fidelycode”  devono essere lasciati vuoti mentre il campo“categoryid” deve essere valorizzato con l’id della categoria che la nuova carddovrà assumere e da cui deriva la numerazione automatica.

 

A questo punto pervisualizzare i campi visibili e obbligatori da richiedere al customer einserire nel body della request, è necessario valutare l’oggetto JSON campaign->completeCustomerFieldsottenuto dalla chiamata all’endpoint GET /terminal/campaign/{campaignid}analizzata nel flusso Avvio cassa, recupero regole e permessi campagna.

Ecco un esempio delbody in una request all’endpoint POST /terminal/customers per la creazione diun nuovo customer, con assegnazione automatica del nr di card, con solo alcunidati essenziali (nome, cognome, data di nascita, cellulare, consensi privacy edun campo dinamico):

{

"campaignid": 362,

"categoryid": 463,

"card”:"",

"fidelycode": "",

"parentcustomerid": "",

"mlmcustomerid": "",

"mlmcustomercard": "",

 "zoneid":"",

"zoneforeignid": "",

"identitycard": "",

"identitycardtypeid": "0",

 "name":"Mario",

 "surname":"Rossi",

 "gender":"M",

"birthdate": "1970-10-01",

"username": "mario.rossi@myemail.it",

"usedforpromotions": true,

"usedforstatistics": true,

"usedbyothers": false,

"cangetcurrentlocation": false,

"cancomunicaverification": false,

"expdateusedprom": "2025-10-31",

"expdateusedstatis": "2025-10-31",

"expdateusedothers": "2025-10-31",

"expdateusedgen": "2025-10-31",

"mailcontactdata": "mario.rossi@myemail.it",

"mobilecontactdata": "33311122777",

"telephonecontactdata": "",

"faxcontactdata": "",

"addressprefix": "",

 "address":"",

"addressnumber": "",

 "zip":"",

 "country":0,

"geolevel1": 0,

"geolevel2": 0,

"geolevel3": 0,

"geolevel4": 0,

"geolevel5": 0,

"facebookid": "",

"twitterid": "",

"instagramid": "",

"youtubeid": "",

"customerdynamicfields": [

               {

                "id": 648,

               "value":"valore di test"

               }

 ],

"accountnumber": "",

"frequentflyernumber": "",

"pathimage": "",

"foreignid": "",

"notsendwelcomemail": false,

 "invitor_code": "",

 "notes": "" }

Per la gestionedei consensi privacy, prima di inserire le preferenze relative nel body dellaquery alle chiamate POST /terminal/customers o PUT /terminal/customers (modificadelle informazioni della card),è necessario confermare le scelte del customer tramite una verifica double OTP.

              1.Come primo passo, servegenerare e inviare al customer un codice OTP per ogni consenso da inserire omodificare. É necessario quindi effettuare chiamate all’endpoint POST/terminal/customers/genotpcodeconsents, inserendo i seguenti parametri:

·       customerid (id del customer, ricevuto in risposta allachiamata all’endpoint POST /terminal/customers),

·       mobile (numero di cellulare del customer | se inseritonon serve valorizzare il campo email),

·       email (indirizzo email del customer | se inserito nonserve valorizzare il campo mobile).

2.Inviati i codici OTP interessati, per verificare le scelte del customerbisogna effettuare una chiamata all’endpoint POST /terminal/customers/verifyOotpcodeconsents,inserendo per ogni consenso legato alla campagna il codice OTP consegnato e lascelta del cliente relativa al consenso specificato.

Ecco un esempio delbody di una request all’endpoint POST /terminal/customers/verifyOotpcodeconsentsdove sono stati richiesti tutti i consensi, ma accettati solo il consenso per lepromozioni e per la geolocalizzazione.

{

"customerid": 123456,

"promotioncode": "055832",

"promotionconsent": true,

"statisticcode": "274829",

"statisticconsent": false,

"othercode": "235267",

"otherconsent": false,

"geolocationcode": "028474",

"geolocationconsent": true

}

5.Lettura Card

Al momento diinterazione tra un customer registrato e il front-end di cassa, è necessarioeffettuare la lettura della card posseduta.

              1.Effettuare una chiamataall’endpoint GET /terminal/customers{nrcard}, specificando nell’url il valore “nrcard”,ovvero il numero di card.

In caso di esitopositivo, in risposta otterremo anche un oggetto JSON “customer” contenentetutte le informazioni della card, sia anagrafiche che contabili (saldo punti,crediti, badge, ecc).

Nel caso in cuiil “answerCode” non è valorizzato a 0, significa che la chiamata non è andata abuon fine.

Le casistiche dirisposta da tenere in considerazione sono:

> “answerCode”= 53              
La card richiesta non esiste, ma il numero è comunque tra quelli validi per lacampagna. Quindi potrebbe essere il caso di una nuova card che va attivata.

> “answerCode”= 59
La card non è presente in white list. Vuol dire che si è inserito un numero dicard che NON può essere utilizzato per la campagna.

> “answerCode”= 60
Card in blacklist. Vuol dire che il nr di card inserito è relativo ad una cardnon più esistente, molto probabilmente è stata sostituita con un'altra card.

 

Questa chiamatapermette di recuperare le ponderazioni della card, utili per un’eventuale spesao movimento successivo.

 

Ecco un esempiodi risposta che otteniamo dalla chiamata all’endpoint GET/terminal/customers{nrcard} :

{

              "answerCode": 0,

"customer":  {

  "id": 123456789,

  "campaignId": 111,

  "card": 50,

  "fidelyCode": 12345678901234,

  "parentCustomerId": 0,

  "mlmCustomerId": 0,

  "totalMlmChildren": 0,

  "registration_shop_id": 123456789,

  "registration_net_id": 123456789,

  "registration_shop_foreign_id": 0,

  "registration_net_foreign_id": 0,

  "zoneId": 0,

  "zoneForeignId": 0,

  "customer_area_status": 1,

  "mailContactData": "nomail@nomail.com",

  "mobileContactData": "3334445566",

  "totalExchangedPrizes": 10,

  "totalMoneyInSale": 0,

  "paidMoneyInSale": 0,

  "totalManualDischargedPoints": 100,

  "totalDischargedPointsInSale": 50,

  "totalDischargedPointsInExchanged": 150,

  "expiredPoints": 0,

  "personalInfo": {

     "identityCard":"ggghhh00a00b111x",

     "identityCardTypeId": 0,

     "name": "Mario",

     "surname": "Rossi",

     "gender": "M",

     "birthdate":"1978-04-08T00:00:00.000+01:00",

     "notes": "",

     "userName":"nomail@nomail.com",

     "privacy": {

       "flags": 3,

       "usedForPromotions": true,

       "usedForStatistics": true,

       "usedByOthers": false,

       "canGetCurrentLocation":false,

       "canComunicaVerification":false,

       "expDateUsedProm":"2020-12-02T11:24:07.000+01:00",

       "expDateUsedStatis":"2021-02-02T11:36:51.000+01:00",

       "expDateUsedGen":"2021-07-03T11:17:02.000+02:00"

     },

     "mailContactData":"nomail@nomail.com",

     "mobileContactData": "3334445566",

    "telephoneContactData": "",

     "faxContactData":"",

     "address":"della Repubblica",

     "addressNumber":"10",

     "addressPrefix":"Piazza",

     "zip": "50100",

     "country": 3,

     "geoLevel1": 20,

     "geoLevel2": 87,

     "geoLevel3": 1512,

     "geoLevel4": 4579,

     "geoLevel5": 0,

     "facebookId": "",

     "twitterId": "",

     "instagramId": "",

     "youtubeId": "",

     "principalCard": false,

     "customerDynamicFields": [

       {

         "id": 12,

         "value": "any kind ofvalue"

       }

     ],

     "foreignid": ""

  },

  "balanceData": {

     "category": 101,

     "status": 1,

     "cardType": 0,

     "pointsCharged": 1210,

     "pointsUsed": 423,

     "creditsCharged": 12,

     "creditsUsed": 6,

     "creditsGiftCharged": 0,

     "creditsGiftUsed": 0,

     "rechargesCard": 23,

     "usesCard": 47,

     "balance_points": 787,

     "balance_credits": 6,

     "balance_gift_credits": 0,

     "total_money_in_sale": 4268,

     "paid_money_in_sale": 3472,

     "pointsChargedCount": 87,

     "pointsUsedCount": 42,

     "creditsUsedCount": 15,

     "creditsGiftUsedCount": 0,

     "expiredPoints": 0,

     "pointsToMoney": 0,

     "pointsMLMCharged": 0,

     "pointsMLMUsed": 0,

     "customerInformationToExpired":{

       "pointToExpire": 0,

       "periodoForeignid": 0

     }

  },

  "issuedDate": "2015-12-01+01:00",

  "customerAreaFlags": {

     "flags": 7,

     "useWeb": true,

     "useAndroid": true,

     "useiOS": false,

     "useJME": false,

     "useBB": false

  },

  "levelBadge": {

     "ID": 1,

     "name": "nomelevel",

     "campaingID": 0,

     "minPointsStatus": 0,

     "maxPointsStatus": 100,

     "icon": "pathimage",

     "flags": {

       "enabled": true

     }

  },

  "pointStatus": 25,

  "badges": [

     {

       "ID": 121,

       "name":"BadgeName",

       "description": "Badgeshort description",

       "longDescription":"Badge long description",

       "onIcon":"https://www.somewhere.com/onicon.png",

       "onOff":"https://www.somewhere.com/officon.png",

       "image":"https://www.somewhere.com/badgeimage.png",

       "points": 0,

       "pointsStatus": 10,

       "flags": {

         "enabled": true

       },

       "categoryBadge": {

         "ID": 0,

         "campaignID": 0

       }

     }

  ],

  "giftCardCustomerOwnerId": 0,

  "umbralCampaign": 20,

  "pccu": true,

  "flags": {

     "flags": 0,

     "activatedFromPointsCharge":false,

     "nameChanged": false,

     "failCardActivation": false,

     "migratedFromFNet1": false,

     "migratedFromFNet2": false,

     "fatherExtension": false,

    "activatedOfflineWithoutPoints": false,

     "merged": false,

     "imported": false,

     "wonPointsByCompleteAllData":false,

     "decrementCardStockByImpor":false,

    "notGivePointsOnActivationFromExternalComponent": false,

     "principalCard": false,

     "fatherFamilyCard": false,

     "verifiedEmail": true,

     "verifiedMobile":true

   }

       }

}

Chiusura scontrino

Al momento dellachiusura dello scontrino, prima del pagamento, è necessario valutare se per ilcustomer che sta effettuando l’acquisto ha a disposizione possibili sconti ovouchers.

Relativamenteagli sconti, i passi da seguire sono:

              1.Recuperare gli oggetti JSON “categories”e “customer” ottenuti dai flussi Avvio cassa, recupero regole epermessi campagna e Lettura della card.

              2.Dall’oggetto JSON “customer”,recuperare la categoria relativa al customer interessato (customer->balanceData->category)e i punti disponibili  (customer->balanceData->balance_points).

              3.Dall’oggetto JSON “categories”,recuperare le ponderazioni relative alla categoria interessata.

              4.Eseguire i calcoli in base alleponderazioni ottenute per valutare la presenza di sconti.

 

Per quantoriguarda i vouchers invece, le API di tipo Terminal  offrono l’endpoint GET /terminal/vouchers,permettendo di ottenere l’elenco dei vouchers in possesso del customer.

MARTA indentificacome voucher i buoni sconto, dividendoli in buoni sconto in percentuale e buonisconto per importo.

              1.Effettuare una chiamataall’endpoint GET /terminal/vouchers, specificando nella query:

·       campaignid (id della campagna, presente anche nell’oggettoJSON “customer” utilizzato nei passaggi precedenti),

·      customer id (id del customer),

·       card (numero della card relativa, presente nell’oggettoJSON “customer”).

·       initlimit (limite iniziale),

·       rowcount (numero di record da mostrare).

In caso di esitopositivo, in risposta otterremo un oggetto JSON “voucherList” contenenteun array di voucher.

Per informazioniprecise sulla risposta ed ulteriori dettagli tecnici fare riferimento a: https://martaapidemo.keyx.it/doc/#/API%20Terminal/get_terminal_vouchers.

 

I campi degli oggettidell’array “vouchersList” che ci interessano sono:

·       id                                         (id del voucher),

·       voucherCode                (Barcode del voucher, da usareper il riconoscimento del voucher),

·       title                                     (Descrizione breve del voucher),

·       description                    (Descrizioneestesa del voucher),

·       expirationDate              (Datadi scadenza del voucher),

·       kind                                    (Tipologiadel voucher. 1=sconto in % 2=sconto per importo),

·       value                                 (Valore del voucher in percentuale oimporto a seconda del kind).

Ecco un esempiodi request all’endpoint GET /terminal/vouchers:

curl --location 'https://martaapidemo.keyx.it/terminal/vouchers?campaignid=362&customerid=195580&card=4&initlimit=0&rowcount=50'\

--header 'Authorization:••••••'

Acquisto

L’acquisto rappresentail momento più complesso se parliamo di interazione tra card e terminale.

Durante l’acquistoinfatti, si effettua la maggior parte della movimentazione eseguibile su unpunto vendita, perché oltre a registrare l’atto da parte del cliente, vengonogestiti:

> l’utilizzodi benefit per ottenere degli sconti come lo scarico punti,  sconti diretti, l’utilizzo di coupon sconto emolto altro,

> l’ottenimentodei punti in base all’importo netto dell’acquisto,

> la ricezionedi eventuali benefit.

              1.Effettuare una chiamata all’endpointPOST /terminal/sale, inserendo principalmente i seguenti parametri:

·       totalmoney                                    (Importototale della vendita),

·       dischargedcredits                     (Importodei crediti da scalare all’importo totale della vendita),

·       dischargedpoints                      (Quantitadi punti da scaricare, che vengono convertiti in sconto sull’importo totaledella vendita),

·       voucherid                                      (iddel voucher sconto eventualmente utilizzato, da scalare dall’importo totaledella vendita),

Se la campagnaprevede l’utilizzo dei prodotti, bisogna completare l’array:

·       productlist                                     (arraycontenente la lista dei prodotti utilizzati nella vendita)

prizecode  //codicedel prodotto

price //prezzounitario del prodotto

amount //quantità del prodotto

La sommatoria ditutti gli importi di vendita dei singoli prodotti deve corrispondereall’importo totale della vendita contenuto nel campo “totalmoney”. Nel caso nonsi volesse far calcolare in automatico a MARTA i punti da caricare sulla cardper l’acquisto di questo prodotto, è necessario valorizzare i seguenti campi:

useChargeDirectPoints // impostare a true

productChargeDirectPoints //punti da caricare sulla card

·       pincode                                          (pincodedel cliente, se il movimento di vendita contiene punti da scaricare e lacampagna prevede il pincode per lo scarico di punti),

·       customerpincodedc                (pincodecreditdel cliente, se il movimento di vendita contiene crediti da scaricare e lacampagna prevede il pincode per lo scarico di crediti),

·       paymentmethod                         (metododel pagamento, se nella campagna viene registato),

L’array “paymentmethod”contiene l’elenco dei metodi di pagamento utilizzati e i campi obbligatori dainserire nell’oggetto sono:

id   //id del tipo di pagamento

money //importo pagato

La sommatoria degliimporti dei vari metodi di pagamento deve corrispondere all’importo netto dellavendita ottenuto sottraendo al campo “totalmoney” il valore di “dischargedcredits”,il valore monetario di “dischargedpoints”  e il valore del voucher indicato da “voucherid”.

Nel caso non sivolesse far calcolare in automatico a MARTA i punti da caricare sulla card perl’acquisto, è necessario valorizzare i seguenti campi:

·       usechargedirectpoints           (davalorizzare a true nel caso non si volesse far calcolare automatico a MARTA ipunti da caricare in base alle ponderazioni impostate),

·       chargedirectpoints                   (quantitàdi punti da caricare scelta, da inserire nel caso usechargedirectpoints siastato valorizzato a true).

 

$ É importantenotare che la possibilità di definre il caricamento forzato di punti sulla cardsi presenta due volte: nella compilazione dell’array productlist e allafine del body della request. Questi campi sono autoesclusivi, di conseguenza ènecessario valorizzare i valori corretti o nel dettaglio prodotti o nel totaledel movimento, mai in entrambi per evitare incongruenze.

 

Come annunciatoprima, per calcolare l’effettivo importo netto della vendita è necessario sottrarreal valore del campo “totalmoney” il valore di “dischargedcredits”, ilvalore monetario di “dischargedpoints”  e il valore del voucher indicato da “voucherid”.

Il valore monetariodi “dischargedpoints” e il valore dell’eventuale voucher indicato in “voucherid”sono recuperabili seguendo la sezione Chiusura Scontrino.

 

Per il contenutodella risposta ed altri dettagli tecnici consultare:

https://martaapidemo.keyx.it/doc/#/API%20Terminal/post_terminal_movements_sale

 

Ecco un esempiodi request con curl all’endpoint POST /terminal/sale.
In questo esempio viene registrata una una spesa di 10 euro con 2 prodotti, dicui su uno è stato forzato l’assegnazione di 8 punti escludendo laponderazioine, l’utilizzo di crediti per 5 euro, e l’utilizzo di un metodo dipagamento.

curl --location'https://martaapidemo.keyx.it/terminal/movements/sale' \

--header 'Content-Type: application/json' \

--header 'Accept: application/json' \

--header 'Authorization: ••••••' \

--data '{

"campaignid": 362,

"customerid": 195580,

 "card": 4,

 "dischargedcredits":5,

 "dischargedpoints":0,

"totalmoney": 10,

"totalBenefits": 0,

"ticketid": "",

"discountid": "",

"voucherid": "",

"operatorforeignid": "",

"paymentmethod": [

   {

     "id":46,

    "money": 5

   }

 ],

"foreignid": "",

"productlist": [

   {

      "code" : "pro2",

      "price" : 7,

      "amount" : 1

   },

   {

      "code" : "pro1",

      "price" : 3,

      "amount" : 1,

       "useChargeDirectPoints":true,

      "productChargeDirectPoints": 8

   }

 ],

 "note":"Any string note you want",

 "customerpincodedc": 1234

}

 

 

Eliminazione ultimo movimento

Per eseguire l’eliminazionedell’ultimo movimento effettuato su una Card, è necessario:

1.Seguire il flusso Lettura della Card.

2.Effettuare una chiamata all’endpoint DELETE /terminal/movements/last,inserendo nel body della request i seguenti parametri:

·       customerid (l’id del customer, ottenuto dal passo precedente| campo obbligatorio),

·       sellercard (il numero della card, ottenuto dal passoprecedente),

·       notes (note relative all’eliminazione se è necessario).

É importarenotare che esiste una parametrizzazione a livello campagna che permette diimpostare un limite di tempo entro il quale effettuare questa eliminazione.

Ecco un esempiodel body in una request all’endpoint DELETE /terminal/movements/last:

{

              "customerid":123456,

              "sellercard":123456,

              "notes”:"”

}

Gift card lettura e uso

All’interno dellatua campagna, puoi intraprendere e gestire la feature delle Gift card.

Prima di integrarequesta funzionalità, è essenziale aver recuperato gli oggetti JSON “categories”e “customer” ottenuti dai flussi Avvio cassa, recupero regole epermessi campagna e Lettura della card.

 

Per attivare unagift card da terminale è necessario:

              1.Effettuare una chiamata all’endpointPOST /terminal/gift, passando nel body della request i seguenti parametri:

·       campaignid

·       card

·       initialamount (valore dell’importo da caricare sulla Gift card),

·       notes.

 

Nel caso ilparametro initialamount venga passato a zero, la gift card viene caricata conl’importo di default definito sulla categoria della card ??? , altrimenti vienecaricata con l’importo inserito.

 

Per il contenutodella risposta ed altri dettagli tecnici consultare:

https://martaapidemo.keyx.it/doc/#/API%20Terminal/post_terminal_gift

 

Ecco un esempio delbody di una request all’endpoint POST /terminal/gift:

{

"campaignid": 362,

 "card":6029,

"initialamount": 50,

 "notes":""

}

 

Per poterscaricare crediti da una gift card occorre:

              1.Effettuare una chiamata all’endpointPOST /terminal/movements/dischargecreditsgift, inserendo nel body della requesti seguenti parametri:

·       campaignid

·       customerid

·       card

·       dischargegiftcredits

·       customerpincodepc.

Nel caso lacampagna abbia attivato la gestione del pincode crediti, è obbigatorio passareanche il campo customerpincodepc che deve contenere il pincode.

 

Per il contenutodella risposta ed altri dettagli tecnici consultare:https://martaapidemo.keyx.it/doc/#/API%20Terminal/post_terminal_movements_dischargecreditsgift

 

Ecco un esempio di request all’endpoint POST / terminal/movements/dischargecreditsgift:

curl --location'https://martaapidemo.keyx.it/terminal/movements/dischargecreditsgift' \

--header 'Content-Type: application/json' \

--header 'Authorization: ••••••' \

--data '{

"campaignid": 362,

"customerid": 463874,

 "card":6029,

"dischargegiftcredits": 15,

 "notes":"",

 "customerpincodepc": null

}’