Search Results for: app development

Design Shopify Apps WITHOUT Polaris

So you have been developing Shopify apps, but you’re not creating the Shopify apps using React or Node.js. So in other words, you can NOT use Polaris. Now you’re wondering… “How am I going to design this app? and I don’t want to use Bootstrap anyway”.

Well, to be fair though, I’ve been in that very same spot and that’s why I am writing this article to guide you on how to design Shopify apps without using or installing Polaris to your Shopify app projects.

Video Tutorial

If you prefer watching video tutorials, the here is the video version of this article.

Getting Started

To get started, I will assume that you have followed our Shopify app development series and you have your own undesigned Shopify app. However, if you have nothing but installed Shopify app in your development store, then feel free to copy the following code and paste it into your index.php file. That being said, for this article, we will be using PHP.

<?php
require_once( "inc/functions.php" );

$shop_url = $_GET['shop'];
$access_token = "ENTER YOUR SHOPIFY STORE ACCESS TOKEN";

/**
*  Install Shopify App
*/
//header('Location: install.php?shop=' . $shop_url);
//exit();

echo "Hello " . $shop_url . '<br /><br />';

echo "The following table will list down all of your items from your store. You can delete an item using the action column";

$products = shopify_call( $access_token, $shop_url, "/admin/api/2021-01/products.json", array(), 'GET');
$products = json_decode( $products['response'], true );

foreach( $products as $product ) {
	foreach( $product as $key => $value ) {
		$image = '';
		if( count( $value['images'] ) > 0 ) {
			$image = $value['images'][0]['src'];
		}

		echo '<img src="' . $image . '" width="60"><br />';
		echo $value['title'] . '<br />';
	}
}

?>
Code language: PHP (php)

The code above should give us the following output:

Design Shopify Apps without Polaris

If you’re developing Shopify apps and you’re not using React, then obviously, you won’t be able to use Polaris. Luckily, there is a free CSS framework that you can use for designing Shopify apps and it’s called Uptown CSS.

Navigate to their official website and click the Download CSS button. We’re going to import this into our project.

Once you have downloaded the css file, import it to your project. I will put it inside of my css folder like below:

Since we need to import the CSS, we’ll have to create the skeleton for our HTML. Update your index.php to the following:

<?php
require_once( "inc/functions.php" );
$shop_url = $_GET['shop'];
$access_token = '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';
/**
 * Install Shopify App
 */
//header('Location: install.php?shop=' . $shop_url);
//exit();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/uptown.css">
</head>
<body>
    
</body>
</html>
Code language: HTML, XML (xml)

Once you saved your files and open your app, your app should update to something like below:

Awesome! That means we’re making a progress and Uptown CSS is working! Let’s continue and create the container and sections for our Shopify app.

Open your index.php and copy the following code.

<?php
require_once( "inc/functions.php" );
$shop_url = $_GET['shop'];
$access_token = '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';
/**
 * Install Shopify App
 */
//header('Location: install.php?shop=' . $shop_url);
//exit();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WeeklyHow</title>
    <link rel="stylesheet" href="css/uptown.css">
    <style>
        body {
            padding-top: 30px;
        }
    </style>
</head>
<body>
    <main>
        <section>
            <article>
                <div class="column twelve">
                    <?php
                        require_once("header.php");
                    ?>
                </div>
            </article>
        </section>
        <section>
            <article>
            <div class="card has-sections">
                <div class="card-section">
                    <?php
                        require_once("product_table.php");
                    ?>
                </div>
            </div>
                
            </article>
        </section>
        <footer>
            <article class="help">
                <span></span>
                <p>Learn more about <a href="#">this app</a> at <a href="#">WeeklyHow</a> Help Center.</p>
            </article>
        </footer>
    </main>
</body>
</html>
Code language: HTML, XML (xml)

In the code above, we created the basic structure of our app. Now, if you’re wondering what is the basic structure, you may use the following code as a reference:

<main>
  <header>
    ...
  </header>
  <section>
    ...
  </section>
  <footer>
    ...
  </footer>
</main>
Code language: HTML, XML (xml)

As you can see in the code above, it consists of three parts: header, section, and footer.

Now we never really used the header tag in our code so if you wish to add the header tag, feel free to do so. But, personally speaking, I never truly liked how it looks. (shrugs)

Now noticed that we have created two files: header.php and product_table.php.

For the header.php file, this is the code:

<h6><?php echo "Hello " . $shop_url . '<br /><br />'; ?></h6>

<div class="alert warning">
    <dl>
        <dt>Read me</dt>
        <dd><?php echo "The following table will list down all of your items from your store. You can delete an item using the action column <br/><br/>";?></dd>
    </dl>
</div>
Code language: HTML, XML (xml)

And for the product_table.php, here is the code:

<table>
  <thead>
    <tr>
      <th colspan="2">Product</th>
      <th>Status</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
  <?php
    $products = shopify_call( $access_token, $shop_url, "/admin/api/2021-01/products.json", array("limit" => 4), 'GET');
    $products = json_decode( $products['response'], true );

    foreach( $products as $product ) {
        foreach( $product as $key => $value ) {
            $image = '';
            if( count($value['images']) > 0 ) {
                $image = $value['images'][0]['src'];
            }
            ?>
                <tr>
                    <td><a href="#"><img width="35" height="35" alt="" src="<?php echo $image; ?>"></a></td>
                    <td><a href="#"><?php echo $value['title']; ?></a></td>
                    <td><span class="tag green"><?php echo $value['status']; ?></span></td>
                    <td><button class="secondary icon-trash"></button></td>
                </tr>
            <?php
        }
    }
    ?>
  </tbody>
</table>
Code language: HTML, XML (xml)

So in the code above, we only retrieve the products through Product API and loop through each product, and render them using table rows. If you want an in-depth guide on how to get Shopify products using Shopify API, you may click the following button to learn more about it.

By saving all of your files, you should have the following output:

Conclusion

There you have it! You have designed your Shopify app without Polaris.

Now, what I really like about this CSS framework is that it doesn’t need jQuery or other JavaScript framework. It’s a very independent framework and can be easily customize especially if you are familiar with CSS or SASS. So, what do you think? Do you think this is a great CSS framework? Let us know in the comments below.

Shopify Theme Development Masterclass: Learn How To Create Shopify Themes

Due to the pandemic, a lot of people are trying to learn how to create an online store with Shopify. These new merchants are looking for Shopify themes that are effective enough to bring them sales. Why not become one of the new Shopify developers and create an amazing Shopify theme from scratch?

 

In this course, we’re going to learn how to create a Shopify theme using ThemeKit and Liquid. We’re going to cover all of the important parts of Shopify Theme Development so you will be ready to create your very own Shopify theme as soon as possible.

In this course you will learn:

  1. Private apps for theme development
  2. Liquid files
  3. Theme assets
  4. Designing your own theme
  5. Adding events to your theme
  6. Liquid language (Referencing asset files, loops, conditional statements, Shopify objects, filters, and many more)

If you think you’re ready to start, signup now and let’s create the best Shopify theme together!

Why Learn Game Development?

Are you thinking of becoming a Game Developer? or are you just wondering how game development works?
In this article, we’ll be giving you ideas about game development and its importance of learning it.

gamer playing minecraft game

Research suggests that playing video games can improve regions of your brain. Which are responsible for your attention and visuospatial skills- and make them more efficient.

Playing video games also helps reduce stress. Though it depends on what type of video game you are currently playing. Most video games are developed to challenge the players, make them feel frustrated, and keep them go play over and over again. These games are called mostly “strategy games”

But what really is a video game?

A video game is an electronic game that involves interaction with a user interface to generate visual feedback on a two- or three-dimensional video display devices such as a TV screen, Virtual reality headgear, or computer monitor.

Video games have been studied seriously for years and have been experimented with by many developers. If you don’t know, there are hundreds of different video games online and offline that players can enjoy. One of the most popular games nowadays is Minecraft. But there are also games that are popular like Grand Theft Auto, and Call of Duty. These video games are sold worldwide and one of the reasons why is because it is enjoyable and truly addictive.

There are many ways to enjoy a video game, one is to use a desktop gaming computer, two is to use a gaming console, and three is to use a mobile device. Of course, those are not the only apparatus that you can use to enjoy a video game but that being said, video games are created for entertainment and that’s all.

So, you might be wondering now…

How do you make video games?

Games are made simply by coding using a certain programming language. However, in this generation, most games are created using a game engine. A good example of this is Unity and Unreal Engine. These two game engines are two of the most used game engine in the game development industry.

Why should I learn game development?

There are plenty of reasons why you should learn about game development and how to create video games. If you enjoy playing games, chances are, you’re going to enjoy MAKING games too.

By learning how to make games, your knowledge will be extended far beyond what you expected. You will learn many programming languages such as C++, C#, HTML5, and JavaScript. You will also be able to learn Android (if you are into mobile games), iOS, and many more.

You should learn about game development because the gaming industry itself is VERY BIG and there’s no doubt that this will be much bigger in the future. There will be no end to this. In other words, your career will have no dead end. In fact, even if you change your career from game development to a different industry like, animation, web, and design, it wouldn’t be much of an issue because you will know most of it in game development.

