# PHP

### BACKEND

#### PHP SDK - How to Use Rocketfuel with PHP SDK

*This is a technical guide for developers and it requires programming experience to follow through the guide.*

**Prerequisite:**

1. An approved Rocketfuel Merchant Account
2. Composer installed on the server

#### How to Install PHP SDK on your PHP app

There are two ways to install PHP SDK

**a. Installation via composer**

`composer require rkfl/rocketfuel-php-sdk`

**b. Manual installation**

```
git clone https://bitbucket.org/rocketfuelblockchain/rocketfuel-php-sdk.git 
cd rocketfuel-php-sdk 
composer install
```

For php integration without composer, follow

#### Usage Examples

1. Get UUID for triggering iFrame - (\*UUID is a Unique User Identifier).

```
<?php
use RKFL\Api\Client\Options;
use RKFL\Api\Client\Rocketfuel;
require_once <PATH_TO_VENDOR> . '/autoload.php';

$options = new Options(
    [
        'environment' => 'sandbox', //or prod
        'merchant_id' => 'MERCHANT_ID',
        'merchant_public_key' => "PUBLIC_KEY",
        'client_id'=>"CLIENT_ID",
        'client_secret'=>"CLIENT_SECRET",
    ]
);

$rocketfuel = new RocketFuel($options);

$payload = [
    'amount' => '100',
    'cart' => [
        [
            'id' => '1',
            'name' => 'test',
            'price' => '100',
            'quantity' => '1'
        ]
    ],
    'currency' => 'USD',
    'order' => '001'
];

$response = $rocketfuel->service()->getUUID($payload);

```

2\. Verify callback from RocketFuel

```
<?php
    use RKFL\Api\Client\Options;
    use RKFL\Api\Client\Rocketfuel;
    require_once <PATH_TO_VENDOR> . '/autoload.php';
    
    $options = new Options(
    [
        'environment' => 'sandbox', //or prod
        'merchant_id' => 'MERCHANT_ID',
        'merchant_public_key' => "PUBLIC_KEY",
        'client_id'=>"CLIENT_ID",
        'client_secret'=>"CLIENT_SECRET",
    ]
);
    
    $rocketfuel = new RocketFuel($options);
    
    $status= $rocketfuel->helpers()->verifyWebhook($data, $signature);
    
```

3\. Manually Cancel a Subscription

```
<?php
use RKFL\Api\Client\Options;
use RKFL\Api\Client\Rocketfuel;
require_once <PATH_TO_VENDOR> . '/autoload.php';

$options = new Options(
    [
        'environment' => 'sandbox', //or prod
        'merchant_id' => 'MERCHANT_ID',
        'merchant_public_key' => "PUBLIC_KEY",
        'client_id'=>"CLIENT_ID",
        'client_secret'=>"CLIENT_SECRET",
    ]
);

$rocketfuel = new RocketFuel($options);

$subscriptionId = '123_sub';

$status= $rocketfuel->subscription()->cancel($subscriptionId);

```

4\. Manually Debit a Subscription

```
<?php
use RKFL\Api\Client\Options;
use RKFL\Api\Client\Rocketfuel;
require_once <PATH_TO_VENDOR> . '/autoload.php';

$options = new Options(
    [
        'environment' => 'sandbox', //or prod
        'merchant_id' => 'MERCHANT_ID',
        'merchant_public_key' => "PUBLIC_KEY",
        'client_id'=>"CLIENT_ID",
        'client_secret'=>"CLIENT_SECRET",
    ]
);

$rocketfuel = new RocketFuel($options);

$orderId= '123';

$subscriptionData = [
  ...,
  [
    subscriptionId=>'123_sub',
    amount=>1,
    currency=>'USD'
  ],
  ...
];

$status= $rocketfuel->subscription()->debit($orderId, $subscriptionData);
```

#### How to configure SDK <a href="#how-to-configure-sdk" id="how-to-configure-sdk"></a>

Use this code snippet for setting it up.

```
<?php
use RKFL\Api\Client\Options;
use RKFL\Api\Client\RocketFuel;

$options = new Options(
    [
        'environment' => 'sandbox', //or prod
        'merchant_id' => 'MERCHANT_ID',
        'merchant_public_key' => "PUBLIC_KEY",
        'client_id'=>"CLIENT_ID",
        'client_secret'=>"CLIENT_SECRET",
    ]
);

$rocketfuel = new RocketFuel($options);
```

