I wanted to integrate Paypal to my site. Some would probably say that I should use a pre-built shopping cart – but I didn’t want to. I want to code everything from scratch as much as possible – this may seem stupid when there are lots of very well established frameworks which includes lots of pre-built stuff out there but I feel that to truly learn as much as possible as quickly as possible it will be more beneficial for me to do things the long way.
This approach is not without it’s hindrances. For example, I already know that I need to change some of my code so that it is more object oriented – this will me to re-use the code in the future. I also know that I have not kept to the model, view , controller framework very well – particularly the model side of things – so I need to undertake an exercise to move that model code out into it’s own place. I also need to make my code set more manageable by splitting up files. I also have a great deal to learn about security and will probably have a lot of re-work to make my site and it’s transactions secure. Having said all that I doubt that I would even having been thinking properly bought my own re-use or maintenance or security requirements if I had been using an existing framework which contained pre-built modules etc.
Anyway – what I was really going to talk about was talking to an API using PHP. Well, it’s so bloody simple it’s ridiculous. PHP uses a library called lib curl. This allows you to use cURL. I don’t want to rip of someone else’s work so take a look at how to use it at Brandon Beasleys Blog.
The only other thing I have to say on the matter is that to parse the response from the API you can use the most magical of PHP functions – in fact it might be the most magical function I have ever seen in any language – it saves writing your own function to parse API responses – that PHP function is parsestr(string encodedString). This means that if I get a response back from an API like TOKEN=EC%3FV7729610061Y&ACK=Success&VERSION=9uuIIHT&OTH=ple887, then I can use the magical statement to assign each API response value to a global variable. So if I use the cURL execute statement to set the response from the API to the variable $result as follows:
$result = curl_exec($apiArrayOfValues);
Then perform the magic:
I then have instant access to the information that was present in that string by calling them using a global variable which has magically been set for each value – the variable names are basically whatever word came before the equals sign in the API response – so in this case $TOKEN, $ACK, $VERSION and $OTH.
So if I execute
echo “THE TOKEN IS: ”.$TOKEN;
I get the result:
THE TOKEN IS: EC-3FV7729610061Y
(Not that the function also changes the % to – for us as well).
If I execute
I get the result:
So all that work is done for me in one easy statement – brilliant!