PHPackages                             nofraud/connect - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Security](/categories/security)
4. /
5. nofraud/connect

ActiveMagento2-module[Security](/categories/security)

nofraud/connect
===============

Sends your transactions to NoFraud for verification of no fraud.

1.7.0(1y ago)133.1k↓37.2%2[4 PRs](https://github.com/Nofraud/nofraud_connect/pulls)OSL-3.0PHPPHP &gt;7.0.1CI passing

Since Jun 25Pushed 1y ago3 watchersCompare

[ Source](https://github.com/Nofraud/nofraud_connect)[ Packagist](https://packagist.org/packages/nofraud/connect)[ RSS](/packages/nofraud-connect/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (1)Versions (41)Used By (0)

NoFraud Connect (M2)
====================

[](#nofraud-connect-m2)

Integrates NoFraud's post-payment-gateway API functionality into Magento 2.

Sections
--------

[](#sections)

- [ Getting Started ](#markdown-header-getting-started)
    - [ Installation ](#markdown-header-installation)
    - [ Configuration ](#markdown-header-configuration)
    - [ Troubleshooting ](#markdown-header-troubleshooting)
    - [ Known Issues ](#markdown-header-known-issues)
    - [ Features to be Implemented ](#markdown-header-features-to-be-implemented)
- [ Flow of Execution (Checkout) ](#markdown-header-flow-of-execution-checkout)
    - [ Observer\\SalesOrderPaymentPlaceEnd ](#markdown-header-observersalesorderpaymentplaceend)
    - [ Helper\\Config ](#markdown-header-helperconfig)
    - [ Api\\RequestHandler ](#markdown-header-apirequesthandler)
    - [ Api\\ResponseHandler ](#markdown-header-apiresponsehandler)
    - [ Logger\\Logger ](#markdown-header-loggerlogger)
- [ Flow of Execution (Updating Orders Marked for Review) ](#markdown-header-flow-of-execution-updating-orders-marked-for-review)
    - [ Cron\\UpdateOrdersUnderReview ](#markdown-header-cronupdateordersunderreview)
    - [ etc/crontab.xml ](#markdown-header-etccrontabxml)
- [ Admin Panel Special Configuration ](#markdown-header-admin-panel-special-configuration)
    - [ Model\\Config\\Source\\EnabledPaymentMethods ](#markdown-header-modelconfigsourceenabledpaymentmethods)
    - [ etc/di.xml ](#markdown-header-etcdixml)
    - [ Helper\\Data ](#markdown-header-helperdata)
- [Dispatch Event Considerations](#markdown-header-dispatch-event-considerations)
    - [ Global vs. Frontend Scope ](#markdown-header-global-vs-frontend-scope)
    - [ Potential for Duplicate API Calls ](#markdown-header-potential-for-duplicate-api-calls)
- [Matters of Opinion](#markdown-header-matters-of-opinion)
    - [ Code Style ](#markdown-header-code-style)
    - [ Separation of Concerns ](#markdown-header-separation-of-concerns)

Getting Started
---------------

[](#getting-started)

### Installation

[](#installation)

---

Just copy to the appropriate folder and run `php magento setup:upgrade`.

```
git clone git@bitbucket.org:razoyo/mage2-module-nofraud.git
cp -r mage2-module-nofraud/app/ ~/current
php ~/current/bin/magento setup:upgrade

```

From the COMMAND LINE using Composer:

```
1. Update composer to require the "nofraud/connect" package with the command: $ composer require nofraud/connect dev-master

2. To enable the module, run the command: $ bin/magento module:enable NoFraud_Connect

3. Then run setup:upgrade to install the necessary updates, with the command: $ bin/magento setup:upgrade

4. If a production environment - re deploy the static content and run the di compiler

```

### Configuration

[](#configuration)

---

### Troubleshooting

[](#troubleshooting)

---

All logging happens in `/var/log/nofraud_connect/info.log`

### Known Issues

[](#known-issues)

---

- [ Cron job is defined and tested but doesn't run on its own ](#markdown-header-etccrontabxml)
- [ "Screened Payment Methods" has the expected effect, but does not show all enabled payment options as choices ](#markdown-header-difficulty-returning-array-of-all-enabled-payment-methods)

### Features to be Implemented

[](#features-to-be-implemented)

---

- Ability to auto-refund orders based on NoFraud API response

NoFraud API Basics
------------------

[](#nofraud-api-basics)

There are two type of requests used in this module:

- `POST` requests, to create new NoFraud transaction records
- `GET` requests, to retreive the status of an existing NoFraud transaction record

### Creating New Records

[](#creating-new-records)

---

Posting a JSON decription of a transaction will create a new record, and will return a small JSON object:

```
{
  "id":"16f235a0-e4a3-529c-9b83-bd15fe722110",
  "decision":"pass"
}
```

An additional `message` key will be present for a "fail" decision, but this key is never used by the module.

```
{
  "id":"16f235a0-e4a3-529c-9b83-bd15fe722110",
  "decision":"fail",
  "message":"Declined"
}
```

### Getting the Status of Existing Records

[](#getting-the-status-of-existing-records)

---

A `GET` request sent to `https://api.nofraud.com/status/:nf_token/:order_id` will return a similar response:

```
{
  "id":"16f235a0-e4a3-529c-9b83-bd15fe722110",
  "decision":"pass"
}
```

The `:order_id` can either be the unique NoFraud transaction `id` provided in the original API response, or the associated Magento Order `increment_id`. Either one can be used interchangeably.

### Errors

[](#errors)

---

If either

- improperly formatted or insufficient data is posted to the API, or
- a status is requested for an invalid transaction ID

a JSON object will be returned, containing an array of one or more error message strings.

```
{
  "Errors":[
    "Error Message 1.",
    "Error Message 2."
  ]
}
```

User Experience
---------------

[](#user-experience)

### Customer

[](#customer)

---

As this module implements post-payment-gateway functionality, the customer checkout experience should remain unchanged.

### Site Admin

[](#site-admin)

---

At the end of the checkout process, information about the transaction is posted to the NoFraud API. In all cases, the response from NoFraud is attached to the `Order` in question as a Status History Comment. This is displayed on the Order's admin page, and provides a link directly to the associated record on the NoFraud website.

Depending on the decision returned by NoFraud ("pass", "fail", or "review"), the `Order` in question can also automatically be placed in a custom status (for example, "On Hold", "Fraud Detected", "Cancelled", etc.). A custom status can also be configured for the case that NoFraud returns an error message.

All of the above can restricted to apply only to certain payment methods. It's also possible to restrict processing to `Order`s with a certain status at the time of execution (for example, if an order is already "Complete", it can be ignored).

Orders placed under review will be updated in NoFraud's database to a "pass" or "fail" at a later time. The module will periodically check the status of such orders, and once a final "pass" or "fail" decision is received from the NoFraud API, the Order's status in Magento will be updated according to the same configuration options described above.

#### Auto-Refund

[](#auto-refund)

While not yet implemented, Orders should additionally be able to be automatically refunded based on the conditions decribed above.

Flow of Execution (Checkout)
----------------------------

[](#flow-of-execution-checkout)

### Observer\\SalesOrderPaymentPlaceEnd

[](#observersalesorderpaymentplaceend)

---

As far creating new NoFraud transaction records, this class is where it all happens.

The observer listens for the `sales_order_payment_place_end` event, which dispatches after a payment is placed (`\Magento\Sales\Model\Order\Payment->place()`), and makes available the associated `Payment` object.

> NOTE: Listening to this particular event is largely out of my initial deference to the original M1 module, and in light of new information, listening for a later event may reduce complexity. ([ see below ](#markdown-header-potential-for-duplicate-api-calls))

#### What Happens During Execution:

[](#what-happens-during-execution)

1. If the transaction should be ignored, then:
    1. Do nothing.
2. Else:
    1. Post the transaction's information to the NoFraud API;
    2. Add a comment to the Order, depending on the API response;
    3. Modify the status of the Order, depending on the API response and the module's configuration;
    4. Save the Order.

#### The Actual Flow of Execution:

[](#the-actual-flow-of-execution)

1. If the module is disabled, then:
    1. Stop execution.
2. Get the `Payment` from the `Observer`;
3. If the Payment should be ignored, then:
    1. Stop execution.
4. If the Payment does not have a transaction ID AND is not an offline payment method, then:
    1. Stop execution.

    > NOTE: This condition is essentially a compatibility measure for Authorize.net. ([ see below ](#markdown-header-potential-for-duplicate-api-calls))
5. Get the `Order` from the `Payment`;
6. If the Order should be ignored, then:
    1. Stop execution.
7. Get the NoFraud API Token from Config;
8. Get the appropriate API URL, depending on the "Sandbox Mode" setting in Config;
9. Prepare the body of the NoFraud API request, from the `Payment` and `Order` objects;
10. Send the API request and get the response;
11. Add a comment to the `Order`, depending on the response (good or bad);
12. If the response was good (no API server errors), then:
    1. Update the status of the `Order`, depending on the "Custom Order Statuses" setting in Config;
13. Save the `Order`.

This all relies on the following classes:

### Helper\\Config

[](#helperconfig)

---

This class contains simple "getter" functions for each Admin Config setting, along with a few wrapper functions which compare provided input against Config values and return a boolean.

### Api\\RequestHandler

[](#apirequesthandler)

---

This class contains only three public functions:

#### RequestHandler public function build( $payment, $order, $apiToken )

[](#requesthandler-public-function-build-payment-order-apitoken-)

Builds the body (a JSON object) for a `POST` request to the NoFraud API.

This function is only involved in creating new NoFraud transaction records during checkout (`\NoFraud\Connect\Observer\SalesOrderPaymentPlaceEnd`).

The full object model this function can build resembles the below example (not all values are always present, and keys with empty non-numeric values are removed). The full model accepted by the NoFraud API is [described here](https://portal.nofraud.com/pages/developer-documentation#1.4).

```
{
  "nf-token": "API-KEY-EXAMPLE",
  "amount": "100.00",
  "shippingAmount": "20.00",
  "currency_code": "USD",
  "customer": {
    "email": "someperson@gmail.com"
  },
  "order":{
    "invoiceNumber": "1123581321"
  },
  "payment": {
    "creditCard": {
      "last4": "1111",
      "cardType": "Visa",
      "cardNumber": "4111111111111111",
      "expirationDate": "0919",
      "cardCode": "999",
    }
  },
  "billTo": {
    "firstName": "Some",
    "lastName": "Person",
    "company": "Some Company",
    "address": "1234 Main St Apt #123",
    "city": "New York",
    "state": "NY",
    "zip": "11001",
    "country": "US",
    "phoneNumber": "1112223333"
  },
  "shipTo": {
    "firstName": "Another",
    "lastName": "Person",
    "company": "Another Company",
    "address": "4321 Ave A",
    "city": "Paris",
    "state": "TX",
    "zip": "77000",
    "country": "US"
  },
  "customerIP": "127.0.0.1",
  "avsResultCode": "U",
  "cvvResultCode": "1",
  "lineItems": [
    {
      "sku": "12345",
      "name": "Example Product 1",
      "price": 24.95,
      "quantity": 3
    },
    {
      "sku": "23456",
      "name": "Example Product 2",
      "price": 179.49,
      "quantity": 1
    }
  ],
  "userFields": {
    "magento2_payment_method": "payflowpro"
  }
}

```

#### RequestHandler public function send( $params, $apiUrl, $statusRequest = false )

[](#requesthandler-public-function-send-params-apiurl-statusrequest--false-)

Sends requests to the NoFraud API and returns a `$resultMap` (see Protected Functions).

By default, this function handles `POST` requests prepared by `build(...)`. If `$statusRequest` is truthy, then a `GET` request is sent instead, and `$params` is assumed to contain only an existing NoFraud Transaction ID and the NoFraud API token.

#### RequestHandler public function getTransactionStatus( $nofraudTransactionId, $apiToken, $apiUrl )

[](#requesthandler-public-function-gettransactionstatus-nofraudtransactionid-apitoken-apiurl-)

A readability wrapper for retrieving the current status of a NoFraud transaction record via `send(...)`.

This function is currently only called from `\NoFraud\Connect\Cron\UpdateOrdersUnderReview`.

#### Default AVS and CVV Codes

[](#default-avs-and-cvv-codes)

```