Game Development consists of parts:

  • Game Designing – This includes terrain or platform designing, character designing, animations, cutscenes, and many more. So if you try to study game development. You will surely encounter all of this and it’ll benefit you in the future- no doubt.
  • Game Programming – This is obviously going to be part of your game development journey. To be honest, programming a game isn’t that hard anymore. Since most of the game engines to this day provide documentation about their APIs. So if you encounter a problem or forget a keyword, there will be always a helping hand online. Google is your friend here.
  • Music – Whoops, did you just say music? Of course! A game is boring without sound effects. So if you study game development, you will surely understand how music design works.

Last words

Learning how to make games can be hard for some people sometimes, but let me tell you that this will be the most fun experience you will ever have. Not only it is a high-paying career but it also gives you knowledge and security that you can use in the future. So if you are thinking of joining this diverse industry. GO! Do it.

How To Make An Invoice App with Shopify Order API

When you build a Shopify store, it’s very common that you get customers to ask you for the invoices when they make a purchase. As a merchant, it’s your responsibility to provide that invoice.

There are few Shopify apps that provide invoice printing but what if you wish to create your own? In this tutorial, we’ll learn how to make an invoice app that allows you to print invoices using PHP and JavaScript.

Video Tutorial

If you prefer to learn through a video tutorial, you can watch the following video.

Getting Started

Like in most of our Shopify app written tutorials, we’ll assume that you have followed our Shopify app tutorial series and you are using the same repository/client that we are using here.

Now, for this tutorial, we’re just going to need the following two files:

  • index.php
  • orders.php

In our index.php file, we should have the following code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
    <title>WeeklyHow Shopify App</title>
  </head>
  <body class="bg-light">
	<div class="container py-5">
		<?php
		include_once("inc/functions.php");
		include_once("inc/mysql_connect.php");
		include_once("header.php");
		include_once("orders.php");
		?>
	</div>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
  </body>
</html>
Code language: PHP (php)

And for our orders.php file, we should have the following code:

<h4>Orders</h4>

<table class="table table-bordered my-5">
	<thead>
		<tr>
			<th scope="col">Order #</th>
			<th scope="col">Email Address</th>
			<th scope="col">Customer Name</th>
			<th scope="col">Total Sale</th>
		</tr>
	</thead>
	<tbody>
		<?php
			$orders = shopify_call($token, $shop_url, "/admin/api/2020-10/orders.json", array("status" => 'any'), 'GET');
			$orders = json_decode($orders['response'], JSON_PRETTY_PRINT);

			foreach ($orders as $order) {
				?>
					<tr>
					<?php
					foreach ($order as $key => $value) {
						?>
							<th><a href="#" data-toggle="modal" data-target="#printOrder<?php echo $value['order_number']; ?>"><?php echo $value['order_number']; ?></a></th>
							<td><?php echo $value['contact_email']; ?></td>
							<td><?php echo $value['billing_address']['name']; ?></td>
							<td><?php echo $value['total_price'] + $value['currency']; ?></td>
						<?php
					}
					?>
					</tr>
				<?php
			}
		?>
	</tbody>
</table>
Code language: PHP (php)

In the code above, what we just did is to create a very simple table to display the list of orders available from the store using Order API.

Now, notice in line 23 that we have added an anchor tag that uses custom attributes such as data-toggle and data-target. These will be used to open a modal to display the invoice.

For that to happen, we have to make sure that the value of the data-target attribute is unique so we concatenated the order_number.

If we save the scripts and run the app, we should have the following output:

shopify order listing api

And the HTML output should look like this

shopify print order html code

So that means, we need to create a modal with an id of #printOrder1001.

We can create a modal, just by inserting the following code in order.php file

<h4>Orders</h4>

<table class="table table-bordered my-5">
	<thead>
		<tr>
			<th scope="col">Order #</th>
			<th scope="col">Email Address</th>
			<th scope="col">Customer Name</th>
			<th scope="col">Total Sale</th>
		</tr>
	</thead>
	<tbody>
		<?php
			$orders = shopify_call($token, $shop_url, "/admin/api/2020-10/orders.json", array("status" => 'any'), 'GET');
			$orders = json_decode($orders['response'], JSON_PRETTY_PRINT);

			foreach ($orders as $order) {
				?>
					<tr>
					<?php
					foreach ($order as $key => $value) {
						?>
							<th><a href="#" data-toggle="modal" data-target="#printOrder<?php echo $value['order_number']; ?>"><?php echo $value['order_number']; ?></a></th>
							<td><?php echo $value['contact_email']; ?></td>
							<td><?php echo $value['billing_address']['name']; ?></td>
							<td><?php echo $value['total_price'] + $value['currency']; ?></td>

							<div class="modal fade" id="printOrder<?php echo $value['order_number']; ?>" tabindex="-1" aria-labelledby="printOrderLabel" aria-hidden="true">
								<div class="modal-dialog modal-lg" style="max-width: 80% !important;">
									<div class="modal-content">
										<div class="modal-header">
											<h5 class="modal-title" id="printOrderLabel">Print Order #<?php echo $value['order_number']; ?></h5>
											<button type="button" class="close" data-dismiss="modal" aria-label="Close">
											<span aria-hidden="true">&times;</span>
											</button>
										</div>
										<div class="modal-body">
											<div class="card border-0" id="printThisInvoice">
												<div class="card-body">
													<div class="row p-2">
														<div class="col-md-6"><h1>LOGO</h1></div>
														<div class="col-md-6 text-right"><p class="font-weight-bold mb-1">Invoice #00001</p></div>
													</div>
													<hr class="my-3">
													<div class="row p-2">
														<div class="col-md-6">
															<p class="font-weight-bold mb-4">Client Information</p>
								                            <p class="mb-1"><?php echo $value['billing_address']['name']; ?></p>
								                            <p class="mb-1"><?php echo $value['billing_address']['address1']; ?></p>
								                            <p class="mb-1"><?php echo $value['billing_address']['country']; ?></p></div>
														<div class="col-md-6 text-right">
															<p class="font-weight-bold mb-4">Payment Details</p>
								                            <p class="mb-1"><span class="text-muted">Payment Type: </span> <?php echo $value['payment_gateway_names'][0]; ?></p>
								                            <p class="mb-1"><span class="text-muted">Name: </span> <?php echo $value['billing_address']['name']; ?></p>
														</div>
													</div>
													<div class="row p-2">
								                        <div class="col-md-12">
								                        	<div class="row">
								                        		<div class="col-3 border">Item</div>
								                        		<div class="col-3 border">Description</div>
								                        		<div class="col-2 border">Quantity</div>
								                        		<div class="col-2 border">Unit Cost (<?php echo $value['currency']; ?>)</div>
								                        		<div class="col-2 border">Total (<?php echo $value['currency']; ?>)</div>
								                        	</div>
								                        	<?php
								                        		$totalPrice = 0;
									                        	foreach ($value['line_items'] as $index => $item) {
									                        		$totalPrice += $item['price'];
									                        		?>
									                        			<div class="row">
											                        		<div class="col-3 border"><?php echo $item['title']; ?></div>
											                        		<div class="col-3 border"><?php echo $item['name']; ?></div>
											                        		<div class="col-2 border"><?php echo $item['quantity']; ?></div>
											                        		<div class="col-2 border"><?php echo $item['price']; ?></div>
											                        		<div class="col-2 border"><?php echo ($item['price'] * $item['quantity']); ?></div>
											                        	</div>
									                        		<?php
									                        	}

									                        ?>
								                        </div>
								                    </div>
								                    <div class="row p-2">
														<div class="col-md-6">
															<p class="font-weight-bold mb-4">Other information</p>
								                            <p class="mb-1">Note: <?php echo $value['note']; ?></p>
								                        </div>
														<div class="col-md-6 text-right">
															<p class="font-weight-bold mb-4">TOTAL:</p>
								                            <p class="mb-1"><?php echo $totalPrice; ?> <small><?php echo $value['currency']; ?></small></p>
														</div>
													</div>
												</div>
											</div>
										</div>
										<div class="modal-footer">
											<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
											<button type="button" class="btn btn-primary" id="printBtn">Print</button>
										</div>
									</div>
								</div>
							</div>
						<?php
					}
					?>
					</tr>
				<?php
			}
		?>
	</tbody>
</table>
Code language: PHP (php)

So we have three parts for this modal.

First is the header. Second is the content and lastly is the footer.

Let’s take a look at the modal body. Here we added a div tag with a class of card. This div basically forms the template of a very simple invoice. Here we have:

  • The logo
  • The invoice number
  • The client’s information
  • The payment details
  • The list of items that were purchased
  • Other information
  • …and the Total

All of these data can easily be customized and so feel free to change anything here. Just remember that variables and key names of the arrays must follow what’s from the API.

Next is the footer of the modal, here we have to buttons, the cancel button and the print button.

For the print button, we’ll have to create a javascript to make an on click event and execute a task and that is to print the invoice.

Saving the script should give you the following output:

Creating an invoice app in Shopify with example template

Printing the invoice

For us to be able to print the invoice, we’ll have to use a plugin that is called printThis.

printThis is an extensive printing plugin for jQuery that allows for printing specific areas or multiple DOM elements. This is perfect since we only want to print what is inside the modal.

To use this plugin, we’ll be using the following CDN:

https://cdnjs.cloudflare.com/ajax/libs/printThis/1.15.0/printThis.min.jsCode language: JavaScript (javascript)

Let’s open our index.php once again and update its code to the following:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
    <title>WeeklyHow Shopify App</title>
  </head>
  <body class="bg-light">
	<div class="container py-5">
		<?php
		include_once("inc/functions.php");
		include_once("inc/mysql_connect.php");
		include_once("header.php");
		include_once("orders.php");
		?>
	</div>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/printThis/1.15.0/printThis.min.js"></script>
    <script>
      $('#printBtn').on('click', function(e) {
        $('#printThisInvoice').printThis();
      });
    </script>
  </body>
</html>
Code language: HTML, XML (xml)

To use the plugin, all we really need to do is to select a DOM element and use the printThis() function to display the print window.

That’s why if we save our script and run the app, we should have the following output when we click the print button.

Shopify print this invoice example

Isn’t that awesome?! Now you can easily print invoices and send these invoices to your customers through email.

Conclusion

In this lesson, we have learned how to create an invoice app using Shopify Order API, PHP, and a very powerful jQuery plugin. This is just the basic of making an invoice app. You can make this more useful by adding events such as sending the invoice to customer’s email as soon as the invoice is printed or something more! Feel free to experiment with the tools provided in this lesson.

If you have any questions, feel free to tell us in the comments below and we’ll try to answer.

Why You Should Use Hostinger for your Shopify Apps in 2020

Why You Should Use Hostinger for your Shopify Apps in 2020

So you’ve been creating Shopify apps through localhost and you’re thinking of publishing it online so Shopify merchants can install your app to their store.

The issue that you’re having now is which web host provider is the best for your Shopify apps. Well, we’re here to tell you.

One of the best web host providers that you can use for your Shopify apps is Hostinger and part of the reason why is because, unlike other web hosts, Hostinger is allowed to interact with Shopify through XMLHTTPRequest or AJAX. You’re surprised? We are too!

Hostinger free hosting plan for everyone
  • Compatible with Shopify
  • LightSpeed Web Server
  • Free domain and SSL certificate
  • 30-day money-back guarantee

We have tried so many web host providers for our Shopify apps and sadly, most of them failed to take care of our apps!

Of course, there are plenty of reasons why you should pick Hostinger for your Shopify app projects, and today, we’re going to list down all of them.

Why you should use Hostinger for your Shopify apps

If one of your main concerns is your budget, then you’ve come to the right place. Hostinger is one of the cheapest web host services in the market but does that mean it’s bad? no.

Below are some of the features why you should consider using Hostinger for your Shopify app projects.

Compatibility

Not all web hosts can be compatible with Shopify especially if your web host doesn’t have an SSL certificate.

If your website still runs under HTTP, then expect Shopify to deny it.

Luckily, Hostinger offers a FREE SSL certificate so you can always run your Shopify apps without any issue at all.

Well, is that all that makes Hostinger compatible with Shopify for our Shopify app development?

Like what we mentioned earlier, Hostinger allows you to do HTTP requests without being blocked by the CORS policy. Of course, you’ll have to make sure that your header is properly set up.

Ease of use

The Hostinger dashboard is fairly easy to use and if you’re new to web hosting, you’re going to love using Hostinger.

Everything in the Hostinger dashboard is understandable and straightforward. Each page is partnered with a very large logo and categorized to make it easier for you to find what you need.

There’s also a search bar for people that don’t like scrolling down.

Speed

For a very cheap web host, you would expect to have a very slow website. However, that’s not the case with Hostinger.

According to their website, the fastest response time that they can reach is about 45 milliseconds, which is insane! If you’re only using their shared web host, what more if you use their business web host plan?

Unlike other web host providers, Hostinger uses technologies that are up to date. In fact, they always update their technologies so that users can always have a good experience.

If you’re going to use Hostinger for your Shopify apps, it is expectable that your apps will load fast but of course, this will always depend on your codes or files. It is advisable to make your codes optimized as much as possible so that you can take advantage of Hostinger’s speed.

Price

Hostinger web hosting plan update in 2020

If you’re in a tight budget and you want to save as much money as possible, then Hostinger should be your choice.

For only $0.99, you can have a single web host with a free SSL certificate which is a good deal especially if your only plan is to host your Shopify apps.

Though it’s important to remember that the price will depend on the contract you’re getting.

For a 1 month contract, the price will be almost $10 plus the setup fee which will cost you another $5. That’s still cheap compared to other web host providers but quite expensive just for a one month service.

To fully save a lot of money, it’s best if you take their 48 months contract, which will only cost you $47 and no setup fee. That’s FOUR years! and you will only need to pay $47.

Now the question is, which plan should you really take?

Well, of course, if you’re just trying out, we recommend taking the single shared web hosting. Then, just upgrade to the business plan once you get enough installs in the Shopify app store.

Stability

Hostinger uptime daily update

There will be times that your website can go offline but how long can your website stay offline if you use Hostinger?

According to Hostinger, the percentage of your website going offline is around 0.03% which means in one year, your website will barely go offline.

Support

It’s been known that Hostinger provides the best support for their users. However, in 2020, changes started to come up.

In 2019 or even before, Hostinger provides 24/7 support for all of their users but in 2020, Hostinger removed the chatbox in the dashboard and you can only contact them through their email.

Hostinger contact page in 2020


But why?

According to their staff, due to the current situation of the entire world, Hostinger had to remove the chatbox.

We’re assuming that this is a temporary change and once the pandemic is over, their 24/7 support will be back for everyone.

Conclusion

Do we recommend using Hostinger for Shopify apps? Absolutely!

Hostinger is one of the trusted web host providers in the industry, offering a very cheap web hosting solutions for your Shopify app development. If your plan is to save up money, then you should consider using Hostinger.

Hostinger free hosting plan for everyone
  • Compatible with Shopify
  • LightSpeed Web Server
  • Free domain and SSL certificate
  • 30-day money-back guarantee

Disclosure: This article may contain affiliate links, which means we may receive a commission if you click a link and purchase something that we have recommended.

How To Create App Snippets from Shopify Apps to Shopify Stores

Shopify recently introduced that they will be adding a feature where Shopify apps can finally and easily import liquid files to Shopify stores without writing a bunch of long codes.

The feature is called App Snippets.

Note that app snippets are still on beta and is only available for Shopify development stores with a developer preview store enabled and is using the online store design experience.

What is App Snippet?

According to Shopify, App snippets are Liquid code that can be included in other Liquid files.

Now you might be asking…

Isn’t it just the same when you use the Theme API?

Yes, you’re absolutely correct. However, the difference is that when you use App Snippets instead of Theme API, Shopify store owners won’t finally need to remove liquid files in Shopify themes.

It’s a relief not just for the developers but also for the online store owners.

But… You will still have to insert one line of code to render your liquid files in their theme. Yep. But that’s better than writing a long code.

How To Create App Snippets

In this guide, we’ll take a look at how to create app snippets in Shopify using PHP. We’ll also create a liquid file that we’ll render in our development store.

If you’re new to Shopify app development, we suggest reading our complete guide on how to develop Shopify apps using PHP or Laravel.

Let’s start by creating the snippets.

Log in to your Shopify Partners account, go to the apps page, and select your app.

Then select Extensions.

shopify app extensions settings

We need to access the Online Store tab and so if you don’t have it beside the Shopify admin tab, then click the Manage extension areas.

shopify missing online store tab in extensions

In the Manage extension areas, scroll down and look for the Online Store section. On its right, click the Enable extension area.

shopify app enabling extension area for online store

Then, go back to extensions page and you should find the Online Store tab.

shopify app extensions online store

Scroll down and look for App Snippets. Then click Add Snippet.

shopify app snippets

In the Create snippet page, enter a snippet title.

shopify creating app snippets

Notice that it ask us to drop a liquid file.

We’ll have to upload a liquid file and this is the liquid file that the app will be importing to Shopify stores. So for the sake of making this guide as simple as possible, we’ll create a very short liquid file that only displays an HTML.

Creating a Liquid File

Open your text editor and save the following code as snippet_test.liquid

<div>
<h1>This is an example Snippet</h1>
</div>
Code language: HTML, XML (xml)

Once you have created the file, upload the file to the create snippet page.

uploading app snippets in shopify app

Underneath the form, you should see a code snippet that looks like this.

{% render 'shopify://apps/example-app/snippets/example-snippet/<id>' %}
Code language: HTML, XML (xml)

This code is what you will be using to import the file into Shopify stores.

Now, save the snippet.

app snippets example shopify

Using the App Snippet

For us to be able to use this app snippet, we’ll have to create a development store with a Developer preview enabled.

Once again, this feature is still in beta and will not work on online stores.

To create a development store, navigate to your Store pages and click the Add Store button.

creating shopify development store

For store type, select Development store.

Fill out the form and right on the Developer preview section, tick the checkbox to enable the Developer preview. This should give you a dropdown to select Online store design experience.

