Micropayment Adventure

๐Ÿ•“ Sep 16, 2019 ยท โ˜•6 min read

Foreword

  1. I'm using Zeit‘s now - it might somewhat different with other providers.
  2. I'm also using Hugo as my Static Site Generator (SSG), again, there might be some differences using other SSG's. Though, not much, I guess.
  3. This will also be done using a monorepo-structure, but it'll probably be easier to implement using multiple repos. Only thing I can think of that might cause an issue, is our good ol’ friend - CORS. They can also be quite the pain in the *beep*.

Doing this post we'll be using the Strike API, a bitcoin payment service. Just FYI, this is the first time ever I'll be implementing a micropayment to a site. Thus, I've been doing some research, and Strike seemed to be the best - and prettiest - of said service out there in the wild, wild web.

Anyhow, forward!

API

For this implementation I'll be using Go as I'm a gopher by heart.

Thus, let's start by adding a new go module - this will not be needed for this simple program, but always a good way to begin - at least for me. So, follow along, and we shall sing! - Might be a lie.

1
2
3
4
mkdir api/micropayment -p
cd api/micropayment

go mod init micropayment

Pay attention to the highlighted line, that the magic.

How does this so-called program look, then? Well, I cannot tell you now, but keep on reading, and it shall be reviewed!

First of, let's start by adding the skeleton.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
package main

import (
  "fmt"
  "net/http"
)

func Handler(w http.ResponseWriter, r *http.Request) {
  fmt.Fprintf(w, "<h1>Hello from Go on Now!</h1>")
}

To be continued…

Config

Now, how does one implement such awesomeness, using a monorepo to a serverless platform?

Luckily, we have now.json to the rescue! Or rather - To the annoyance!

Joking, of course, now.json is my friend - alas they can be annoying at times. For instance:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{
    "version": 2,
    "builds": [
        { "src": "api/**/*.go", "use": "@now/go" },
        { "src": "public/**", "use": "@now/static" }
    ],
    "routes": [
        { "src": "/api/(.*)", "dest": "/api/$1" },
        { "src": "/(.*)", "dest": "/public/$1" }
    ]
}

If using this - recommended - structure of the now.json, one would think that everything should work as before - it should be said, that we're still using hugo as the SSG - Alas, this is not the case.

As you can see, if you're following along with me. You'll get a rather blunt site. With no styling applied - this is not what we wanted. We just wanted something that works.

Anyhow, the fix is simple, but weird. By adding the highlighted line below, it'll fetch that styling as easy as 1..3 ๐Ÿคทโ€โ™‚

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
{
    "version": 2,
    "builds": [
        { "src": "api/**/*.go", "use": "@now/go" },
        { "src": "public/**", "use": "@now/static" }
    ],
    "routes": [
        { "src": "/api/(.*)", "dest": "/api/$1" },
        { "src": "/(.*)", "dest": "/public/$1" },
        { "src": "/css/(.*)", "dest": "/public/css/$1" }
    ]
}

Now that we got the styling in place. Let's work a tad more on our API.

API - continued

Now, back to the awesome Gopher code! Psych! First navigate to the api documentation of Strike. This time, scroll down until you find Create a charge.

Select the language of choice, in this case, the golang-tab. You can simply copy'n paste the code. It's almost fully working. Only thing missing is our API-key.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package main

import (
  "fmt"
  "strings"
  "net/http"
  "io/ioutil"
)

func main() {

  url := "https://api.dev.strike.acinq.co/api/v1/charges"
  api_key := "sk_your_api_key"

  payload := strings.NewReader("{\n\t\"amount\": 100,\n\t\"description\": \"example charge\",\n\t\"currency\": \"btc\"\n}")

  req, _ := http.NewRequest("POST", url, payload)
  req.SetBasicAuth(api_key, "")
  req.Header.Add("Content-Type", "application/json")
  req.Header.Add("cache-control", "no-cache")

  res, _ := http.DefaultClient.Do(req)

  defer res.Body.Close()
  body, _ := ioutil.ReadAll(res.Body)

  fmt.Println(string(body))
}

Well, if you check the code. You'll see that that I lied just a tad. I've change a couple of lines. More specifically:

  1. Line 11 has been removed. Because, why the empty line?
  2. On line 12 I've removed the .dev-part of the uri. I Know this is working, though, keep it for testing, if you want.
  3. Changed the "sk_your_api_key" to os.Getenv("STRIKE_KEY"), as we'll be getting this from the environment.
  4. Line 15 has been modified, whereas I've removed some of the \ (back-slash), and added (back-ticks) around the the string within strings.NewReader(...).
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package main

import (
  "fmt"
  "strings"
  "net/http"
  "io/ioutil"
)

func Charge(w http.ResponseWriter, r *http.Request) {
	url := "https://api.strike.acinq.co/api/v1/charges"
	apiKey := os.Getenv("STRIKE_KEY")

	payload := strings.NewReader(`{\n\t"amount": 5,\n\t"description": "MaWeCo Support",\n\t"currency": "btc"\n}`)

	req, _ := http.NewRequest("POST", url, payload)
	req.SetBasicAuth(apiKey, "")
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("cache-control", "no-cache")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		fmt.Fprintf(w, "๐Ÿค”: %s", err.Error())
	}

	defer res.Body.Close()
	body, _ := ioutil.ReadAll(res.Body)

	w.Header().Set("Content-Type", "application/json")
	fmt.Fprintln(w, string(body))
}

Now, all there's left, is to add our secret api-key.

Secrets

First, let's add the key to our own environment.

1
set -gx STRIKE_KEY "S3CR3T_K3Y" # Remember to use your actual key here

Next up, add the key to the now-environment.

1
now secret add STRIKE_KEY "S3CR3T_K3Y" # Remember to use your actual key here

You'd simply, instead of typing/pasting the key again, infer it from our own environment. I'm not lazy enough, so I've pasted it again.

Lastly, expose the secret to the now-environment.

1
now -e STRIKE_KEY=@strike_key

JavaScript

So, how do we call this magnificent function, that we've just created.

Good question, my dear Watson.

Let's add a new script to our site.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
window.addEventListener("DOMContentLoaded", function() {
    var btc = 0.00000005;
    var white = "background:white;color:black;";
    var black = "background:black;color:white;";

    var payBtns = Array.from(document.getElementsByClassName("mp"));
    for (var i = 0; i < payBtns.length; i++) {
        payBtns[i].addEventListener("click", function() {
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function(){
                if (this.readyState == 4 && this.status == 200) {
                    alert("Please take a look at the console");
                    console.log(
                        "%cPlease transfer %c%f%c BTC to this address: %c%s%c, Thanks!", 
                        black,
                        white, btc, black,
                        white, JSON.parse(this.responseText).payment_hash, black,
                    );
                }
            };

            xhr.open("GET", "/api/micropayment");
            xhr.send();
        });
    }
});

I'll take a random assumption, that you already can read JavaScript, thus, no explaination is needed ๐Ÿค—

- Thanks,

Mads Cordes


Mads Cordes
WRITTEN BY
Mads Cordes
Dev of Sorts