Facebook Payments Documentation Guide for Lazy Developer

Facebook payment documentation provided just has too much chitchat going on. So here is simple quick rundown.
NOTE: This is for September 12, 2013 breaking changes local currency payments documentation.



Step 1 - Define your Items

Essentially each item has it's own http/https address and being red via GET request, so you want to have view that could display each item by giving it an id. This link will be used in your frontend js and Facebook will cache the contains on it. https://developers.facebook.com/docs/howtos/payments/definingproducts/#ogproduct_item

If you want to make dynamic prices for things such as flash sales - don't provide the price, but that defeats the purpose of Facebook cached HTML views IMO, probably just a reason to push `og`. In this case on each popup Facebook will ask your backend the exact price. Request/Response after the image:

List of supported currencieshttps://developers.facebook.com/docs/concepts/payments/currencies/

You can debug your views by pasting your item link to https://developers.facebook.com/tools/debug/

Step 2 - Add JavaScript

In this step you have to create JS method that will be called in the frontend in order to call up the payment popup.
It's easy and nothing much to add here. Just look up this https://developers.facebook.com/docs/howtos/payments/paymentflow/#paydialog

Step 3 - Create Callback

Here is the meat of the callbackhttps://developers.facebook.com/docs/howtos/payments/fulfillment/#jscallback
In the overview you'll see a graph and explanation below it, all you care at this point is what happens on step 8 and after. This is the callback logic. The best thing about it that docs are pretty solid here, also for rather quick rundown on logic video is great too.

So here you have two options (or both): you can confirm purchase via frontend (this is good for notification of payments for the user) and backend and technically you don't need both (technically!), and better one is via real time callback (backend) true graph api since it's more secure and will update in cases where JavaScript might fail (video explains this quite well).

So frontend docs are here: https://developers.facebook.com/docs/howtos/payments/fulfillment/#orderfulfillment
And Real Time docshttps://developers.facebook.com/docs/howtos/payments/fulfillment/#asynchronousconfirmation

Not much else to drop from this.
Have fun.


Quick Bits #3 - Working in Remote Server via SSH

So I am working in remote server as my primary development platform for half a year or more. Everything via SSH. So my few cents on this.

Nginx dynamic domain proxy

The server it self has a domain and some open ports, besides that I use Nginx to proxy all requests to my development server running locally.

Nginx can use regex in this case quite effectively, besides some of my projects are hostname sensitive so this helps a lot since I get port :80 to listen any domain with single Nginx setting. All it needs is server name:
server_name         ~^dev\.(?P<project>\w+)\.(?P<network>\w+)\.mydomain\.com$;
Also I can use this latter on as variables to use different logs or do other scripting, but for some reason that was failing on me and I never need it that much since I work on single project at the time. So maybe this will be expanded latter on.

SSH keep alive/timeout change

So when you have multiple tabs open they start to disconnect, so usually what people do is to run tmux or screen session and work with that. But event then, you go for a cup of coffee... Well ok this is bad sample since it's also a security risk that way, but the idea is the same - have more time on your hands.

This is solved and explained quite extensively here - http://qr.ae/I5Fnd

Personally I edit ~/.ssh/config or /etc/ssh/ssh_config, this works on server side too for single server, just config is /etc/ssh/sshd_config. So All you need to add is
ServerAliveInterval 10 


Other than Nginx I use daily these tools (in no particular order) that help me to cope with SSH environment:
  • ZSH with Oh-My-Zsh (https://github.com/robbyrussell/oh-my-zsh, zsh installed via apt)
  • Tmux (allows to run multiple terminals on same ssh session)
  • Vim (in Ubuntu Vim-nox, since it comes with all extensions and python interpreter)
  • Git and Tig (Tig is a history viewer for Git)
  • Htop (enhanced version of top)
  • tree (shows hierarchical folder tree)
  • dtrx (allows to extract any compressed archive, I never remember all the flags)


Heath Points of Hewlett Packard and the Review of HP Envy dv6

Most of my friends are somewhat IT related,  and most of them have horrible opinion when it comes to HP. This is due to the fact that most of them know at least few friends that owned or they owned themselves HP laptop and it broke in horrible ways.
For starters friend of mine had HP laptop that constantly overheated so he had to remove bottom cover for HDD/RAM/WiFi and carry around something to lift the bottom so the laptop would get air to cool itself. His girlfriend had HP laptop and it's graphics card was repaired few times by warranty and died because of the same reason. My other friend had HP laptop, it corpus around the hinges broke in half a year. My mother had laptop for work that was painfully slow. I probably could name few more, but you get the point. Horror stories are all around.
So it happened that I was planing to buy ASUS laptop that I was looking at for a very long time, but on the last moment shit went down and I had to buy anything that works if possible - as cheap as possible. Sure I wanted something that could work with some 3D graphics and wouldn't lag on OS itself, maybe play some games, so bare with me it was not the cheapest laptop. But I got it with discount as well as 3 year warranty.
So in the end I let myself for and adventure buying HP Envy dv6.

The Horror

The unboxing was not pleasant. When I powered on the computer - I've noticed that only English power plug is added. I do believe it's a fault of seller not manufacturer. It was just a step "O.K. Here we go...". Around the screen there was protectors from fingerprints. All around the damn unit including on hinges where it's really hard to remove. There was also one on the grill bellow the monitor (purely decorative I believe). Those are made of plastic and left side is 0.5 mm too long (right side is stuck perfectly) so it just slightly out of the in-cut for it. Also on the left side there was this bit that does not stick and helps you to remove the protector. I've started pulling on that and the whole grill started to come off. At this point I was thinking how/when I'll return the unit.

Surprise, Surprise 

When turned on everything went smoothly. Windows 8 activation (about Windows 8 - it will be another topic), UEFI disabling, Ubuntu installation besides Windows 8... Maybe too smoothly. It was one of the easiest laptop setups I've done. I was especially surprised when I turned on Ubuntu. Everything works. Sure the Laptop comes with nVidia geforce gt 630M - this means Optimus Prime stomping on your dual screen... But to my surprise VGA connector is not bound to the nVidia. Dual screen true VGA works fine. The only downsides are that brightness changing takes big steps so it's not as smooth as in Windows, but hey - in last laptop (emachines) the back-light was completely not working and would light only when direct command would be sent out.
To install Ubuntu along side Windows 8 just follow this guide - http://askubuntu.com/a/228069/8825

What I don't Like

  • The screen. It's same old 1366x768. I do agree with Linus on this topic and I believe 1080p should be the smallest standard. It's one of the better screens on this resolution, but just because it's not 1080p - I hate it.
  • Around the monitor there is a rubber protector that sticks our something like 1 mm. It feels when touched horrible, but to the eye, it is not as bad as it sounds.
  • Indicators. Well more lack of them. There is WiFi indicator on WiFi/F12 button. There is CapsLock indicator on CapsLock. There is power indicator on power button as well on back of the lid (illuminated HP logo). Aaaand thats it. FFS at least they could have put NumLock indicator. Also there is no HDD indicator witch means you will not be able to know if your computer is counting sheep or hard at work with HDD.
  • WiFi and Bluetooth is a combo card, witch means you cannot turn off one without other. This means that I have always running hidden bluetooth.

Things I like

  • Sound. It comes with Beats Audio (tm) and supposedly has subwoofer on the bottom. Hard to say if it contributes that much, but I can listen music without headphones on this one.
  • Insides. Intel i7, nVidia geforce GT 630M, 8 Gigs of RAM, 1TB HDD makes quite a show. The only things that I would like to change is bit faster HDD since this one is 5200 RPM. Also since I already had 16 Gigs of 1600 Mhz CL 10 RAM - I changed those, but the ones that come are decent enough.
  • When changing RAM I've noticed that everything is accessible removing single panel and that panel is hold by single screw. No warranty stickers on it ether, so you can upgrade your laptop without a fuss. 

Things that are "Meh"

  • Keyboard. It's comfortable - old apple style keyboard, but there is small gap between the spacing and the keys so stuff can go under the keys. It might be hard to clean.

Back to HP

So all in all I had quite uncomfortable start, but after that it exceeded my expectations. My brother right now has HP ProBook as well. He's working with quite demanding software and it handles it well. No breaking, not scratches, no heating. Nothing. Also I gave him my stock RAM's (8 Gigs) and holy fuck. This is how you change ProBook RAM:

No screws. Why the hell not every laptop is this way?! Take a note that it also opens up fan for easy cleaning. This is just perfect...
So all in all it went better than expected. Well see how it will last. I'll post updates if something happens.


Quick Bits #2 - Terminal tutoring

Recently I've commented this on one of the G+ threads, so decided to put it on the paper internet. There is these tools - terminal multiplexers. Most commonly known is Screen. Another, a lot younger one is Tmux, oh there is also wrapper for these called Byobu for Ubuntu, but that's a little bit off topic. They share a lot in common, and have some differences as well. Best comparison is here - https://www.wikivs.com/wiki/Screen_vs_tmux.
In short - these programs allows to run multiple terminals in single session, allows to leave it running and continue latter on. If you're doing a lot of work via ssh, most probably you already use one of such multiplexers.
One of great features is session sharing (both of them have it). Session sharing will allow to multiple users enter text/commands and view same outputs and inputs. At least in screen (not sure on tmux yet) there is a problem - when you share a session, and it contains multiple terminal instances - all connected users needs to switch to that terminal manually. So the easiest solution is to run screen within a screen (no screenception pun intended) or mix screen and tmux, whatever works, personally I like mixing screen and tmux since by default they use different keys ^a and ^b... In such case only the bottom layer  (first screen/tmux) will need to share the session while top layer (second one) will just display output for all users, meaning that if one will switch terminal it will be switched for all. So far it seems to me to be the best way to introduce to code/configs and terminal based tools.

To share screen session (what I personally used) - http://serverfault.com/questions/336594/share-screen-session-with-users-in-the-same-group-linux
For Tmux - http://readystate4.com/2011/01/02/sharing-remote-terminal-session-between-two-users-with-tmux/


Quick Bits #1 - Nginx proxy

I've been developing social games for over a year now for most of the time I had simply open ports to my laptop at office. Also our office has domain. So inside of social apps I have set iframe url as myofficedomain.com:<myport>. This is convenient only when working inside office. Sometimes shit happens and you have to help/work from home and if you want to load the same app within laptop on different network - you're shit out of luck. You have to get outgoing domain for that, network you're in might require port-forwarding that cannot be changed and so on. So I found the easiest solution for that is to setup proxy to witch you could ssh from any machine and use it as gateway for your social apps.

This brings few good things. You don't need port (for example new vk.com payment system disallows to use links with ports in payment system). You don't need change iframe urls within apps since sometimes that can become annoying since it might require confirmation true emal or even worse - phone, also sometimes these notifications lags quite a bit and it's dead time waiting.

So all you need to do is to get a server that has your soon-to-be-proxy domain pointing to it and Nginx installed in it.

You need to setup Nginx vhost as displayed:
server {
    listen 80;
    server_name myawesomeproxydomain.com;

    location / {
        proxy_set_header  Host $host;
        proxy_set_header  X-Real-IP $remote_addr;
        proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
This will proxy all requests that will come to your domain to localhost:5000

Sure on the server nothing runs on localhost:5000 (sure you can change the port) so we need now to setup proxy from your machine to the server. It's simple as connecting to the server. SSH has -R attribute that will setup reverse proxy. Or as manual writes:
     -R [bind_address:]port:host:hostport
             Specifies that the given port on the remote (server) host is to be forwarded to the given host and port on the local side.  This works by allocating a socket to listen to port on the remote side, and whenever a connection is made to this port, the
             connection is forwarded over the secure channel, and a connection is made to host port hostport from the local machine.

             Port forwardings can also be specified in the configuration file.  Privileged ports can be forwarded only when logging in as root on the remote machine.  IPv6 addresses can be specified by enclosing the address in square braces.

             By default, the listening socket on the server will be bound to the loopback interface only.  This may be overridden by specifying a bind_address.  An empty bind_address, or the address ‘*’, indicates that the remote socket should listen on all
             interfaces.  Specifying a remote bind_address will only succeed if the server's GatewayPorts option is enabled (see sshd_config(5)).

             If the port argument is ‘0’, the listen port will be dynamically allocated on the server and reported to the client at run time.  When used together with -O forward the allocated port will be printed to the standard output.
So it's as easy as opening SSH connection with such command line:
ssh -R proxyuser@yourawesomeserver.com
So if you run your project in localhost:8000 it will receive everything that comes to proxy domain.

Another good thing to do here is to increase life time of a SSH session. This can be done on both sides - server and your local machine. I suggest to do it on your local machine. Simply edit /etc/ssh/ssh_config if you're in Linux and add ServerAliveInterval 60 this will send each 60 seconds a packet to the server to mention that the user is still around.

SSH session fix is taken from here: http://ocaoimh.ie/2008/12/10/how-to-fix-ssh-timeout-problems/


Flask With Green Pony. Part #1 - Putting Damn Pony into the Cage.

So I figured to share some evening battle stories. Maybe it will help someone while fighting against their own demons and zombies via Google jails.

TL;DR - scroll to the bottom.

Right now I'm fighting Gunicorn - a green nifty WSGY server. It's not the best. But I like it. Buzz off.
The situation is this. I'm developing quite big flask app. The reasons that made me choose flask over others was that I'm for sure going to use SQLAlchemy and flask has some nifty plugins. For me Django without it's ORM seems bit pointless. So I figured to take something smaller and build on top of it.

One of my friends always says how he's used to start big and just remove stuff he don't need. As I saw him using snippets that was exactly what he did. Vim combo results in huge snippet and then a third of that is deleted. I have quite opposite plan of actions. Start small, but clean and then build up. Sure I see advantage in his approach that you don't need to remember/find that much stuff. Anyways. Flask.

Flask has some issues. Devs loves to put everything in single file. That pisses me off. I like hierarchical clean structures. Also Flask just adores global variables. I would suggest to find a room for those two [flask and global variables], but hey who I am to judge?

So the idea is that I have Flask app that is developed by my standards meaning that there is startup scripts, management commands, soon to be plug-in modules, clean settings for app. Yeah. More or less lighter Django with more litter in the code. But it's MINE. Buzz off.

So challenge is to run my fat-ass Flask app with gunicorn. What Flask docs has to offer?


myproject:app? that's what?.. Method? setup.py has possibility to add global console scripts (terminal global scrips per say) that uses package:method declaration. But this does not work in my case if I give it main method. I wish... So what Google has to offer?


So it expects global variable once again. Great. But then again what's the point of it? I don't want to always run my app with $ gunicorn <stupid_miles_long_path>/main:app <crap-ton of properties>
I want to make it that I just could run MyApp within terminal and give few SIMPLE arguments and everything would be fine. So I want to implement gunicorn directly to my app. Most of the internet here is useless, all you can find is how to proxy with nginx to $ gunicorn main:app

Here is the golden link:


It's almost right. Few fixes - main file is not main.wsgi in most projects, it's proper *.py and there is few problems. Last line of MyCustomApplication class.

If you look at util file https://github.com/benoitc/gunicorn/blob/master/gunicorn/util.py#L275 you'll find that it tries to extract app file from string (you're giving it string - what do you expect). If you're doing this directly from app - you have everything on your finger tips - why the hell you would want to get file from same folder try to parse it's name and then fail. Yep. It leads to error of booting workers. Something similar to -

If you're doing everything cleanly - it will simply wont find THE app. And it's easy to fix it. Instead of calling utg.import() simply import your global variable from whatever you placed it and return THE app.

Oh also I added ProxyFix. Not sure if I need it. In most google places it was added so I would assume it's a good thing.

So here is that custom extra class. I named it Server:

from gunicorn.app.base import Application

from werkzeug.contrib.fixers import ProxyFix

from MyApp import app

class Server(Application):
    Custom Gunicorn Application

    def __init__(self, options={}):
        '''__init__ method

        Load the base config and assign some core attributes.
        self.usage = None
        self.callable = None
        self.options = options

    def init(self, *args):
        '''init method

        Takes our custom options from self.options and creates a config
        dict which specifies custom settings.
        cfg = {}
        for k, v in self.options.items():
            if k.lower() in self.cfg.settings and v is not None:
                cfg[k.lower()] = v
        return cfg

    def load(self):
        '''load method

        Imports our application and returns it to be run.
        app.wsgi_app = ProxyFix(app.wsgi_app)
        return app

And this is how my part of main:main looked with flask running:

def main():

    app.secret_key = settings.SECRET

And this is how it looks now:

def main():

    app.secret_key = settings.SECRET
        'bind': '%s:%s' % (settings.ARGS['--host'], settings.ARGS['--port']),
        'debug': settings.DEBUG,
        'worker_class': 'gevent',
        'workers': numCPUs() * 2 + 1,

Sure main has right now access to numCPUs() method and sure Server is imported. numCPUs() method can be found in previously mentioned link - http://www.capsunlock.net/2011/04/running-flask-with-gunicorn.html
Also my app uses docopt, so I just removed __doc__ string from examples here.

I still right now have some issues - it seems gunicorn ignores my debug option. Demonizer suicides. But that's for another evening.

Over and out.


Asus EEE X101CH Review

For quite I while I have to fix, update and maintain this little netbook. Although it's not mine - I've used it for quite a while and feel comfortable writing this review.

The Outside

It's meant to be cheep. Plastic only. However it means that it's light. Just a bit over 1 Kg with charger in your bag. So don't expect anything special, it's meant just to do it's job and it does it quite well.

Keyboard is surprisingly comfy. Touch pad is incorporated to plastic cover. With this one I had few problems, but about that latter on. It has full size HDMI connection, VGA, 2xUSB 2.0 LAN, Audio connections and Card Reader. That's it.

Screen is reasonable - 10.1 inch LED Backlight WSVGA (1024x600) screen. It's not glossy, colorful and sharp enough that it wouldn't strain your eyes.

All in all - it's good enough that it wouldn't bother you.

The Inside

This one is a bit tricky. Sure it has standard Intel Atom N2600 Dual Core processor and a gigabyte of RAM. 320Gb HDD, 0.3 Mp front camera, single (quite bad) speaker,  WLAN, Bluetooth... Nothing special until you touch operating system... Here goes my rant...

It is suggested to be used with Windows 7. What a load of bullshit that is. First touch pad drivers... Non of both types of drivers provided by Asus does not work and it's better to leave it as is after installing Windows. One of those makes touch-pad unusable other simply does nothing. Great.

Secondly it has only a gig of RAM, immedeatly at least half of it is occupied by Windows. So if you want to write a document while opening 3 or so tabs of chrome while listening for music in the meantime - you gonna have a bad time... You cannot upgrade RAM since it's stuck right to the motherboard and does not have SO-DIMM.

I'm not sure ether it's fault of Windows since it does not have swap space and tendency to ran out of memory or ether it's problem with overheating, but netbook tends to freeze up from time to time (also it gets hot) when under heavier loads. It's really annoying and it's a huge problem. On this alone I would not recommend buying this one, but only if you cannot live without windows.

Yep. Linux to the rescue! Linux did had a problem with this laptop since Linux did not sported Intel GMA 3600 graphics (this netbook Intel Atom uses these). So you got 800x600 resolution only, or something similarly small, but since release of Linux Kernel 3.4.2 it works fine. So newest batch of Linux distributions will work better and better with this laptop. Currently I've installed Ubuntu 12.04 and 3.4.2 Linux Kernel and it works fine. Sure Battery wont hold as long, brightness settings does not work yet as well, YouTube video lags a bit too (from time to time), but hey, at least it does not freeze up for a minute once per 5 minutes and can multitask. Ubuntu 12.10 already contains this Kernel update as far as I know, so there wont be any need for addition fiddling with Linux Kernels very soon. Also running Linux makes it faster and more responsive. And no more - "you [pathetic human being] need TouchPad Drivers" popups again!

All in All

It's small little netbook, probably will be on sale for very low price in official retailer shops since Asus is killing eee netbook series due to tablet invasion for small portable devices. If you do need something like that and you're comfortable with Linux I would really suggest grabbing one just because of low price it could end up. Otherwise if you do need windows and you do need exactly netbook, I would suggest to avoid this model.


So it seems that Ubuntu 12.10 will not boot at all since there is a bug that requires to blacklist that particular GMA chipset. So far the best is to run 12.04 with 3.4.2 kernel. At least that works. More info here: http://linuxrepository.blogspot.com/2012/09/how-to-install-linux-342-quantal-kernel.html

Update 2.0

Ubuntu 13.04 works fine. Unity is quite slow, but Xubuntu is perfectly usable. No issues whatsoever. Maybe something is not quite right (again it's not my laptop and I am not a primary user of it so I didin't test everything), but from first sight it's fine and so far I had no complains.