creating shopify development store with online store design experience

Hit save.

Navigate back to your Store page and log in to your development store with Online store design experience enabled.

shopify development store with online store design experience

Once you’re logged in, install the app (with the snippet applied/enabled) into your development store.

installing example shopify app in development store

Testing the Snippet

There are two ways to test if your snippets are working.

The first one is by using the Theme API.

Obviously, using Theme API is your only way to push your code to Shopify store’s theme files but since snippets are still on beta. You can test your snippet by just going to your theme files.

That’s the second way of testing your snippets. It’s by editing your liquid files and adding the snippet code into your theme.

Let’s try that.

Under the Sales Channels, select Online Store and navigate to your themes page.

accessing themes in shopify

In your Theme library, select the theme that the store is currently using then select Action and click on Edit Code.

editing source codes in shopify

Then, look for the theme.liquid and paste the snippet code right at the top of the script like below, for example:

editing theme liquid code in shopify

If you save the script and check your store, you should be able to see that the snippet is working like below.

shopify app snippet example

Awesome! Now you can start customizing your snippet codes and update it directly with Shopify.

Removing App Snippets on Uninstallation

With app snippets, you don’t really need to worry about the removal of your scripts from Shopify stores. App snippets will do it all for you.

But like we said in the beginning, the snippet code that we added to the theme.liquid, it will stay until the store owner removes it themselves. So it’s better to always add a note/comment that the snippet code came from your app and they should remove it once they uninstall your application.

But hey! App snippets are still on beta so who knows? Maybe Shopify will provide a way to make it happen.

Conclusion

Shopify app development has been there since the very beginning and Shopify always provide updates not just to their API but to the entire software. Now that they’re working on App snippets, Shopify developers will probably start using webhooks and other API less.

Publishing Your Apps To Shopify App Store & Get Approved

You have finally developed your very first Shopify app and you feel like it’s time to submit your application to Shopify for reviewing and publishing. However, there is a problem… You don’t know the right steps before submitting your application.

In this tutorial, we’re gonna be looking at how you can publish your Shopify app easily and guaranteed to be approved by Shopify reviewer.

Getting Started

It’s quite obvious that before you can publish your Shopify app, you firstly need to make sure that your app is 101% ready to be published. The app’s functionality must be working with little to no bugs.

Not only that, but you should also verify that your application is following the app requirements of Shopify If you haven’t read any of those, it’s best to check if your app is compatible in the app store so you won’t be disappointed in the future.

Once you’re sure that your app is compatible with the Shopify app store. The next thing you need to do is to submit it to Shopify and we’re here to teach you how to do it step by step.

But first! Again! Double-check if your app is installing properly in your development store. Otherwise, the Shopify app reviewer will ask you to fix your installation process.

Installation Process of your App

Sadly, this is one of the common mistakes of Shopify developers. If you are not fully aware of this, whenever a merchant installs your app, Shopify will use your scripts to install your application to this merchant’s store.

If you have followed our Shopify app development tutorial, you would have a script something like install.php, and this script is included in the whitelisted redirection URL(s) in the app setup like below.

Shopify App Settings URLs

Unfortunately, this script will never be loaded whenever a merchant installs your app. Instead, it will open the App URL and look for the index.php.

So the trick here is to add a condition in your index file that checks if this merchant’s store exists in your database. If it doesn’t then redirect this merchant to your install.php file.

$store_check = mysqli_query( $conn, "SELECT * FROM shops_table WHERE shop_url='SHOP_URL_OF_THE_MERCHANT' LIMIT 1");
if( mysqli_num_rows( $store_check ) < 1) {
	header("Location: install.php?shop=" . 'SHOP_URL_OF_THE_MERCHANT'); 
	exit();
}Code language: PHP (php)

As you can see in the example above, we used a simple MySQLi query to check our database. Then, we check if this data exists. If it doesn’t then we use the header() function to redirect the merchant to our install.php file with the shop URL of the merchant’s store.

Submitting Your App

Once you feel like you have fixed all your app issues then that’s the moment we can start our app listing. To do this, navigate to your app dashboard and click on the App listings button.

Shopify app listings for app submission review

Then, once you have arrived in the app listings page, you can either use the English listing or create another listing in different language. We suggest before creating a non-english listing, you submit your app in english list first as it will expose your apps into a larger community.

Shopify app listing overview page

As you can see above, the default listing is in English and you are required to complete the listing before you can submit the app.

By selecting the English listing, you should be redirected to the listing form.

App Listing Form

Once you arrived in the app listing form, you will see a very long form that requires you to fill in. We’ll be guiding you step by step on how to properly fill the input boxes below.

shopify app english listing information

Let’s start with the listing information.

Listing information

This part is the most easiest to fill-in. All you need is the name for you Shopify app and the tagline that you want to say about your application.

App name

With app name, you can only input a total of 30 characters so it’s best to pick the perfect name for your app. We recommend picking a name with keywords that are usually used when merchants used the search box. SEO is also applied for your app name so use it wisely.

A perfect example for app name is the Free Shipping Bar by Hextom.

shopify app free shipping bar

If you look closely, the app name contains only three words yet super effective that it always gets to #1 spot of search results.

Here’s how it works:

The word free is used to indicate that this app can be used for free. Then, the word shipping is also used to indicate that this app is for shipping offers, discounts, and more. Then, of course, the word bar indicates that this app is used to display a bar on the top of the store’s page. Super easy to understand the name.

Although, we recommend you experiment with this since you can always customize this even if the app is published.

App icon

Next up is the application icon. This part is surely easy to understand. All you need is to upload a 1200×1200 image with no text at all. Making your own icons should not be that much of an issue. However, if you are lacking knowledge on how to create an image. You can contact us and we’ll work for you to create a perfect image that can surely attract new installs.

Search terms (optional)

Although this is optional, we HIGHLY recommend putting at least five search keywords to boost your exposure in the search results. Like what we mentioned before, SEO is a big part of this process so use this wisely.

App Details

Next up is the application details. This is where you describe what your application is all about. This is where you can tell why your app is better than the other apps. *wink*

Promotional video (optional)

The first one is the promotional video. This one is purely optional. You can add a YouTube link here to describe what your app is all about and what it can provide.

From our experience, adding a promotional video is not that very useful. In fact, it’s just a waste of effort and time as it don’t provide that much increase in installs.

We’d rather put more additional efforts to our images than adding a promotional video.

Key benefits

This will be the section where you describe the best features of your application. This is very useful and very effective for attracting more installs. Although adding photos are optional, we highly recommend adding eye-catching photos that represent each benefit to fully take advantage of this section.

Check the following example:

shopify app key benefits example image

For the image, it’s suggested to use 1600px by 1200px image dimension. You may download the following template for your reference.

Featured app banner (optional)

If you want your application to be featured on the front page of Shopify app store. You must create a well-made banner. This is optional. However, to increase the chance of getting well-known through the entire community, it’s best to create a banner. Who knows? Maybe you’ll get featured and get not only hundreds of new installs but also thousands of new installs.

For banners, it’s suggested to use 1600px by 900px image dimension. You may follow the guidelines on how to create a perfect banner.

Screenshots

This section is one of the most important parts of your app listing. Based on our own research, almost 89% of merchants look at app’s screenshots almost immediately after picking an application. With that being said, it’s important to pick the right screenshots of your application.

Now, you may be asking…

“What are the best screenshots for my Shopify app?”

The answer is very simple.

The first photo that you should be sharing to merchants is the result or the output when they finally installed your app. It should tell them that your app is user-friendly and easy to use. Take these screenshots as the thumbnails of your application. Make them interesting and eye-catchy. Don’t just screenshot your app and paste in the Paint and save it as PNG. Work on it. Add small details that can help merchants understand how your app works.

Always remember, your goal is to help the merchant and make things easier for them. NEVER confuse them.

There are three parts of screenshots. The first one is for desktop, the second one is for mobile, and the last one is for Point of Sale. Both mobile and Point of sale are optional but we highly recommend adding mobile screenshots since most merchants rely on mobile. So make sure your app works perfectly on mobile.

For images, the dimensions are the following:

  • Desktop: 1600px by 900px
  • Mobile: 900px by 1600px
  • Point of sale: 2048px by 1536px

The templates are also included in the file that you have downloaded earlier. Feel free to use them.

Detailed description

The detailed description section is where you provide almost everything about your application. For most application, they start their description by adding an introduction telling what the application is all about and what it can do. Then, after the introduction, provide and explain thoroughly each of your app’s key features.

The title description field allows you to use a markdown format. In other words, you can create a header/title, an ordered list, and a non-ordered list. Use this to make your description look neat and easy to read.

Never never never just create a block of long text full of paragraphs. Merchants have no time reading a letter!

Demo URL (optional)

Although this is optional, adding a demo URL can prove that your app is perfectly working especially if your app is customizing the merchant’s storefront. Otherwise, paste a URL leading to a demo page or maybe a YouTube video URL that demonstrates how the app works? That should be fine too.

Integration (optional)

If your application works with other application or devices, you can list them here.

Pricing

shopify app pricing free to install image example

This section is all about the pricing of your application.

There are three types of pricing: Free, Recurring Charge, and One-Time Charge.

If your app doesn’t charge the merchants, then you can just leave the radio-button set to Free. Otherwise, set it to either Recurring Charge or One-Time Charge. Just make sure your app is using Charge API. Although there are also a way to provide both a free plan and a paid plan to your merchants. You can do that simply with Charge API.

If you want to charge your merchants and you haven’t implemented the Charge API to your application, we highly recommend following our guidelines on how to create a recurring charge API.

Contact Information

The contact information section is one of the most important part of your app listing. This is where you provide contact numbers, email addresses, and URL addresses to help the merchants contact you in case there is an issue within your application.

Review notification email

You may enter any of your email addresses here. This email address will be receiving notifications whenever there is a review on your application.

App submission contact email

You may enter any of your business/personal email addresses here. The email address you provide will be receiving updates about the app you submitted for review. Make sure to always check this email address especially after you submit your app for review.

Sales and support

shopify app support section listing app

All of the information you provide in the sales and support will be displayed in the app listing page and will be used by merchants to contact you. So make sure you use business related email addresses and phone numbers. Be prepared because you will get contacted a lot by merchants especially if you have plenty of installs.

Tracking (optional)

If you want to track your application then feel free to add Google analytics ID and more. It don’t really matter since Shopify has its own analytics page.

Install requirements (optional)

This part is very useful especially if you want to lessen the amount of uninstalls of your app. If your app requires certain settings then you can adjust it here in this section.

App review instructions

shopify app review instructions for listing

And finally, last but not the least. The app review instructions is the part where you explain to the Shopify app reviewer how to use your application and what it should be doing. It’s important to explain everything in detail and it should be step by step.

For example, start from installations, to settings, and end to output.

Review Duration

Once you have finally submitted your app to Shopify, an employee from Shopify will start reviewing your app and this process usually takes around 2-3 days depending on how complex your application is.

You shouldn’t be scared of this process. We agree that this part takes time but if your application is working perfectly then no doubt your app will get published as soon as possible.

However, if you get a response saying that you need to fix something then that’s also good! That means you avoided getting a negative review from merchants.

Conclusion

Developing Shopify apps can be a tedious task but submitting your app to Shopify is much harder especially if your app is not meant to be submitted yet. So we suggest before submitting your app, check it thoroughly and make sure there’s no flaw at all.

If your app get rejected, don’t worry, you have a full month to respond to the reviewer for rechecking the application.

JavaScript / HTML5 Game Development – How To Create Games

If you are a gamer (like most people), you probably thought of making your own video game or at least wonder how video games are developed.

Video games are made to entertain people, like you and me.

To be able to create a video game, you must understand first the purpose of your development and how knowledgeable you are when it comes to programming.

Of course, game development is not for everyone. If you are a programmer and you only develop software, sometimes you will feel like you are out of your zone.

person using laptop computers

Game development offers a TON of work and responsibilities. To be able to create an amazing game, you would need to understand how to design a game, how to program the game, how to write music and etc. These things form the actual game. Without one of these (let’s say music), the game would feel… empty… or… boring.

As a game developer, it is your responsibility to entertain gamers. To make them feel emotions that you want them to feel.

In this article, we’ll be guiding you on how to develop a video game using JavaScript and HTML5. If you don’t have any knowledge about vanilla JavaScript and HTML5, then this course is perfect for you as we’ll explain to you every part of game development that you need to know.

Although if you’re already a game developer yourself, then, you have the advantage to understand what’s going on.

But first…

What is a video game?

A video game is a digital game designed mainly for personal computers. Although there are other electronic machines like game consoles designed for playing games.

Video games are created in different ways. Some games are developed using game engines like Unity or Unreal. Some games are created using a plain code like Python or C++.

boy playing donkey kong arcade box

Choosing a way of developing games completely depends on your knowledge of programming languages. If you know how to code in C#, then Unity may be the best option for you. If you know C++ then Unreal engine is the one that could help you.

Understanding your knowledge about programming is your starting point to becoming a game developer. Of course, everyone’s different. You may find it easy to understand game development or you may find it not.

My tip for you is to find your comfort zone as it will lead you to your success. Otherwise, you will end up just giving up.

Introduction to Game Development

In every game development, you will find it very common to see a game loop and no we’re not talking about the game over and replay. We’re talking about the frames that loop back and forth inside your game.

This loop is very important due to its ability to check what is going on inside the game frame. Whether it is a keypress event or a mouse event, the game loop will always detect it.

Another thing to remember before starting game development is that…
Mathematics is very important. You will always be doing computations and stuff just to be able to go from one point to another.

Anyway…

For this course, we’ll be doing a very simple game. A single game to be precise. We’ll be developing a classic ping-pong game using vanilla JavaScript and HTML5.

For this, you will only need a text editor like Notepad++ or Sublime.

How to develop a pong game with JavaScript & HTML5

To start developing a single-player pong game using vanilla javascript and HTML5, open your text editor and copy the following code.

Keep in mind that it is best to always create a new folder for every time you create a new project. That way your files will be organized and easier to be accessed.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>Single Player Pong Game</title>
		<style>
			body {
				padding: 0;
				margin: 0;
			}

			canvas {
				background-color: #eee;
				display: block;
				margin: 0 auto;
			}
		</style>
	</head>
	<body>
		<canvas id="game_canvas" width="640" height="480"></canvas>
		<script>
			var canvas = document.getElementById("game_canvas");
			var context = canvas.getContext("2d");

			function drawCanvas() {
				requestAnimationFrame(drawCanvas);
			}

			requestAnimationFrame(drawCanvas);
		</script>
	</body>
</html>Code language: HTML, XML (xml)

With the code above, you will see that a canvas is created.

Creating a canvas using javascript

But there’s nothing in the canvas yet!

Drawing the ball

Well, to be able to add objects inside the canvas, you will need to use the context variable to draw a path or an object.

To do that, add the following code inside your script tag.

var x = canvas.width / 2;
var y = canvas.height - 30;

var radius = 15;

function drawPlayer() {
	context.beginPath();
	context.arc( x, y, radius, 0, Math.PI * 2 );
	context.fillStyle = "red";
	context.fill();
	context.closePath();
}Code language: JavaScript (javascript)

Next, inside the drawCanvas() function, call the drawPlayer() function.

function drawCanvas() {
	drawPlayer();
	requestAnimationFrame(drawCanvas);
}Code language: JavaScript (javascript)

Refresh the page and you should see the object inside the canvas.

creating a ball using context 2d in html5 canvas using javascript

Awesome! Now let’s make the ball move around the canvas.

Making the ball move around

To do that, we will need to declare a set variable so just below the var radius = 15; add the following code.

var distanceX = 2;
var distanceY = -2;Code language: JavaScript (javascript)

Next, inside the drawCanvas() function and just below the call of drawPlayer() function, add the following code.

x += distanceX;
y += distanceY;

Save your code and you should have the following output.

Now there’s the issue, why is the canvas drawing a line instead of moving the circle? Well, technically the ball is moving but the problem is that the ball gets redrawn inside the canvas and over the previous balls.

To fix this, we’ll need to clear the canvas every time a new frame arrives.

So, once again, inside the drawCanvas() function and just above the drawPlayer() function, add the following line of code.

context.clearRect( 0, 0, canvas.width, canvas.height );Code language: CSS (css)

That should give you the following output.

Fixing the issue of the ball going through the canvas

The next thing that we’re going to do is to make sure that the ball won’t go through the canvas.

To do this, we’re gonna need to learn about collisions. We’ll need to check if the ball’s position is near the edge of the canvas. If it is, we’ll bounce it off the edge and so on and so forth.

Inside the drawCanvas() function and just above the x+= distanceX;, copy the following code.

if( x + distanceX > canvas.width - radius || x + distanceX < radius ) {
	distanceX = -distanceX;
}

if( y + distanceY < radius ) {
	distanceY = -distanceY;
}

Save your code and you should be able to see that the ball bounces off as soon as it touches the edge of the canvas.

Next, let’s create a paddle for the player to control.

Creating the player paddle

To do that, we’re going to do the same process that we did for the ball. We’re going to create a new function and we’ll call it drawPaddle().

var paddleHeight = 12;
var paddleWidth = 60;
var paddleX = ( canvas.width - paddleWidth ) / 2;

function drawPaddle() {
	context.beginPath();
	context.rect( paddleX, canvas.height - paddleHeight, paddleWidth, paddleHeight );
	context.fillStyle = "brown";
	context.fill();
	context.closePath();
}Code language: JavaScript (javascript)

And then, make sure that you call this new function inside the drawCanvas() function.

Just below the call of drawPlayer() function.

drawPaddle();

Save your code and you should have the following output.

creating paddle object for pong game using javascript and html5 canvas

The next thing that we’re going to do is to make this paddle movable horizontally with key presses.

Making the paddle move on keypress event

As soon as the player holds the left key, the paddle should slowly or quickly move to left and as soon as the player holds the right key, the paddle should move to the right.

To do that, we’ll need to declare a couple of key handlers.

So go back to your script and copy the following lines of code.

var paddleDistanceX = 8;

