While a number of other payment processors have sprung up in recent years, Paypal continues to remain one of the de facto standards because of its relative prevalence and its ability to tokenize personal information. Many users have come to prefer Paypal for websites and services that may not have yet been fully vetted and would thus prefer to not hand over personal information, like credit card numbers, directly.

That said, integrating with Paypal is almost always a great business move as it will aid in capturing as many customers as possible for your web service or platform.

This post will walk you through a basic integration for Paypal with recurring billing. Paypal's latest REST API will be used in combination with Paypal-Checkout.

Terms

Before diving in, it is worth explaining a few terms that Paypal uses often when it comes to recurring billing:

  1. Agreement - An agreement is essentially a subscription, that is, a recurring payment that happens based on a predetermined schedule.

  2. Billing Plan - A billing plan provides the basic information to create an agreement. Things like cost, term and taxes are defined on a billing plan.

Integrating Checkout.js

To begin, Paypal-Checkout (checkout.js) will need to be included on the web page(s) where you would like to offer support for Paypal subscriptions.

This can be done by adding the following script to the scripts area of your web page:

<script src="https://www.paypalobjects.com/api/checkout.js" data-version-4></script>

Next, you will want add a <div> where the Paypal button should be shown:

<div class="paypal-button"></div>

Lastly, some Javascript code will be required to instantiate the button and remaining functions. You can add the following directly to a web page, or you can add the Javascript to a separate js file and include that in your web page.

paypal.Button.render({

    env: 'sandbox', // Or 'production',
    commit: true, // Show a 'Pay Now' button
    client: {
        'sandbox': 'YOUR CLIENT ID HERE', // switch to 'production' if in prod
    }

    payment: function(data, actions) {
        /* 
         * Set up the payment here 
         */
         
         // The goal here is to return a promise or callback that
         returns a payment ID
    },

    onAuthorize: function(data, actions) {
        /* 
         * Execute the payment here 
         */
         
         // Once the user has authorized the subscription, you will
         need to execute the agreement here.
    },
}, '#paypal-button');

If you reload your page you should now see a button similar to what is shown below:

Paypal Button

Creating Plans

Next you will need to create a plan to offer to your customers. Currently Paypal does not offer a web interace to do this, so plans must be configured via the REST API. That said, the best source for examples here would be the Paypal API documentation directly, found here.

Creating an Agreement

With plans created you can now begin the process of creating your first agreement. Paypal-Checkout does not offer direct support for billing agreements so you will need to manually handle this information server side.

First, write the server endpoint - in this example Python, the Flask framework and the Paypal Python SDK will be used (pip install paypalrestsdk - docs here) will be utilized:

# import standard flask modules
from urllib.prase import urlparse, parse_qs

@billing.route('/billing/paypal/agreement/token', methods=['POST'])
def get_agreement_token():
    plan_id = json.get('plan_id') // Get the plan ID from the request
    
    agreement = paypalrestsdk.BillingAgreement({})
    
    if agreement.create():
        parsed_url = urlparse(agreement.links[0]['href'])
        return jsonify({ 'token': parse_qs(parsed_url.query)['token'][0]})
    
    return jsonify({ 'error': 'failed'})

The goal with this endpoint is to take the plan ID selected by your customer and use it to retrieve a payment token. The token is retrieved on this line: parsed_url = urlparse(agreement.links[0]['href']) and then returned as a JSON object here: return jsonify({ 'token': parse_qs(parsed_url.query)['token'][0]}).

Back on the Javascript side, you can write an AJAX call to this endpoint like so:

paypal.Button.render({

    env: 'sandbox', // Or 'production',
    commit: true, // Show a 'Pay Now' button
    client: {
        'sandbox': 'YOUR CLIENT ID HERE', // switch to 'production' if in prod
    }

    payment: function(data, actions) {
        var plan_id = '1'; // change this to be the actual paypal plan ID
        
        $.ajax({
          url: '/billing/paypal/agreement/token',
          type: 'POST',
          data: JSON.stringify({ plan_id: plan_id }),
          contentType: 'application/json',
          dataType: 'json',
          success: function(data, status, xhr) {
            agreement_id = data.agreement_id;
            resolve(data.token); // resolve the promise so onAuthorize is called
          },
          error: function(xhr, status, error) {
            console.log('checkout error', error);
            reject(error)
          },
});        
    },

    onAuthorize: function(data, actions) {
        /* 
         * Execute the payment here 
         */
         
         // Once the user has authorized the subscription, you will
         need to execute the agreement here.
    },
}, '#paypal-button');

