}
     $ins_sql = "INSERT INTO app (shop) VALUES ('" . $_REQUEST['shop'] . "')";
     $shop_id = mysql_query($ins_sql);
     $shopifyClient = new ShopifyClient($shop, "", SHOPIFY_API_KEY, SHOPIFY_SECRET);
     $pageURL = 'http';
     if ($_SERVER["HTTPS"] == "on") {
         $pageURL .= "s";
     }
     $pageURL .= "://";
     if ($_SERVER["SERVER_PORT"] != "80") {
         $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
     } else {
         $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
     }
     $pageURL = str_replace("?", "&", urldecode($pageURL));
     header("Location: " . $shopifyClient->getAuthorizeUrl(SHOPIFY_SCOPE, $pageURL));
     exit;
 }
 if ($_REQUEST['shop'] != '' || $_SESSION['shop'] != '') {
     $shop = $_REQUEST['shop'] != '' ? $_REQUEST['shop'] : $_SESSION['shop'];
     $select_sql = "SELECT `id`,`token`,`payment_status`, `app_status` FROM `app` WHERE `shop` = '" . $shop . "' ORDER BY `id` DESC LIMIT 1";
     $res = mysql_query($select_sql);
     if (mysql_num_rows($res) > 0) {
         $res_arr = mysql_fetch_assoc($res);
         $token = $res_arr['token'];
         $payment_status = $res_arr['payment_status'];
         $app_status = $res_arr['app_status'];
         $id = $res_arr['id'];
     }
     if (($payment_status == 'accepted' || $payment_status == 'free') && $app_status == 'installed') {
         header("Location: admin/add_image.php?shop=" . $shop);
    $_SESSION['token'] = $token;
    if ($_SESSION['token'] != '') {
        $_SESSION['shop'] = $_GET['shop'];
    }
    echo $token;
    header("Location: shop.php");
    exit;
} else {
    if (isset($_POST['shop']) || isset($_GET['shop'])) {
        // Step 1: get the shopname from the user and redirect the user to the
        // shopify authorization page where they can choose to authorize this app
        $shop = isset($_POST['shop']) ? $_POST['shop'] : $_GET['shop'];
        $shopifyClient = new ShopifyClient($shop, "", SHOPIFY_API_KEY, SHOPIFY_SECRET);
        // if(!$shopifyClient->validateSignature($_GET)) die('Error: invalid signature.');
        // redirect to authorize url
        header("Location: " . $shopifyClient->getAuthorizeUrl(SHOPIFY_SCOPE, REDIRECT_URI));
        exit;
    }
}
// first time to the page, show the form below
?>
    <p>Install this app in a shop to get access to its private admin data.</p> 

    <p style="padding-bottom: 1em;">
        <span class="hint">Don&rsquo;t have a shop to install your app in handy? <a href="https://app.shopify.com/services/partners/dev_shops/new">Create a test shop.</a></span>
    </p> 

    <form action="" method="post">
      <label for='shop'><strong>The URL of the Shop</strong> 
        <span class="hint">(enter it exactly like this: myshop.myshopify.com)</span> 
      </label>