`MERCHANT_ID`,`PASSWORD`,`EMAIL`,`PUBLIC_KEY` are merchant details. See [below ](#how-to-retrieve-merchant-details)to retrieve these details&#x20;

### PHP SDK WITHOUT COMPOSER

To integrate with PHP without composer, you will need to use [this](https://github.com/RocketFuel-BlockChain-Inc/rocketfuel-php-client/blob/development/readme.md).

Step 1: Clone repo into project

```
git clone git@bitbucket.org:rocketfuelblockchain/rocketfuel-php-client.git
```

Step 2: Configure the client and access its methods

```
   require_once(PATH_TO_RKFL.'../src/RKFL_CLIENT.php');
   //configure Options
   $options = array(
       'environment'=>'sandbox', //sandbox -- prod,
       'merchantId'=>'MERCHANT_ID',
        'secret'=>'CLIENTSECRET',
        'clientId'=>'CLIENTID'
   );

   $rkfl = new \RKFL\Client\RKFL_CLIENT($options);

   $payload = array(
       "amount" => "100",
       "cart" => array(
           array(
               "name" => "Test",
               "id" => "200",
               "price" => 100,
               "quantity" => "1"
           )
       ),
       "merchant_id" => MERCHANT_ID,
       "currency" => "USD",
       "order" => "20",
       "redirectUrl" => ""
   );

   $rkfl->rkflgenerateUUID($payload);
```

#### Using webhook

For more information, visit[ webhook ](https:docs.rocketfuelblockchain.com/webhooks)

```
   require_once(PATH_TO_RKFL.'../src/WEBHOOK_CLASS.php');
    use RKFL\Client\WEBHOOK_CLASS as rkflWebhook

    /**
     * $_REQUEST wont work because the webhook is application/json format and not formdata format
     */
    $payload = file_get_contents('php://input'); //use for receiving payload from RKFL SERVER

    $payload = json_decode($payload);

    $result = rkflWebhook::verify_callback($payload->data->data, $payload->signature);

    if ($result) {
        echo "verified \n";
    } else {
        echo 'not verified';
        return;
    }
    rkflWebhook::validate_payment($payload->data);
```

### FRONTEND

#### **RKFL JS** [**CDN**](https://d3rpjm0wf8u2co.cloudfront.net/static/rkfl.js) **and Implementation**

* Add the script from [**CDN**](https://d3rpjm0wf8u2co.cloudfront.net/static/rkfl.js) to the Merchant site.
* Once we get the response with the UUID from the backend. We will initialise an object of the above included script. We pass the following :
  * uuid
  * callback function&#x20;
  * environment
  * Token

```
    const  uuidInfo = JSON.parse(result);
   
     if(uuidInfo.error !== undefined){
        alert("Order placement failed");
        return  false;
    }
    
    uuid = uuidInfo.uuid;
    
    rkfl = new RocketFuel({
        uuid,
        callback:  callBackFunc,
        environment:  "<%= developmentEnv %>"  // prod, preprod
    });
```

* After initialising the object, start the payment by calling the initPayment method of the above script.

```
    function  startPayment(){
        rkfl.initPayment();
    }
```

* Callback payload

```
 // In case of Bank/Exchange payment
          {
            paymentMode: 'Bank/Exchange',
            txn_id: 
            status: 
            meta:
          },

          Sample response:
          {
            paymentMode: 'Bank/Exchange',
            txn_id: "7df55d22-fa5e-4ca2-9af4-a39c95f18b3a"
            status: 0
            meta: {offerId: "1630402767550"}
          },



// In case of Wallet payment
      {
        paymentMode: 'Wallet',
        status: 
        recievedAmount:
        currency:
      },

       Sample response:
       {
           paymentMode: 'Wallet',
           status:"completed",
           recievedAmount:10.00,
           currency:"ETH"
       }
```

## SSO Login <a href="#markdown-header-sso-login" id="markdown-header-sso-login"></a>

### Create merchant Auth using the [PUBLIC\_KEY](https://github.com/RocketFuel-BlockChain-Inc/rocketfuel-readme/blob/master/notification.md) <a href="#markdown-header-create-merchant-auth-using-the-public_key" id="markdown-header-create-merchant-auth-using-the-public_key"></a>

```
    ### JS Code snippet

        var merchantAuth = function(merchantId) {
            var buffer = Buffer.from(merchantId);
            var encrypted = crypto.publicEncrypt(process.env.PUBLIC_KEY, buffer);
            return encrypted.toString("base64");
        }
```

### RKFL Token usage <a href="#markdown-header-rkfl-token-usage" id="markdown-header-rkfl-token-usage"></a>

* Autosignup

  ```
      const payload = {
          firstName: firstName,
          lastName, lastName,
          email: email,
          merchantAuth: "<%= merchantAuth %>",
      }
      rkfl = new RocketFuel({ environment: "<%= developmentEnv %>", });
      rkfl.rkflAutoSignUp(payload, environment = "<%= developmentEnv %>").then((res) => {
          // save this rkflToken for reference in the DB 
          // It is unique to each customer
          res.result.rkflToken;
      })})
  ```
* Existing RKFL Token

  ```
      rkfl = new  RocketFuel({
          token, // rkfltoken
          uuid,
          callback:  callBackFunc,
          environment:  "<%= developmentEnv %>"  // prod, preprod
      })
  ```

You can refer to the [REFERENCE\_LINK](https://github.com/RocketFuel-BlockChain-Inc/rocketfuel-demo-hosted-v2) for demonstration.

### How To Retrieve Merchant Details <a href="#how-to-retrieve-merchant-details" id="how-to-retrieve-merchant-details"></a>

The Email and Password refer to the email/password you use in signing into your merchant portal on <https://merchant.rocketfuel.inc> or equivalent.

The environment refers to the type of details you are using. You should choose production for real transactions and select sandbox when you are testing.

To retrieve Public Key, visit  [https://Merchant.rocketfuel.inc/settings](https://merchant.rocketfuel.inc/settings) and copy the string highlighted in the screenshot below.

![](https://1226631082-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fxp9w5RKLdYBhhpcmcvEp%2Fuploads%2FJz1RoCMt82uegG2j5KO9%2Fimage.png?alt=media\&token=7c6b5998-16e3-455e-98ee-5ff8990a0339)

You can also retrieve Merchant Id from the same page. Simply scroll up on the settings page and copy from the section highlighted below

![](https://1226631082-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fxp9w5RKLdYBhhpcmcvEp%2Fuploads%2FAkfYTutdSmxVNlXplAR4%2Fimage.png?alt=media\&token=efb4c208-937e-47b2-8df2-6e3535e7dcaa)