Once the payment token is returned in resolve the user is prompted to accept the agreement you have created. Once this has been done, the onAuthorize handler is called and you will need to execute the agreement for it to complete.

Executing the Agreement

To execute the agreement a separate server side endpoint will need to be created. Here is an example:

@billing.route('/billing/paypal/agreement/execute', methods=['POST'])
def execute_agreement():
    payment_token = json.get('payment_token')
    
    if paypalrestsdk.BillingAgreement.execute(payment_token):
        return jsonify({ 'status': 'success' }) // we're good to go!
        
    return jsonify({ 'error': 'failed' }) // something broke!

This endpoint does not need to return anything in particular, so long as the response code is 200. The payment_token is obtained in the JSON body POSTed to this endpoint, it is then supplied to the Paypal Python SDK and the execute function is called with that parameter. If all is well, the status: success line is returned, else an error is returned.

To integrate this on the Javascript side, another AJAX call will need to be made:


    env: 'sandbox', // Or 'production',
    commit: true, // Show a 'Pay Now' button
    client: {
        'sandbox': 'YOUR CLIENT ID HERE', // switch to 'production' if in prod
    }

    payment: function(data, actions) {
        var plan_id = '1'; // change this to be the actual paypal plan ID
        
        $.ajax({
          url: '/billing/paypal/agreement/token',
          type: 'POST',
          data: JSON.stringify({ plan_id: plan_id }),
          contentType: 'application/json',
          dataType: 'json',
          success: function(data, status, xhr) {
            agreement_id = data.agreement_id;
            resolve(data.token); // resolve the promise so onAuthorize is called
          },
          error: function(xhr, status, error) {
            console.log('checkout error', error);
            reject(error)
          },
});        
    },

    onAuthorize: function(data, actions) {
         $.ajax({
          url: '/billing/paypal/agreement/execute',
          type: 'POST',
          data: JSON.stringify(
            {
              payment_token: payment_token,
            }
          ),
          contentType: 'application/json',
          dataType: 'json',
          success: function(data) {
            // success!
          },
          error: function(xhr, status, error) {
            // failure! 
          },
    },
}, '#paypal-button');

If all is well, the success handler will be called and you can then direct the user to the appropriate page, do further requests or obtain additional information if necessary.

Conclusion

At this point you should have a very basic Paypal integration with support for recurring payments. Please note, the endpoints shown in Python are written under the assumption you have a working Flask application, to do that you will need to import additional modules not explicitly shown above. However, regardless of backend, the flow would be the same:

  1. User clicks Paypal button
  2. Fire request to server to get a payment token
  3. User accepts agreement
  4. Fire another request to server to execute it with the agreement token
  5. success or error is called, redirect appropriately

I hope this has been a helpful look at creating a basic Paypal subscription integration. Please do not hesitate to let me know if you have any questions, thanks!

Introduction

One of my all time favorite topics is the brain, but more specifically, how the brain's operation results in the human condition. Recently I have been reading about the dichotomy between the conscious and unconscious mind.

The most interesting of which, I think, is a study conducted at the University of Tennesee that investigates the timing of the decision making process while observing brain activity in an fMRI machine (an imaging device that allows researchers to view brain activity in real time) [1].

Research

During the study, researchers placed subjects in an fMRI machine and prompted them to decide to press a button in their left or right hand. Simulatenously, the subject is shown a clock with a rapidly moving second hand. Subjects are asked to identify which number the hand is closest to when they make the decision to press one button or the other. Comparing the data, researchers identified a roughly 200-300ms delay between when the subject reported making the decision and when they actually pressed the button. More interestingly, though, is that the fMRI scanner showed activity in the area of the motor cortex (the part of the brain that drives our movements) 300-500ms before the subjects reported making their decision.

