Creating a Gift Card Application with Snipcart & PHP

Gift cards are awesome, right? When relatives give you one for Christmas or your birthday, it's like they're saying: "Listen, I know you like that place. But we both know it's better if you actually buy the exact stuff you want in there. It'll save us both some trouble." Gift cards are a win-win gift, always. Whether they're digital or physical, they help us avoid a whole lot of awkwardness as a society. Because let's be honest here: how bad a feeling is it when you receive a gift you totally don't appreciate but have to muster the social energy to fake gratefulness?

At Snipcart, we've received many requests about handling gift cards via our application. We've decided to put a blog post together showing any interested user one way to do just that. So today, I'll show you how easy it is to create a gift card application with Snipcart and PHP. Let's get into it now, shall we?

First of all, we need to create a discount every time a customer buys our gift card. The easiest way to do this is by using Snipcart webhooks. But before going deep into webhooks, we are going to add our gift card product into our HTML. Here's an example of what it'll look like:

<a href="#"
  class="snipcart-add-item"
  data-item-id="1"
  data-item-name="20$ gift card"
  data-item-price="20"
  data-item-weight="0"
  data-item-url="Our Url"
  data-item-description="awesome 20$ gift card"
  data-item-custom1-name="To"
  data-item-custom2-name="From">
    20$ gift card
</a>

Now take a closer look at those custom fields: this is where we are going to stock the information about the gift card recipient and the gift card sender. By creating these fields, we will be able to use them with our webhook.

For now, we have a legit product, named "20$ gift card", which can be bought by our customers. When checking out in the cart, the customer will be asked to enter a sender email and a recipient email.

After the gift card order is completed, Snipcart will call our webhook.php. To do this, you will have to enter the URL of your PHP file in the Snipcart webhooks settings . In this example, I'm developing locally with ngrok. If you want to know more about developing with Snipcart and ngrok, you can read our blog post Develop a Snipcart Powered Website Locally Using ngrok.

So what now? We need to create a discount in Snipcart every time our gift card is bought. To do this in PHP, I used PHP Curl. Here is the specific function that creates the discount:

 function addGiftCardToDiscounts($discountCode){

    $ch = curl_init();
    $key = "Some valid API key";
    $options = array(
        CURLOPT_URL            => "https://app.snipcart.com/api/discounts",
        CURLOPT_USERPWD        => $key,
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_HTTPHEADER     => array(
            'Accept: application/json',
            'Content-Type: application/json'
        ),
        CURLOPT_POSTFIELDS     => "{ 
            name: 'Gift Card 20$',
            trigger: 'Code',
            code: '". $discountCode."',
            type: 'FixedAmount',
            shippingDescription: '20$ gift card',
            amount: 20
        }"
        
    );
    curl_setopt_array($ch, $options);
curl_exec($ch);
    curl_close($ch);
}

Don't forget to add the proper headers and post fields as I did here. Wondering where to get the API key? You can get it by adding a secret API key in the Snipcart webhooks settings.

After the discount has been created, we can notify the recipient by sending an email with the new discount code we just created.

$message = "Hey " . $recipientEmail . 
  ", Your friend " . $senderEmail . 
  "is sending you a 20$ gift card. Here is the code: " . 
  $discountCode;
      
mail($recipientEmail, "Your new gift card", $message);

But it is not over yet! We also need to reduce the gift card's remaining amount every time the recipient buys something with it. To do this, we are going to add another function:

function reduceGiftCardAmount($updatedAmount, $discount){

    $ch = curl_init();
    $key = "Some valid API key";
    $options = array(
        CURLOPT_URL => "https://app.snipcart.com/api/discounts/"
        . $discount['discountId'],
        CURLOPT_USERPWD        => $key,
        CURLOPT_CUSTOMREQUEST  => "PUT",
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_HTTPHEADER     => array(
            'Accept: application/json',
            'Content-Type: application/json'
        ),
        CURLOPT_POSTFIELDS     => "{ 
            id: '" . $discount['id'] . "'," .
            "name:'" . $discount['name'] . "'," .
            "trigger:'" . $discount['trigger'] . "'," .
            "code:'" . $discount['code'] . "'," .
            "type:'" . $discount['type'] . "'," .
            "amount:" . $updatedAmount . 
        "}"
    );
    curl_setopt_array($ch, $options);
    curl_exec($ch); 
    curl_close($ch);
}

In this function, we call Snipcart's e-commerce API with a PUT request on the discount. Don't forget to add the discount identifier to the URL here. Again, you need to add the proper headers and post fields. The updated amount is the amount of the discount minus items total.

With this function added, everytime a customer buys a product with the gift card's discount code, we reduce the remaining amount of this discount in Snipcart.

Merge this code with our webhooks code snippet and you'll have a nice gift card application!

<?php
$json = file_get_contents('php://input');
$body = json_decode($json, true);

if (is_null($body) or !isset($body['eventName'])) {
    header('HTTP/1.1 400 Bad Request');
    return;
}
switch ($body['eventName']) {
    case 'order.completed':

        $items = $body['content']['items'];
        $discounts = $body['content']['discounts'];
        $giftCardId = 1;
        $discountCode = "A unique gift card code";

        foreach ($items as $key => $item) {
        
            if($item['id'] == $giftCardId){
                
                addGiftCardToDiscounts($discountCode);
      
        $customFields = $body['content']['customFields'];
                $senderEmail = "";
                $recipientEmail = "";
                foreach ($customFields as $key => $field) {
                    switch($field['name']){
                        case 'To':
                            $recipientEmail = $field['value'];  
                            break;
                        case 'From':
                            $senderEmail = $field['value'];
                            break;
                    }
                }
                $message = "Hey " . $recipientEmail . ", Your friend " 
                  . $senderEmail . "is sending you a 20$ gift card. Here is the code: " 
                  . $discountCode;
      
        mail($recipientEmail, "Your new gift card", $message);
            }    
        }
        foreach ($discounts as $key => $discount) {

            if($discount['code'] === $discountCode && $amount > 0){
      $amount = $discount['amount'];
                $itemsTotal = $body['content']['itemsTotal'];
                $updatedAmount = $amount - $itemsTotal;

                reduceGiftCardAmount($updatedAmount, $discount);
            }
        }
        break;
}
header('HTTP/1.1 200 OK');

That's about it, folks! I hope this post helps you offer nice gift cards to your customers (and save them from awkward moments with their loved ones). If you have any questions or feedback regarding this little gift card app we've built, drop us a line at geeks@snipcart.com. We'll be glad to discuss ideas and answer questions! As always, feel free to let us know what you think in the comments section below.

Suggested posts: