My mom needed 250 discount codes created to go onto product labels as a bonus gift, and they all needed to be unique. She uses Shopify for her online store, and uses Shopify’s product discount codes. It would’ve taken forever to manually generate each code, as each one had to be unique and required some settings (one time use). Another requirement is that they had to all be in a CSV file, so it could be printed using the Maestro Label Designer and their “Mail Merge” feature.
Since I found Google Sheet’s scripting tool useful before, I decided it would be a good solution in this case. The first thing to do was find out if Shopify even had a discounts API. Fortunately, because Shopify it a pretty complete platform, they also have an extensive API, including endpoints for Discounts. Next, I needed to connect Google Sheets to Shopify. Google Sheets thought about the need for developers to make API request calls, so they added their UrlFetchApp class.
For making calls to Shopify, I could either authenticate for end users as an app or directly add the API keys. I found it easiest to directly use the API keys instead of going through the full authentication scheme, though if I wanted to make the app publicly available I would have to authenticate differently. It is possible, but somewhat more difficult (External APIs).
Finally, it was a simple matter of generating random text (quick search on StackOverflow to find out how), and sending the requests to Shopify to create the discount code. It was a two part process, the first to create a price rule and the next to create the code itself. I don’t know why the API was designed to require both, since all the data in the price rule is enough to create the code. I’m guessing it was just how it was built internally, with the price rule and discount code being separate.
To actually generate, I ran the script manually through the script editor. Again, if I were building a public app, I could add a whole menu with all the discount code options. The codes all generated one row after the other. From there, it was a simple matter to export as a CSV and importing it into the label designer program.
There are probably many automations you could create using Google Sheets that require repetitive action and data, I hope I can use it more in the future.