This effect was so prevalent, researchers found they could readily and consistently predict how the subject would react before the subject reported making a decision.

In a separate but related study at Harvard University, Alvaro Pascual-Leone went on to modify the experiment to utilize TMS (transcranial magnetic stimulation, a way to manually stimulate the brain). In the follow up experiment, subjects were asked to think about moving one hand or the other during a specific auditory cue. Following a random pause, a second distinct auditory cue signaled that they should actually move the hand they decided to move. During some tests, researchers determined the hand that the subject intended to move using real time brain imaging and, prior to the second auditory cue, delivered a shock to the subject's motor cortex that would result in the opposite hand moving. When this happened, the subjects were questioned about the change in behavior with researchers noting that the subject's brain activity suggested that they would move their other hand. Consistently the subjects seemingly made up an explanation, stating they changed their minds, or something similar. But, given the brain imaging, it is possible to discerne with reasonable accuracy that this was not the case, and rather, the conscious brain simply tried to rationalize why the decision it made (to move the left hand, for example) did not happen. Moreso, subjects reported feeling completely normal, as if making a decision to move one hand and having the other move instead was normal.

These findings seem to suggest that this is a completely normal state for the brain. That is, that the conscious mind is not the portion of the brain that actually results in decision making.

fMRI scans during these experiments showed the activation of various regions of the brain, showing that the motor cortex was stimulated 300-500ms before the subject reported making a decision, suggesting the decision was made elsewhere in the brain and that the conscious mind, seemingly, was one of the last to know.

Foreward

From here, I wanted to take some time to expand upon the findings above, but before that I would like to note I am aware the objective of the studies above was to determine brain functionality and not to attempt to support or reject the concept of free will. However, I do believe that these findings can be used for further extrapolation in the discussion of free will.

Concept

What would it mean if the findings of these studies actually meant that free will was an illusion at best? We tend to operate under the assumption that our conscious minds are making the decisions we eventually act out, but it seems that the conscious mind is just along for the ride while doing its best to make sense of our actions.

If this is true, it would imply that what we typically consider to be free will simply does not exist. How then do we ultimately formulate our relatively complex actions then? I would like to assert that the brain operates deterministically. That is, given a specific brain state and a set of stimuli, the brain will always product the same output, similar to a computer program.

Discussion

With a deterministic brain we can be expected to react the same way every time a set of criteria are met. If I were to poke your arm right now, the reaction you would have is the same reaction you would have if we replicated the poke with the exact same brain and the exact same stimuli. That said, it is worth noting that it would be neigh impossible for the physical state of the brain to be the same since brain plasticity (the tendency for the brain to physically change based on actions and memory) has been well documented [2]. But, if you took your brain as it is right now, placed it in a vat and gave it all the stimuli you are currently experiencing, along with my poke, you would likely react the same way you did originally.

To further expand upon this idea - with a brain operating in a deterministic way, every action we take is literally the only action we will ever take because, given a certain state and a certain set of stimuli we will always act the same way.

If this is the case, then regardless of how much you want to think you wouldn't do X or Y, it is ultimately the state of your brain that decides what you will actually do.

Conclusion

If we were to agree that the idea the brain operates in a deterministic way is correct, what would that mean for the idea of free will? Researchers have demonstrated it is not the conscious mind that is first made of aware of decisions, rather, it is looped in on a need to know basis and allowed to make its own narrative. Think about this the next time you take a seemingly random action - why did you do that? Take some time to ponder the reason your conscious mind provides you - does it actually make sense?

Furthermore, consider what this means in terms of law and order. When we punish a criminal for committing a crime, are we punishing the conscious mind or the unconscious mind that likely decided to take the criminal action in the first place? Is this ethical if the brain is truly deterministic, if so, the criminal was incapable of acting in any other way.

What else would be impacted if we were to determine with certainly that our brains operate in a deterministic way?