var isRightKeyPressed = false;
var isLeftKeyPressed = false;

function keyDownHandler(event) {
	if( event.keyCode == 37 ) {
		isLeftKeyPressed = true;
	}

	if( event.keyCode == 39 ) {
		isRightKeyPressed = true;
	}
}

function keyUpHandler(event) {
	if( event.keyCode == 37 ) {
		isLeftKeyPressed = false;
	}

	if( event.keyCode == 39 ) {
		isRightKeyPressed = false;
	}
}

document.addEventListener('keydown', keyDownHandler, false);
document.addEventListener('keyup', keyUpHandler, false);Code language: JavaScript (javascript)

In the code above, we only added an event listener to check whether the player is pressing the keycode 37 or 39.

If the keycode that is being pressed down is 37, then we make the value of the isLeftKeyPressed variable to true. The same goes to the other variable.

Right, so the next thing we need to do is to use these events to move our paddle horizontally whenever the player presses an arrow key.

To do that, copy the following code inside the drawCanvas() function and just above the x += distanceX;.

if( isLeftKeyPressed ) {
	paddleX -= paddleDistanceX;
} else if( isRightKeyPressed ) {
	paddleX += paddleDistanceX;
}Code language: JavaScript (javascript)

With your code being saved, you should be able to move your paddle like the output below.

With that, you should also be able to see that there’s an issue with the paddle and the ball.

The paddle can currently go through the canvas, and the ball can go through the paddle.

So to fix those issues, we’ll update the if statements that we just added before and we’ll add another if statement to check if the ball hits the paddle.

if( isLeftKeyPressed && paddleX > 0 ) {
	paddleX -= paddleDistanceX;
} else if( isRightKeyPressed && ( paddleX + paddleWidth ) < canvas.width ) {
	paddleX += paddleDistanceX;
}

if ( y + distanceY < radius || ( y + distanceY > canvas.height - paddleHeight - radius && x + distanceX > paddleX && x + distanceX < paddleX + paddleWidth )) {
	distanceY = -distanceY;
}Code language: JavaScript (javascript)

With your code being saved, you should have the following output.

Cool! Now everything seems to be working.

Now let’s add something to our code to check if it falls through the canvas. If it did, then we’ll restart the game. Let’s just make it simple.

Add the following code inside the drawCanvas(), just underneath the if statements that we just added earlier.

if( y + distanceY > canvas.height ) {
	location.reload();
}

Save your script and you should see the game restarts as soon as the ball touches the bottom corner of the canvas.

Building the brick field

After all the lines of codes we just made above, we have finally developed the most part of the game. We already have a game over function, keypress event handlers, and the ball.

The next thing that we’re going to do is to actually build the bricks for our player to destroy using the ball.

To do this, we’ll be creating another set of variables and a looping statement so we won’t manually put the bricks on the canvas one by one.

We’ll also create a new function for drawing the bricks, the same as how we draw the ball and the paddle. You may already see the pattern we do here.

Alright, so just below the variables in our code, copy the following.

var brickRowCount = 3;
var brickColumnCount = 9;
var brickWidth = 55;
var brickHeight = 16;
var brickPadding = 10;
var brickOffsetTop = 25;
var brickOffsetLeft = 25;

var bricks = [];

for( var c = 0; c < brickColumnCount; c++ ) {
    bricks[c] = [];

    for( var r = 0; r < brickRowCount; r++ ) {
        bricks[c][r] = { x: 0, y: 0 };
    }
}

function drawBricks() {
    for( var c = 0; c < brickColumnCount; c++ ) {
        for( var r = 0; r < brickRowCount; r++ ) {
        	var brickX = ( c * ( brickWidth + brickPadding ) ) + brickOffsetLeft;
			var brickY = ( r * ( brickHeight + brickPadding) ) + brickOffsetTop;

            bricks[c][r].x = brickX;
            bricks[c][r].y = brickY;

            context.beginPath();
            context.rect(brickX, brickY, brickWidth, brickHeight);
            context.fillStyle = "gray";
            context.fill();
            context.closePath();
        }
    }
}Code language: JavaScript (javascript)

Next, inside the drawCanvas() function and just below the call of drawPaddle() function, copy the following code.

drawBricks();

Save your code, and you should see the same following output.

creating brick array for pong game using vanilla javascript and html5 canvas

Great! Now let’s work on how we can destroy these bricks with collisions.

Breaking the bricks!

We finally have the bricks being displayed on the canvas, but the ball is still not interacting with it as it goes through them.

What we need to do is to apply the same method that we did to our paddle but the difference is we need to destroy the bricks if the ball hits them.

To start, let’s create a new function where we calculate the collision that is happening within our game. We’ll be using the same looping statement that we did before as we are using a two-dimensional array for our brick objects.

function collisionDetection() {
    for( var c = 0; c < brickColumnCount; c++ ) {
        for( var r = 0; r < brickRowCount; r++ ) {
            var b = bricks[c][r];
            if( x > b.x && x < b.x + brickWidth && y > b.y && y < b.y + brickHeight ) {
                distanceY = -distanceY;
            }
        }
    }
}Code language: JavaScript (javascript)

Next, we’ll have to add a new property to each of our brick object. This property will tell if the current brick is destroyed or not.

We’ll call this property status.

If the status property is set to 0, then the brick should be destroyed.

If the status is set to 1, then the brick should still be on the canvas.

Find the following line of code:

bricks[c][r] = { x: 0, y: 0 };

And change it to:

bricks[c][r] = { x: 0, y: 0, status: 1 };

Next, we need to check the status of each brick. So for the drawBricks() function, update the following code from.

function drawBricks() {
    for( var c = 0; c < brickColumnCount; c++ ) {
        for( var r = 0; r < brickRowCount; r++ ) {
        	var brickX = ( c * ( brickWidth + brickPadding ) ) + brickOffsetLeft;
			var brickY = ( r * ( brickHeight + brickPadding) ) + brickOffsetTop;

            bricks[c][r].x = brickX;
            bricks[c][r].y = brickY;

            context.beginPath();
            context.rect(brickX, brickY, brickWidth, brickHeight);
            context.fillStyle = "gray";
            context.fill();
            context.closePath();
        }
    }
}Code language: JavaScript (javascript)

to…

function drawBricks() {
    for( var c = 0; c < brickColumnCount; c++ ) {
        for( var r = 0; r < brickRowCount; r++ ) {
        	if(bricks[c][r].status == 1) {
	        	var brickX = ( c * ( brickWidth + brickPadding ) ) + brickOffsetLeft;
				var brickY = ( r * ( brickHeight + brickPadding) ) + brickOffsetTop;

	            bricks[c][r].x = brickX;
	            bricks[c][r].y = brickY;

	            context.beginPath();
	            context.rect(brickX, brickY, brickWidth, brickHeight);
	            context.fillStyle = "gray";
	            context.fill();
	            context.closePath();
	        }
        }
    }
}Code language: JavaScript (javascript)

Now, the next thing we need to do is to add the brick status property in the collisionDetection() function.

If the brick is not destroyed, we will check whether the collision is happening or not.

If there’s a collision, we’ll set the status of the brick to 0 so it won’t be drawn inside the canvas.

To do that, we’ll have to update our collisionDetection() function to the following.

function collisionDetection() {
    for( var c = 0; c < brickColumnCount; c++ ) {
        for( var r = 0; r < brickRowCount; r++ ) {
            var b = bricks[c][r];
            if(b.status == 1) {
	            if( x > b.x && x < b.x + brickWidth && y > b.y && y < b.y + brickHeight ) {
	                distanceY = -distanceY;
	                b.status = 0;
	            }
	        }
        }
    }
}Code language: JavaScript (javascript)

The last thing we need to do is to activate our collision detection function.

To do that, add the following line of code to the drawCanvas() function, just below the drawPaddle() function.

collisionDetection();

Save your script, and you should have the following output.

Next steps

Congratulations! Now you have successfully developed your simple yet fun single pong game. You can finally move the paddle and make the ball bounce around the canvas and destroy the bricks.

If you want, you can adjust the variables and see what changes it does to the game.

Yes, the game is not totally finished as you still need a game scoring system, a sound, and a user interface.

The main purpose of this course is to introduce you to the idea of how to develop a game using vanilla javascript and HTML5.

If you have suggestions or questions, don’t hesitate to comment down below and we’ll do our best to help out.

How To Implement Recurring Application Charge API To Shopify Apps

Did you know that you can earn money when you develop Shopify apps? Yes, you can!

When you create Shopify apps, you’re obviously allowed to either charge your users only for one-time or monthly. You can even not charge them at all.

You can do this by implementing Billing API which is divided into four different API resources:

  • RecurringApplicationCharge
  • ApplicationCharge
  • UsageCharge
  • ApplicationCredit

In this article, we’ll be focusing more on implementing monthly charges to users who use your Shopify apps which of course we’re talking about RecurringApplicationCharge.

But…

before we go deeper into that topic. Let’s understand first…

What is Billing API?

Billing API is an API used by Shopify apps for collecting a one-time charge, a fixed monthly fee, or a monthly fee based on the usage of the users.

