directpay-ipg-js
Version:
Directpay IPG Plugin
245 lines (200 loc) • 9.97 kB
Markdown
# directpay-ipg-js
DirectPay Internet payment gateway javascript plugin.
## Installation
### NPM packages
#### JS
```bash
$ npm install directpay-ipg-js
```
#### React
```bash
$ npm install react-directpay-ipg
```
#### Angular
```bash
$ npm install ng-direct-pay-ipg
```
#### VUE
```bash
$ npm install vue-directpay-ipg
```
### CDN
```html
<script src="https://cdn.directpay.lk/v3/directpayipg.min.js"></script>
```
### WooCommerce
<a id="raw-url" href="https://cdn.directpay.lk/v3/wp/directpay-ipg-woocommerce.zip">Download Plugin</a>
## Usage
### package
```js
const DirectpayIpg = require('directpay-ipg-js')
const dp = new DirectpayIpg.Init({
signature: signature,
dataString: encoded_payload,
stage: 'DEV',
container: 'card_container'
})
//popup IPG
dp.doInAppCheckout().then((data) => {
console.log('client-res', JSON.stringify(data))
}).catch((error) => {
console.log('client-error', JSON.stringify(error))
})
//open IPG inside page component
dp.doInContainerCheckout().then((data) => {
console.log('client-res', JSON.stringify(data))
}).catch((error) => {
console.log('client-error', JSON.stringify(error))
})
```
### CDN
```html
<div id="card_container"></div>
<script src="https://cdn.directpay.lk/v3/directpayipg.min.js"></script>
<script>
var dp = new DirectPayIpg.Init({
signature: signature,
dataString: encoded_payload,
stage: 'DEV',
container: 'card_container'
});
//popup IPG
dp.doInAppCheckout().then((data) => {
console.log("client-res", JSON.stringify(data));
alert(JSON.stringify(data))
}).catch(error => {
console.log("client-error", JSON.stringify(error));
alert(JSON.stringify(error))
});
//open IPG inside page component
dp.doInContainerCheckout().then((data) => {
console.log("client-res", JSON.stringify(data));
alert(JSON.stringify(data))
}).catch(error => {
console.log("client-error", JSON.stringify(error));
alert(JSON.stringify(error))
});
</script>
```
### How to make a payment?
1. first select stage - ```DEV / PROD```
2. Create payment **payload** & **signature** from Server-side and parse signature and base64 encoded payload to *
Plugin*
*Note: it's the best practice to create payload and signature from server side. otherwise, the data will be
compromised.*
#### payload
Payload is a base64 encoded string that created from JSON payload string. Here is a sample object,
```js
payload = {
merchant_id: "xxxxxx",
amount: "10.00",
type: "ONE_TIME",
order_id: "CP123456789",
currency: "LKR",
response_url: "https://test.com/response-endpoint",
first_name: "Sam",
last_name: "Perera",
email: "user@email.com",
phone: "0712345678",
logo: "",
};
```
#### signature
Signature is HmacSHA256 hash of the base64 encoded payload string. The **secret** for HmacSHA256 can be found at
developer portal.
```js
createHmacSha256Hash(base64jsonPayload, secret);
```
##### Signature generate in PHP
```php
$encode_payload = base64_encode(json_encode($json_payload));
$signature = hash_hmac('sha256', $encode_payload, 'SECRET');
```
##### Signature generate in JS
```js
var encode_payload = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(JSON.stringify(json_payload)));
var signature = CryptoJS.HmacSHA256( encode_payload, 'SECRET');
```
##### Signature generate in JAVA
```java
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec('SECRET'.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hmacSha256 = mac.doFinal(encode_payload.getBytes(StandardCharsets.UTF_8));
signature = String.format("%032x", new BigInteger(1, hmacSha256));
```
#### Response Security (Serverside Response Validation)
##### Step 1: Fetch authorization header and request payload.
```php
// Request payload
$requestBody = file_get_contents('php://input');
// Authorization header
$signature = $_SERVER['HTTP_AUTHORIZATION'];
```
##### Step 2: Split Authorization header (signature) into two parts from space character and extract request hash received.
```php
$authArray = explode(' ', $signature);
$receivedHash = $authArray[1]; // Received hash
```
##### After splitting the authorization header, if there are two parts, it is a valid authorization header. Otherwise the header is invalid.
```php
if (count($authArray) == 2) {
// Proceed signature verification
} else {
echo "Invalid Signature.";
}
```
##### Step 3: Generate hmac hash for received request payload using hmac secret key provided by DirectPay.
**Note: Received request payload is a json encoded and then base64 encoded data string.**
```php
$secret = "vs6568s7v2aklsdv687a3dn8a6q92z";
$generatedHash = hash_hmac('sha256', $requestBody, $secret);
```
##### Step 4: Compare generated hash with the received hash.
```php
if (strcmp($receivedHash, $generatedHash) == 0) {
echo "Signature Verified.";
} else {
echo "Signature Verification Failed.";
}
```
**If two hashes are identical, then the signature is valid and the request is a valid request, hence the request can be authenticated. Otherwise, the request is invalid or fraud.**
##### Complete example code:
```php
// Request payload
$requestBody = file_get_contents('php://input');
// Authorization header
$signature = $_SERVER['HTTP_AUTHORIZATION'];
$authArray = explode(' ', $signature);
$receivedHash = $authArray[1]; // Received hash
$secret = "vs6568s7v2aklsdv687a3dn8a6q92z";
if (count($authArray) == 2) {
$generatedHash = hash_hmac('sha256', $requestBody, $secret);
if (strcmp($receivedHash, $generatedHash) == 0) {
echo "Signature Verified.";
} else {
echo "Signature Verification Failed.";
}
} else {
echo "Invalid Signature.";
}
```
#### Parameters
| Field | Type | Description | Allow values | Mandatory | Length |
|--------------------|---------|----------------------------------------------------------------------------------------------|----------------------------------------------------------|-------------------------------------|--------|
| merchant_id | String | Merchant identification code given form DirectPay | | YES | |
| amount | String | Transaction amount | | YES | |
| currency | String | Transaction currency code. | USD, LKR | | |
| type | String | Transaction Type | ONE_TIME, RECURRING, CARD_ADD | YES | |
| order_id | String | Every transaction need unique reference | | YES | |
| return_url | String | After transaction process redirect to given url | | NO | |
| response_url | String | Server-side response URL /HTTP POST request will be sent to the given endpoint | | NO | |
| first_name | String | Customer first name - Auto fill the IPG UI customer details | | NO | |
| last_name | String | Customer last name - Auto fill the IPG UI customer details | | NO | |
| email | String | Customer email - Auto fill the IPG UI customer details | | NO | |
| phone | String | Customer mobile number - Auto fill the IPG UI customer details | | NO | |
| logo | String | Merchant logo - need to provide secure image url of the logo. this will appear in the IPG UI | | NO | |
| start_date | String | Starting date of the recurring payment | YYYY-MM-DD | Mandatory when **TYPE = RECURRING** | 10 |
| end_date | String | End date of the recurring payment | YYYY-MM-DD | NO | 10 |
| do_initial_payment | Integer | Recurring initiate time transaction | 1 = YES / 0 = NO | Mandatory when **TYPE = RECURRING** | |
| interval | Integer | Frequency of payment | 1 = MONTHLY, 2 = BIANNUALLY, 3 = ANNUALLY, 4 = QUARTERLY | Mandatory when **TYPE = RECURRING** | |