[1] https://www.nature.com/news/2008/080411/full/news.2008.751.html

[2] https://www.psychologytoday.com/blog/the-athletes-way/201702/how-do-neuroplasticity-and-neurogenesis-rewire-your-brain

I have been fortunate in that I made it through 26 years of life before I lost somebody very close to me. This streak ended yesterday, May 23rd, 2017 when my grandmother passed in her sleep. Death is not something I had spent a great deal of time pondering before now, but sitting here in the aftermath of it all, I have had a great deal of time to think it through.

I think we all realize that death is the unfortunate end we are all moving towards. It is an inevitability, a when and how, not an if. In my experience, most deal with death by way of religion. Many major religions have a concept of a heaven or heaven equivalent, with this, it is easy to find comfort knowing your loved one is in a better place. I have no gripes with this, in fact I have found myself finding comfort through similar ideas since learning of my grandmother’s passing. However, I ultimately identify as an agnostic or atheist depending on the exact context. That said, I have been spending time trying to reconcile my beliefs with my need for comfort in such a difficult time.

In doing this, I read similar anecdotes by other atheists and one in particular caught my eye and truly resonated with me.

While I highly recommend giving the original article a read, the author is posed with a question by friend whose father had passed recently. The friend asks how the author deals with death given he is an atheist. The author discusses this in the form of a letter, during it he highlights this passage by Aaron Freeman:

You want a physicist to speak at your funeral. You want the physicist to talk to your grieving family about the conservation of energy, so they will understand that your energy has not died. You want the physicist to remind your sobbing mother about the first law of thermodynamics; that no energy gets created in the universe, and none is destroyed. You want your mother to know that all your energy, every vibration, every Btu of heat, every wave of every particle that was her beloved child remains with her in this world. You want the physicist to tell your weeping father that amid energies of the cosmos, you gave as good as you got.

And at one point you'd hope that the physicist would step down from the pulpit and walk to your brokenhearted spouse there in the pew and tell him that all the photons that ever bounced off your face, all the particles whose paths were interrupted by your smile, by the touch of your hair, hundreds of trillions of particles, have raced off like children, their ways forever changed by you. And as your widow rocks in the arms of a loving family, may the physicist let her know that all the photons that bounced from you were gathered in the particle detectors that are her eyes, that those photons created within her constellations of electromagnetically charged neurons whose energy will go on forever.

And the physicist will remind the congregation of how much of all our energy is given off as heat. There may be a few fanning themselves with their programs as he says it. And he will tell them that the warmth that flowed through you in life is still here, still part of all that we are, even as we who mourn continue the heat of our own lives.

And you'll want the physicist to explain to those who loved you that they need not have faith; indeed, they should not have faith. Let them know that they can measure, that scientists have measured precisely the conservation of energy and found it accurate, verifiable and consistent across space and time. You can hope your family will examine the evidence and satisfy themselves that the science is sound and that they'll be comforted to know your energy's still around. According to the law of the conservation of energy, not a bit of you is gone; you're just less orderly. Amen.

Having never read (or heard) this quote, I was very moved by it. I found it particularly interesting that the ideas conveyed in the passage so easily mirror those that the religious among us rely on during difficult times. When it is broken down, what we truly want to know is that our loved ones mattered, that their existence changed something in the world irrevocably, and through that change they live on.

While I am ultimately not sure if there is a heaven or hell, I do know that my grandmother lived a long, passionate and fulfilling life. She had two children, my mother and my uncle, both went on to have children of their own. My grandmother’s actions have profoundly changed the world, as a nurse she cared for the sick, as a mother she brought new life into this world, and as a grandmother she helped raise the future generations of our family. Her energy and passion live on in her children, her grand-children, and eventually my children, their children and so on.

I am comforted by the fact that, while yes, my grandmother is no longer with us, that her life had meaning. This meaning is not something that will ever die, it lives on in all of us, and in a way, my grandmother lives on too.

Recently, I have spent a great deal of time pondering the nature of what we call gut feelings. Personally, many of my decisions have been primarily guided by what I would describe as a gut feeling - but what is a gut feeling really?