Like what we have mentioned before, Billing API is divided into four API resources:

  • RecurringApplicationCharge which is used for charging users every 30-days;
  • ApplicationCharge used especially by apps that provide free-trial then charge a one-time payment after the trial ended;
  • UsageCharge used for charging users depending on their usage, and
  • ApplicationCredit is used for future purchases inside the app hence the name ApplicationCredit.

There are several reasons why you should use Billing API for charging your users.

  • The payment appears directly on the merchant’s Shopify invoice. They don’t have to enter their credit card details to pay for the apps.
  • Higher conversion rates because payments come directly from Shopify.
  • Tax is 100% correct and charged automatically
  • Lastly, Shopify handles all the chargebacks.

How it works?

When you implement Billing API to you Shopify apps, the API usually process in the following flow:

01


Triggers the Billing charge

This can be done by the merchant either by installing the app or by clicking on a button.

02


The app creates the charge

The app will create the Billing which can be either one-time charge or recurring charge.

03


Shopify verifies the charge

Shopify will verify the charge created by the app and once verified, Shopify will redirect the merchant to the confirmation_url

04


Merchant confirms the charge

If the merchant confirms the charge, he/she will be redirected to the return_url  specified in the API. Otherwise, notify that the charge was declined.

We have a Shopify App Development Course! Be one of the first students!

Are you looking for an in-depth guide on how to create Shopify apps? Click the enroll button to get started!

Implement Recurring Billing API

Creating a charge using the RecurringApplicationCharge resource is very easy and it takes just a couple of lines of codes to be able to create a charge.

If you have been following our Shopify app development tutorial series, you have the advantage of learning this course much easier because we’ll be using the very same method as before.

Read moreHow to build Shopify apps in 10 minutes

Creating Recurring Application Charge

In this course, we’ll assume again that you have followed our Shopify app development course and you’re using the very same files like ours.

To start, open your index.php file and add the following HTML code.

<hr>
<strong>Aha!</strong>
<p>You're still using our free trial. Click the upgrade button below to have access to more awesome features!</p>
<a href="upgrade.php?<?php echo $_SERVER['QUERY_STRING']; ?>" target="_blank">Upgrade</a>
Code language: HTML, XML (xml)

To help you catch up. This is our full index.php file. Feel free to copy it. Just make sure to replace the value of $token and $shop variable.

<?php
require_once("inc/functions.php");

$requests = $_GET;
$hmac = $_GET['hmac'];
$serializeArray = serialize($requests);
$requests = array_diff_key($requests, array( 'hmac' => '' ));
ksort($requests);

$token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$shop = "weeklyhow";	//change this to your store subdomain.
			//for example:
			//test-store.myshopify.com
			//your $shop variable is:
			//test-store

?>

<!DOCTYPE html>
<html>
<head>
	<title>Shopify Example App</title>
</head>
<body>
	<h1>Shopify App Example by WeeklyHow</h1>
	<hr>
	<strong>Aha!</strong>
	<p>You're still using our free trial. Click the upgrade button below to have access to more awesome features!</p>
	<a href="upgrade.php?<?php echo $_SERVER['QUERY_STRING']; ?>" target="_blank">Upgrade</a>
</body>
</html>
Code language: PHP (php)

Next, we’re going to create a new file.

Name it upgrade.php

We’ll do the very same thing here:

  • Require the functions.php
  • Get the $_GET variable
  • Get the hmac
  • Declare $token and $shop variables.

Your upgrade.php file should also look like this:

<?php
require_once("inc/functions.php");

$requests = $_GET;
$hmac = $_GET['hmac'];
$serializeArray = serialize($requests);
$requests = array_diff_key($requests, array( 'hmac' => '' ));
ksort($requests);

$token = "xxxxxxxxxxxxxxxxxxxxx";
$shop = "weeklyhow";

?>
Code language: PHP (php)

Next, we’re finally going to create the Billing API object. To do that, we’ll use the following code.

$array = array(
	'recurring_application_charge' => array(
		'name' => 'Example Plan',
		'test' => true,  //remove this line before sending to app store
		'price' => 15.0,
		'return_url' => 'https://weeklyhow.myshopify.com/admin/apps/exampleapp-14/?' . $_SERVER['QUERY_STRING']
	)
);

$charge = shopify_call($token, $shop, "/admin/api/2019-10/recurring_application_charges.json", $array, 'POST');
$charge = json_decode($charge['response'], JSON_PRETTY_PRINT);
Code language: PHP (php)

Make sure to copy the code above and write it below the $shop variable.

Next, once the code above is processed successfully, our $charge variable will give us a confirmation URL that we can use to redirect our users to the payment confirmation page.

To do that, we can use the following code:

header('Location: ' . $charge['recurring_application_charge']['confirmation_url'] );
exit();
Code language: PHP (php)

And that’s it! We can now save the scripts and see the results.

Shopify App example by weeklyhow

There’s our result! Now, if we click the upgrade link, we should be redirected to the payment confirmation page like below:

Billing API recurring application charge tutorial

If in case you received an error like below, that means you’re using a development store or your billing API is not on test mode.

Billing API application charge upgrade your account error

To successfully create a charge. Make sure you test the app with your upgraded Shopify store.

Activating the charge

If the merchant accepts the confirmation and paid your app for the monthly subscription, you need to activate the charge so the merchant can enjoy all the benefits awaiting for the merchant.

To do that, we’re going to modify our index.php once again and add the following code. Just below the $shop variable.

if( isset($_GET['charge_id']) && $_GET['charge_id'] != '' ) {
	$charge_id = $_GET['charge_id'];

	$array = array(
		'recurring_application_charge' => array(
			"id" => $charge_id,
		    "name" => "Example Plan",
		    "api_client_id" => rand(1000000, 9999999),
		    "price" => "1.00",
		    "status" => "accepted",
		    "return_url" => "https://weeklyhow.myshopfy.com/admin/apps/exampleapp-14",
		    "billing_on" => null,
		    "test" => true,
		    "activated_on" => null,
		    "trial_ends_on" => null,
		    "cancelled_on" => null,
		    "trial_days" => 0,
		    "decorated_return_url" => "https://weeklyhow.myshopfy.com/admin/apps/exampleapp-14/?charge_id=" . $charge_id
		)
	);

	$activate = shopify_call($token, $shop, "/admin/api/2019-10/recurring_application_charges/".$charge_id."/activate.json", $array, 'POST');
	$activate = json_decode($activate['response'], JSON_PRETTY_PRINT);

	print_r($activate);
	
}
Code language: PHP (php)

The code above will simply check if the Billing API has successfully provided a charge_id. If so, then we create an array of data to pass onto the next API call which will activate the charge.

Make sure you replace the value of the return_url with your development store URL or if you are using a database, just retrieve the merchant’s store URL.

By saving and running your Shopify app, you should see the following.

Billing API recurring application charge tutorial
Recurring Application Charge API for Shopify Billing API tutorial PHP

Not only that, but you will also receive an email that says your charge is approved which is awesome!

Test charge email for Shopify recurring charge API tutorial PHP

Conclusion

Congratulation! Now you can earn money with your Shopify app. But wait a minute, what’s the next step? After activating their subscription, how can I give the merchants the benefits of paying for the app?

The answer is very simple. Just verify if the merchant’s subscription is currently active. If it is, then the app should provide more features. Otherwise, give only the features that are only available for non-paying merchants.

Database is your friend here.

Using database, you can store their subscription’s status and there you can check if the merchant’s subscription is active or not.

We have written an article that can help you integrate your Shopify app with MySQL database.

How to Display HTML in Shopify Store with Shopify App (Script Tag)

We have a Shopify App Development Course! Be one of the first students!

Are you looking for an in-depth guide on how to create Shopify apps? Click the enroll button to get started!

If you’re a Shopify Developer, you might not know that one of the most powerful features of Shopify is the script tag API. It’s an API that allows Shopify apps to import javascript files to give more custom features for Shopify stores.

For example, you’re planning on creating a Shopify app that displays a coupon code. Some themes don’t provide that feature but you can do that by adding a script tag with a source URL coming from your server and that script has a callback function that communicates with your Shopify app to get the coupon codes from the store’s database.

Sounds too complicated? Don’t worry, we’ll explain this further so keep on reading.

Getting started

Whatever you’re trying to build, the script tag API will give you a way to add your javascript to your customers’ Shopify stores without making them import your script files manually.

In this tutorial, we’ll learn everything you need to know to be able to build a Shopify app that displays an HTML code in the storefront. We’ll also cover all the things that you can do to control your customer’s front store using pure JavaScript and HTML/CSS.

Also, we’re going to assume that you already have your Shopify app created using PHP and Shopify Repository by Nyalex so if you don’t have a Shopify app yet, we recommend you to learn how to create a Shopify app from scratch.

What is Script Tag?

Just like any other Shopify API, script tag is an API object that you can create, update, and delete on the Shopify store. It might seem a little confusing especially if you’re familiar with the other type of script tag which is enclosed with angle brackets (also known as <script>).

So to clear things up, script tag in Shopify is an API object and script tag in HTML is a code for sourcing a javascript file.