I recently spoke to a woman who posed an interesting idea, that our gut feelings are a mechanism by which the universe communicates with us - an invisible hand attempting to shape our fate and our destiny. There was more that went along with the idea, but the rest was cloaked in fictional ideas based around bona fide creatures that lived within us. I don’t necessarily believe in those ideas, but I do think that the core concept is still valid.

In thinking about this some more I have been reminded of the concept of our “lizard brain” as some affectionately refer to it. Commonly, “lizard brain” refers to our more primal brain, the brain stem and associated areas. This area of the brain is commonly associated with reflexive actions that require little to no processing in the higher orders of the brain. For instance, the heart beat and respiration is largely controlled in this portion of the brain.

Evolutionarily speaking, the brain developed upwards, if you will, from the brain stem, eventually culminating in the frontal cortex that is responsible for much of the logic and reasoning us humans enjoy today.

I find it most curious that there are portions of our brain, that are very much brain in the literal sense, that we are unable to consciously tap in to. For instance, we cannot reason our heart beat down to some desired level, likewise, we cannot override the idea that we are hungry, or thirsty. This has lead me down the path of reasoning that perhaps our gut feelings have something to do with these active, but not consciously accessible portions of the brain.

The lesser brain, as I will refer to it from here on out, was what our earlier ancestors used to accomplish basic tasks. The lesser brain told them when they were hungry, it helped them move around and generally, live the life we see in most other reasonably evolved animals on earth. But there had to have been some sort of complex analysis done in this portion of the brain for our ancestors and animals to accomplish what are inherently complex tasks – intercepting prey, analyzing images provided by the eyes to locate predators, and so on. These tasks likely happen autonomously given that these creatures are not conscious in the human sense. This is all well and good in creatures that only have primitive brains, but for humans there is so much more going on, especially with the frontal cortex and the higher orders of the brain.

So then, I’ve reasoned that as humans, our lesser brains still process information much like what I have described above for animals and our ancestors. While this is no revelation in and of its self (it has been scientifically proven that this is the case), I have also posited that the lesser areas of the brain help us in processing complex situations more than we may realize.

Perhaps, what we describe as a gut feeling, is the lesser brain attempting to help us with our analysis of problems that are typically beyond its wheel house. While the frontal cortex and other higher brain orders act as a sort of central processing unit, picking apart details, perhaps the lesser brain acts as a sort of crude auditor, looking over the previously analyzed facts and drawing a more basic conclusion.

Given the separation, it would make sense that the lesser brain would communicates this information in an inherently vague and sometimes confusing way, in the form of a gut feeling.

What I find most intriguing about this idea, is that often, my gut feelings are counterintuitive. I spend a great deal of time analyzing a situation when anything more than a cursory decision is to be made, arguably, too much time. What I find curious, though, is that the conclusion I come to through my analysis is often logically sound and, objectively, a sound decision while my gut feeling is often completely the opposite.

Does this mean our lesser brains are better at processing this information? No, probably not, but then again I am not a brain scientist either. My interpretation of all of this has resulted in the idea that we should carefully consider our decisions, but not too carefully. Perhaps the over analysis that I, and probably some of you, are guilty of is clouding our judgement. Perhaps the logically sound choice isn’t the best choice? As a big fan of logic (I am a programmer after all) it pains me to suggest this, if we can’t trust logic what can we trust? But all in all, I take comfort in the idea that there is likely no “right” choice. With that in mind, we shouldn’t be afraid of taking a chance – if there is no “right” choice, logically, there can be no “wrong” choice either.

It is that time of year again, time to reflect on what has happened over the past year, where I succeeded and where I failed, and more importantly set goals for the coming year.

I, like many of you, had a pretty rough year so I am quite pleased to bid adieu to 2016.

I like to start these posts by covering what I actually did this year before delving into the specifics of last year's goals and how I did there, so here it goes!

  • Started a new business - Last year I started Bitkumo with my friends Lev and Mike. Things didn't work out super well there, but before Bitkumo ended Lev and I started a new business, Statusy. Statusy makes affordable status pages. I've put tons of time into this business and it has grown over the year into a profitable business.

  • Lost a job - I really enjoyed my time at Virtkick, but unfortunately budgetary constraints resulted in me being laid off around the beginning of the summer. While this sucked at the time, I look at it as a blessing in disguise, giving me a chance to relax and work on personal projects for the first time since I was high school.

  • Got a new job - One door closes, another opens. Not long after I departed from Virtkick I started working for Plaid Technologies, a position I have really come to love over the past few months. I feel like this position was made for me and it is allowing me to grow substantially as a developer.

  • Moved - Another year, another move. After I finished my time at Virtkick my then girlfriend and I decided it would be wise to move closer to family, so we packed up our apartment and moved north to Minnesota. When we arrived it wasn't much different than San Antonio, honestly the heat was kind of worse (with humidity stacked in), but I quickly forgot about that as we moved into the winter and sub-zero temperatures. I never understand what -19 meant in terms of temperature, but I do now: pain.

  • Traveled - I had the pleasure of taking a road trip from San Antonio to the Minneapolis area at the beginning of the year so my then girlfriend could attend a friend's wedding. I love road tripping and it is always a joy to see family so that was a good time. I also spent a few weeks in San Francisco, I hadn't been there previously but it was an enjoyable time, thanks Plaid!

  • Ended a relationship - Easily the roughest part of the year was the end of my near nine year relationship with my girlfriend, April. Break ups always suck, but this was especially rough given the time and experiences we had together. Fortunately, many friends and family were there to help me make it through to the other side with relatively minor wounds, thanks guys!

With that out of the way, it is time to look at what I wanted to accomplish this year. In my post from 2015 I listed the following goals for 2016:

  • Grow Bitkumo - This sort of happened. Bitkumo stagnated about four months after the beginning of the year, my good friend and then business partner Lev decided we shouldn't proceed. After some himming and hawing we eventually decided to sell the business to Virtkick, who continues to operate Bitkumo to this day. But hey, a successful exit is still success!

  • Get my code into production - Check! Much of my code eventually went into production at Virtkick. I also have a fair number of things in production with my current employer.

  • Learn RoR - A swing and a miss. I learned what I needed to know during my time at Virtkick, but after moving to a company that didn't utilize Rails I kind of lost interest. I have more than made up for this in my improved JS skills though.

  • Continue growing as a developer - Definitely. I've learned a ton more about Javascript, wrote a React/Redux app and continued expanding my Python knowledge. I have also improved my code reading skills drastically. I never imagined this would be as hard as it is, but it is definitely a skill to be developed.

  • Continue growing as a person - Sure. With the end of the relationship I mentioned above I took a lot of time to do some soul searching and learn a bit more about myself. Through this I've become a better Joe, I think.

Overall I am happy with my progress for the year, especially given the difficulties it has introduced. Now, on to 2017!

  • Continue growing Statusy - I love working on Statusy, I have found a great partner in Wojtek, a former colleague from Virtkick. Together we have made innumerable improvements to the Statusy platform including several major redesigns, improved UI/UX and more features than I can count on my fingers and toes. I want to continue growing this business, it is fun, and I feel it fills a hole in the market.

  • Continue learning about myself - It sounds kind of like BS, but hey it is what it is. Doing my own thing has allowed me to learn more about who I am, what I am, and what I want. I want to continue this adventure in 2017.

  • Resume pilot training - A few years back I started developing a love of aviation. This manifested its self in the pursuit of my private pilots certificate. Unfortunately, things didn't work out financially so I ultimately stopped this pursuit, but now that I am where I am, it seems like a great time to pick this up again.

  • Have fun - Another thing I have learned throughout the year is that working all the time is simply no fun. I've had several very productive years, but working all the time has started to have an impact on myself today, my previous relationship and relationships with friends and family. I don't intend to become a bum, but I do want to take it easy this year and enjoy myself a bit more.

With that, good bye 2016, hello 2017. I hope you all have a great 2017!