If you have questions, don’t hesitate to ask it out in the comments below and we’ll answer that as soon as we can.

Alright, so let’s proceed.

The first thing we need to do obviously is to create a script tag using Shopify API. However, there are two things that you need to do first before you can successfully create a script tag.

  • Ask a permanent access token with write_script_tags scope / permission
  • Create a javascript file for sending to Script Tag API

Video Tutorial

If you prefer to watch video tutorials, you may click this video

How to use Script Tags

The following are the step by step guide on how to use script tags in Shopify.

Installing Script Tag

Now, let’s assume we have the following install.php script.

<?php
// Set variables for our request
$shop = $_GET['shop'];

$api_key = "ASSIGN YOUR API KEY HERE";
$scopes = "read_orders,write_products";
$redirect_uri = "http://YOUR-DOMAIN-NAME.COM/generate_token.php";

// Build install/approval URL to redirect to
$install_url = "https://" . $shop . "/admin/oauth/authorize?client_id=" . $api_key . "&scope=" . $scopes . "&redirect_uri=" . urlencode($redirect_uri);

// Redirect
header("Location: " . $install_url);
die();
Code language: PHP (php)

The PHP script above is a basic example of installing Shopify app to your customers.



As you can see, we have the $_GET variable for Shopify store URL and the API key which you can retrieve from your Shopify Partner dashboard under the app credentials.

Where To Get the Shopify App Credentials - Shopify Partner Dashboard

Now, we have the $scopes variable.

This variable contains a string which is required for asking very specific permissions to Shopify stores. For example, you want to create a Shopify app that will retrieve all the products. Then you may use the read_products scope.

To be able to add scripts to your customer’s store, you need to use the scope write_script_tags.

In your install.php file, update the scope variable to:

$scopes = "read_orders,write_products,write_script_tags";
Code language: PHP (php)

Keep in mind that there must be NO spaces in the string.

List of Shopify API Access Scopes

To successfully access the Shopify API, you are required to ask your customers for permission to allow you to access their resources. You may use the following authenticated access scopes for that.

read_content
write_content
Used for accessing blog posts, comments, pages, and redirect
read_themes
write_themes
Used for accessing themes and assets
read_products
write_products
Used for accessing products and collections
read_product_listingsUsed for accessing product listings and collection listings
read_customers
write_customers
Used for accessing customers’ data
read_orders
write_orders
Used for accessing orders, fulfillments, and other transactions
read_all_orders Used for accessing all orders instead of the default window of 60 days worth of orders. (If you are going to use this scope, make sure you used this with read_orders, or write_orders scopes. You also need to write a request to Shopify before adding this scope to your app.)
read_draft_orders
write_draft_orders
Used to access draft orders
read_inventory
write_inventory
Used to access inventory
read_locationsUsed to access locations
read_script_tags
write_script_tags
Used to access script tags
read_fulfillments
write_fulfillments
Used to access fullfillment services
read_shipping
write_shipping
Used to access to carrier services, country, and province
read_analytics Used to access Analytics API
read_users
write_users
Used to access users (Available for Shopify Plus only)
read_checkouts
write_checkouts
Used to access checkouts API
read_reports
write_reports
Used to access Reports API
read_price_rules
write_price_rules
Used to access Price Rules
read_discounts
write_discounts
Used to access GraphQL Admin API – Discounts features
read_marketing_events
write_marketing_events
Used to access Marketing Event
read_resource_feedbacks
write_resource_feedbacks
Used to access Resource Feedback
read_shopify_payments_payouts Used to access the Shopify Payments Payout, Balance, and Transaction resources
read_shopify_payments_disputes Used to access the Shopify Payments Dispute resources.

Installing Shopify App

Assuming you followed our Shopify app development tutorial. You can install your Shopify app into your store using the following URL:

https://your-shopify-app-website/install.php?shop=your-shopify-store.myshopify.com
Code language: JavaScript (javascript)

Keep in mind that your-shopify-app-website is your host where your Shopify app source files are uploaded in. And your-shopify-store.myshopify.com is your shopify store URL.

After loading that URL, you should see the following:

Installing Shopify App with Script Tag Access Scope

Notice that there is Manage your Online Store.

Once your customers installed your app, your app will have access to your customers’ storefront and that’s where the magic happens.

Creating JavaScript for Script Tag API

Now that your Shopify app is installed to your store. You can start using Shopify API to import your script to your customer’s storefront.

But how?

Before we proceed to add the javascript to our store. Let’s create the file first.

Open your preferred text editor and create a javascript file called shopify.js.

jQuery(document).ready(function() {
	console.log('Thanks for reading WeeklyHow\'s Tutorials!');
});
Code language: JavaScript (javascript)

Assuming you have uploaded this script into your host scripts folder. You can access this file through:

https://your-shopify-app-website/scripts/shopify.js
Code language: JavaScript (javascript)

Creating Script Tag API Object

Now that we have installed our app to our store and created a sample javascript. Let’s import this script using script tag API.

To do this, we’re going to use the shopify_call() method which is included in the function.php file.

Here’s how your index.php file should look like.

<?php
require_once("inc/functions.php");

$params = $_GET; 
$hmac = $_GET['hmac'];
$serializeArray = serialize($params);
$params = array_diff_key($params, array('hmac' => ''));
ksort($params);

$parsedUrl = parse_url('https://'.$params['shop']);
$host = explode('.', $parsedUrl['host']);
$subdomain = $host[0];

$shop = $subdomain;
$token = "PUT YOUR STORE GENERATED ACCESS TOKEN HERE";


$array = array(
	'script_tag' => array(
		'event' => 'onload', 
		'src' => 'https://your-shopify-app-website/scripts/shopify.js'
	)
);

$scriptTag = shopify_call($token, $shop, "/admin/api/2019-07/script_tags.json", $array, 'POST');
$scriptTag = json_decode($scriptTag['response'], JSON_PRETTY_PRINT);


?>
Code language: PHP (php)

Before you test your app, make sure you have replaced the value of the variable $token. Keep in mind that each store have its own unique access token so make sure you get the access token which is generated by your generate_token.php. You can also store the access token to the database so it’ll be much easier for you to retrieve it whenever your customers use your app.

Notice as well the value of the $array, this variable is a multi-dimensional array so be careful of creating this variable.

The first key of our array is the script_tag and its value is another array which has two keys. event and src.

By default, event should always have a value of onload. To be clear, there are no other values available for the event key. However, it is important to always initialize this whenever you create a script tag.

The next key is src. This key is used to source the file that you want to import to your customer’s storefront. In the code above, we have sourced the link https://your-shopify-app-website/scripts/shopify.js.

Make sure you replace this with the URL you have in your domain.

$array, this variable is a multi-dimensional array so be careful of creating this variable.

The first key of our array is the script_tag and its value is another array which has two keys. event and src.

By default, event should always have a value of onload. To be clear, there are no other values available for the event key. However, it is important to always initialize this whenever you create a script tag.

The next key is src. This key is used to source the file that you want to import to your customer’s storefront. In the code above, we have sourced the link https://your-shopify-app-website/scripts/shopify.js.

Make sure you replace this with the URL you have in your domain.

Testing the App

Once you’re done with everything, you can open the Shopify app. If you haven’t seen any errors and such, you may proceed to your Shopify store and open the console.

If you’re using Google Chrome, you may open the console by pressing CTRL + Shift + I.

If you’re using Firefox, just right-click the window and press Q.

Edit Shopify Store with Script Tag API - Shopify App Development

There you have it! You have successfully displayed a message in your Shopify store.

“But that’s boring! No one will actually look at their browser’s console just to see that message. We want to show it as soon as the guests arrive at our customers’ store” – Everyone 2019

Chill! Well, since we already displayed a sample message, it’ll be much easier to append HTML/CSS codes. Thanks to JavaScript!

Alright, for example, we want to display a bar on the top of the page saying that we’re on a sale. You can do that by using the following example code in your javascript:

jQuery(document).ready(function() {
	$('body').prepend('<div class="header" id="myHeader"><h2>Thank you for reading WeeklyHow\'s Tutorial!</h2></div>');
	$('head').prepend('<style>.header { padding: 10px 16px; background: #555; color: #f1f1f1; } .content { padding: 16px; } .sticky { position: fixed; top: 0; width: 100%} .sticky + .content { padding-top: 102px; }</style>');

	var header = document.getElementById("myHeader");
	var sticky = header.offsetTop;

	window.onscroll = function() { 
		if (window.pageYOffset > sticky) {
			header.classList.add("sticky");
		} else {
			header.classList.remove("sticky");
		}
	};

});
Code language: JavaScript (javascript)

Feel free to change the text to “We’re on 100% Sale!” (Wow)

Displaying HTML in Shopify Storefront using Shopify API and PHP Tutorial - Shopify App Development

Conclusion

There you go! You have successfully displayed a message in your customer’s storefront. I suggest you experiment with this API because like we said before, you can do almost everything with script tag API.

But there’s always a downside with this.

Everything will only load once the whole document is loaded. That’s why if you noticed, whenever you reload your store, the message will only display a couple of seconds later.

If you enjoyed this article, feel free to share your thoughts! Do you have questions? Let us know in the comments below!