A simple guide to Stripe Webhooks

How they work and a quick PHP tutorial

What are webhooks?

Webhooks are ‘user-defined HTTP callbacks’. When an event occurs, the originating site will send an HTTP post request to a (usually) third-party who can then do something with it.

As an example, if you pay for something with Stripe then it will send a webhook. This will contain lots of data that looks like this:

Stripe\Charge JSON: {
  "id": "ch_15qP2a2eZvKYlo2C4fpk2mXl",
  "object": "charge",
  "created": 1428760376,
  "livemode": false,
  "paid": true,
  "status": "succeeded",
  "amount": 4995,
  "currency": "usd",
  "refunded": false,
....and so on

You can check out a more complete version on Stripe’s API docs here.

Why should I care?

If you don’t work in technical services or you found this page whilst googling for fishing tips, you probably won’t.

On the other hand, it’s very useful for storing information about what’s happening with your Stripe account. As the co-founder of Hooked.io I built a company which trivialises getting notifications about payments, disputes and transfers.

It’s also good for things like collecting usage data and whatnot.

How can I get a webhook?

Easy! First get hold of the Stripe PHP Library and put it in your directory.

First set your Stripe secret key (available in the dashboard)

\Stripe\Stripe::setApiKey(“sk_test_dwndaindiawd232dad”)

Then we want to get the POST data that Stripe sends:

$input = @file_get_contents(“php://input”);

Then decode the json:

$event_json = json_decode($input);

This will produce the array that you saw above. Take a look with:

print_r($input);

From there you can do anything you like with the array data! Referencing individual values is very simple:

if $event_json->type == ‘charge.succeeded’ {
echo ‘You made some money! Hooray!’;
}

Obviously a basic understand of arrays will make life easier for you here.

This is a very simple example of course, and there are some security factors which you should consider such as never processing the same event twice.

It’s fairly simple to do this, simply store the event id in a database and check against it before processing your webhook.

That’s it! Hopefully you found this helpful.

Courtesy: MEDIUM
Advertisements

5 New Features In PHP 7 That You Should Have A Look At

PHP is by far, the most preferred programming language. But is PHP 7 the most exciting releases of them all? Yes. The whole PHP community and the people linked to PHP, are all excited to welcome the biggest release for PHP in decades. It surely adds more versatility to the already versatile language.

But you must be wondering why PHP named its latest release PHP 7 and not PHP 6. Reason behind it is that, many of the PHP 6 releases were already implemented in PHP 5.3 and later, there was not really a proper reason just to change the name. What I am trying to say here is that we haven’t missed anything. Just to avoid the confusion with a dead project, PHP’s latest release was named to PHP 7.

Is This Hype Valid for PHP 7? What It Actually Brings Forth for the Developers?Hop on and let’s take a deeper dive. Let’s check out what new features PHP 7 has to offer. And what improvements those features will bring forth.

 

1. Speed Improvement

The developers for the PHP 7 has done a pretty commendable job here. Now your PHP codebase uses less memory and gives you even more performance than before. After it’s release, internet was overloaded with benchmarks which were really promising. It is almost a 2x increase inserver response times with PHP 7. For further details on benchmarks click here.

2. Implementation of Type Declarations

The type declaration is used to specify the type of variable. PHP sets this automatically and because of which, PHP is a weakly typed language. PHP does not need you to declare the data type. Because of which, you could do radical things with the variables, like adding Float into String without resulting in an error. Type declaration helps you get the expected results. Making sure that only certain procedures can occur. Which makes the code understandable.

In the previous PHP versions, we could use type hinting method. This method specifies the type of an argument declaration in a function. But the issue with this method was that you can only use it with a function declaration. Which limits to only two types, a class name, and an array.

Scalar Type Declaration

PHP 7 has now added Scalar type declaration for int, float, string, and boolean. Adding scalar type declaration and enabling strict requirements ensures that more correct and well-documented PHP programs can be written. It also helps you in gaining more control over your code and make the code easier to read.

By default, on PHP 7, these declarations are non-strict. Which means that the type forging is possible. As if you pass a string starting with a number into a float type function, it grabs the number from in the start and skips everything else. Passing a float into a function that requires an int, that float will become int.

Non-Strict Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function getSum(float $a, float $b) {
   return $a + $b;
}
getSum(6, "7 week");
//Here int(6) changed to float(6.0) and string “7 week” changed to float(7.0)
//with a “Notice: A non well formed numeric value encountered”
//returns float(13)
getSum(1.1, "2.2");
//Here string "2.2" is changed to float(2.2) without any notice
//returns float(3.3)
getSum(3.1, 2);
// changes int(2) to float(2.0)
// returns int(5.1)

Here the getSum function receives 2 floats and adds them together returning the sum. When you use a non-strict type declaration in PHP 7. It will reforge these arguments to match the type specified in the function. Which means whatever the argument we pass, PHP will convert it to float.

Strict Example

PHP 7 additionally gives us the opportunity to strict the declaration type. It is achieved by adding “strict_types=1” on the very first line of the file. This ensures that any calls made to the functions specified must strictly adhere to the specified types. Strict is determined in the file in which the call to a function is made and not the file in which the function is defined.

While using a strict type-declaration, if a mismatch occurs, a “Fatal Error” occurs and we know that something is not functioning as desired. This helps in not causing random and confusing diagnose issues. Let’s just cut the talk and take a look at an example with strict types turned on.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
declare(strict_types=1);
function getSum(float $a, float $b) {
    return $a + $b;
}
getSum(3, "2 week");
// Fatal error: Uncaught TypeError: Argument 2 passed to getSum() must be of the type float, string given
getSum(1.8,  "4.5");
// Fatal error: Uncaught TypeError: Argument 2 passed to getSum() must be of the type float, string given
getSum(3.1, 2);
// int(2) change to float(2.0)
//returns float(5.1)

Setting “declare strict_type” to “1”, the first two calls that pass a string produces a Fatal error: “Uncaught TypeError: Argument 2 passed to getSum() must be of the type float, string given”. With only the exception in the third call, in which if you pass an integer for an argument instead of a float value, PHP will perform “widening”, which includes adding .0 at the end of the integer value. This returns (5.1).

Return Type Declarations

The third type of declaration that PHP 7 supports are a Return Type Declaration. It supports all similar type arguments as a return. Take look at the example of how to specify a return type declaration.

1
2
3
function getSum(float $a, float $b) : float {
}

Adding a return type ensures that only an expected value type returns. For the previous two examples if we set the return type float it will work the same. As the values being returned are already float. So we will be doing an example for int. return types.

Non-Strict Integer Example

Without the strict type declaration on, if we specify the return type as int for the previous examples, it will work the same. With just the difference being, that return will be forged to an integer. Which means it will truncate the float value and only returns the integer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function getSum(float $a, float $b) : int {
    return $a + $b;
}
getSum(6, "7 week");
// changes int(6) to float(6.0) & string(“7 week”) to float(7.0)
// returns int(13);
getSum(1.1, "2.2");
// changes string "2.2" to float(2.2)
// returns int(3.3)
getSum(3.1, 2);
// changes int(2) to float(2.0)
// returns int(5.1)

Strict Integer Example

If we turn strict types on, we’ll get a Fatal error: Uncaught TypeError: Return value of getSum() must be of the type integer, float returned. For this case we’ll be casting our return value as an int. which then returns the truncated value.

1
2
3
4
5
6
7
8
9
declare(strict_types=1);
function getSum(float $a, float $b) : int {
    // return $a + $b;
    // The above statement shows Fatal error: Uncaught TypeError: Return value of getSum() must be of the type integer, float returned
    return (int)($a + $b); // truncate float like non-strict
}
getSum(3.1, 2); // changes int(2) to float(2.0) and returns int(5.1)

Benefits

These new implementations of Type Declaration certainly help in making the code easier to read. With PHP 7 you get a versatile type declaration methods which makes your life easier. You can even see at the start of the function, what is required and what will be returned.

3. Implementation of Error Handling

The next new feature we will be discussing are the new Error Handling techniques implemented in PHP 7. Handling fatal errors was a nightmare in previous versions of PHP. If a fatal error occurs it just simply stops the script rather than invoking the error handler. On a production server, this returns a blank white screen to your users, which in the end causes your credibility to drop.

But PHP 7 allows an exception to be thrown when an error occurs, rather than stopping the whole script. This doesn’t mean that Fatal errors are gone from PHP 7. They still exist i.e., an uncaught exception will still be a fatal error in PHP 7. One more thing to highlight here is that other types of errors like warnings and notices are unchanged in PHP 7. And exceptions are only thrown by fatal and recoverable errors only.

However, Error and Exception both in PHP 7 implements the new throwable class. This means both work almost the same way. Let’s see the new hierarchy to understand more.

-> Exception implements Throwable
    -> …
-> Error implements Throwable
    -> TypeError
    -> ParseError
    -> ArithmeticError
        -> DivisionByZeroError
    -> AssertionError

Under Error, PHP 7 now have some more specific errors. Which includes ParseError, TypeError, ArithmeticErrors and an AssertionError. Practically all errors that were fatal in PHP 5, now throw instances of Error in PHP 7, which in term help you to improve your code legibility.

4. New Operators

PHP 7 also brings us some new operators. Let’s just cut the talk and directly go through all the new operators.

Spaceship Operator

The first one in our list is the Spaceship Operator, also known as the Combined Comparison Operator. It is put together using three of the previous operators, namely, “<”, “=” and “>”. It looks something like this:

1
<=>

What this operator is useful for is that it will compare the value on the left to the value on the right and returns 3 different values. See the example below for further understanding.

1
2
3
4
5
6
7
$compareResult = $a <=> $b
if $a < $b it returns “-1” to the variable “compareResult”
if $a = $b it returns “0” to the variable “compareResult”
if $a > $b it returns “1” to the variable “compareResult”

A very useful operator. The most common use of this operator will be in sorting.

Null Coalesce Operator

Another new operator in PHP 7 is the Null Coalesce Operator. If it is not null it returns the left operand, otherwise, it returns the right operand. The thing worth mentioning here is that it won’t pop any notice if the left operand is a null variable.

1
$user = $userName ??  "v3ron";

In the above example, if the variable userName is not null, it will push that value to the variable “user”, or else “v3ron” will be assigned to the variable “user”.

Before PHP 7, something like this would be written as:

1
$user = isset($userName) ? $userName : “v3ron”;

And yes, these can be stacked which makes it much likely to be used. It will check each item from left to right until it finds one that is not null, it will use that value. For example:

5. CSPRNG Functions

The CSPRNG abbreviated as “Cryptographically Secure Pseudo-Random Number Generator” is an easy to use API. It provides an easy and reliable way to generate secure random integers and bytes for use within cryptographic contexts. It can be used especially for generating random passwords or password salt.

2 new functions have been introduced in PHP 7 to use namely, “random_int” and “random_bytes”. Let’s analyze a bit more to see what these two brings to the table for the developers.

Random Bytes

With random_bytes, you only supply a single argument that is the length of the random string which it will return in bytes. Take a look at the example for a better understanding.

1
2
3
4
5
$randomByte = random_bytes(10); // 10 is the length in bytes
var_dump(bin2hex($randomByte));
// output for the above code is: string(20) "5f655db3ae43c256937b"

These are bytes, not integers. For a random number or integer, you should use the random_int function.

Random Integers

This function generates secure random integers. When using random_int you supply two arguments, that are min and max. Which tells the minimum and maximum numbers for the random integer.

For example:

1
random_int(2,10);

The above code returns a random number between 2 and 10, including those two as well.

6. Conclusion

So much for all the new features. There are some features that have been removed in PHP 7, you can check them out by going to the deprecated features section in PHP 7.

Versions released before 5.5 are not compatible any longer. Now it is for you to decide whether to upgrade to PHP 7 for super fast speeds and update all your code accordingly. Or stay with the previous version of PHP.

PHP Libararies for working with MS Office

1. Microsoft Word

PHPWord – A library for working with Microsoft Word documents.
PHPWord is a library written in pure PHP that provides a set of classes to write to and read from different document file formats. The current version of PHPWord supports Microsoft Office Open XML (OOXML or OpenXML), OASIS Open Document Format for Office Applications (OpenDocument or ODF), Rich Text Format (RTF), HTML, and PDF.

2. Microsoft PowerPoint

PHPPowerPoint – A pure PHP library for writing presentations files.
PHPPowerPoint is a library written in pure PHP that provides a set of classes to write to different presentation file formats, i.e. Microsoft Office Open XML (OOXML or OpenXML) or OASIS Open Document Format for Office Applications (OpenDocument or ODF).

3. Microsoft Excel

PHPExcel – A pure PHP library for reading and writing spreadsheet files.
PHPExcel is a library written in pure PHP and providing a set of classes that allow you to write to and read from different spreadsheet file formats, like Excel (BIFF) .xls, Excel 2007 (OfficeOpenXML) .xlsx, CSV, Libre/OpenOffice Calc .ods, Gnumeric, PDF, HTML, … This project is built around Microsoft’s OpenXML standard and PHP.

ExcelAnt – Simple yet powerful Excel manipulation library for PHP 5.4+.
ExcelAnt is an Excel manipulation library for PHP 5.4. It currently works on top of PHPExcel.

4. Extra

Csv – A CSV data manipulation library.
Csv is a simple library to ease CSV parsing, writing and filtering in PHP. The goal of the library is to be powerful while remaining lightweight, by utilizing PHP native classes whenever possible.

5. The end

Hopefully this simple tutorial helped you with your development.
If you like our post, please follow us on Twitter and help spread the word. We need your support to continue.
Did we miss out anything? Do leave a comment below to let us know.

 

POSTing JSON Data With PHP cURL

I got this question the other day: how to send a POST request from PHP with correctly-formatted JSON data? I referred to the slides from my web services tutorial for the answer, and I thought I’d also put it here, with a bit of explanation. After all, publishing your slides is all very well, but if you didn’t see the actual tutorial, I often think they aren’t too useful.

We can’t send post fields, because we want to send JSON, not pretend to be a form (the merits of an API which accepts POST requests with data in form-format is an interesting debate). Instead, we create the correct JSON data, set that as the body of the POST request, and also set the headers correctly so that the server that receives this request will understand what we sent:

$data = array("name" => "Hagrid", "age" => "36");                                                                    
$data_string = json_encode($data);                                                                                   
                                                                                                                     
$ch = curl_init('http://api.local/rest/users');                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($data_string))                                                                       
);                                                                                                                   
                                                                                                                     
$result = curl_exec($ch);

All these settings are pretty well explained on the curl_setopt() page, but basically the idea is to set the request to be a POST request, set the json-encoded data to be the body, and then set the correct headers to describe that post body. The CURLOPT_RETURNTRANSFER is purely so that the response from the remote server gets placed in $result rather than echoed. If you’re sending JSON data with PHP, I hope this might help!

cURL Requests with PHP

Introduction

cURL allows transfer of data across a wide variety of protocols, and is a very powerful system. It’s widely used as a way to send data across websites, including things like API interaction and oAuth. cURL is unrestricted in what it can do, from the basic HTTP request, to the more complex FTP upload or interaction with an authentication enclosed HTTPS site. We’ll be looking at the simple difference between sending a GET and POST request and dealing with the returned response, as well as highlighting some useful parameters.

Basics

Before we can do anything with a cURL request, we need to first instantiate an instance of cURL – we can do this by calling the function curl_init();, which returns a cURL resource. This function takes one parameter which is the URL that you want to send the request to, however, in our case, we’ll hold off doing that for now and set it an alternatively way later.

Settings

Once we’ve got a cURL resource, we can begin to assign some settings, below is a list of some of the core ones that I set

  • CURLOPT_RETURNTRANSFER – Return the response as a string instead of outputting it to the screen
  • CURLOPT_CONNECTTIMEOUT – Number of seconds to spend attempting to connect
  • CURLOPT_TIMEOUT – Number of seconds to allow cURL to execute
  • CURLOPT_USERAGENT – Useragent string to use for request
  • CURLOPT_URL – URL to send request to
  • CURLOPT_POST – Send request as POST
  • CURLOPT_POSTFIELDS – Array of data to POST in request

We can set a setting by using the curl_setopt() method, which takes three parameters, the cURL resource, the setting and the value. So, to set the URL that we’re sending the request to as http://testcURL.com:

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://testcURL.com');

As mentioned, we can set the URL by sending a parameter through when getting the cURL resource:

$curl = curl_init('http://testcURL.com');

It is possible to set multiple settings at one time by passing through an array of settings and values to the function curl_setopt_array():

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'http://testcURL.com'
));

Sending request

When all of the options are sent, and the request is ready to send, we can call the curl_exec() method which will execute the cURL request. This function can return three different things:

  • false – if there is an error executing the request
  • true – if the request executed without error and CURLOPT_RETURNTRANSFER is set to false
  • The result – if the request executed without error and CURLOPT_RETURNTRANSFER is set to true

Using the previous example, where we are wanting to get the result back, we would use the following:

$result = curl_exec($curl);

With $result now containing the response from the page – which might be JSON, a string or a full blown site’s HTML.

Close Request

When you’ve sent a request and got the result back, you should look to close the cURL request so that you can free up some system resources, this is as simple as calling the curl_close() method which as with all other functions takes the resource as its parameter.

GET Request

A GET request is the default request method that is used, and is very straight forward to use, infact all of the examples so far have been GET requests. If you want to send parameters along in the request you simply append them to the URL as a query string such as http://testcURL.com/?item1=value&item2=value2.

So for example to send a GET request to the above URL and return the result we would use:

// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'http://testcURL.com/?item1=value&item2=value2',
    CURLOPT_USERAGENT => 'Codular Sample cURL Request'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);

POST Request

The sole difference between the POST and GET request syntax is the addition of one setting, two if you want to send some data. We’ll be setting CURLOPT_POST to true and sending an array of data through with the setting CURLOPT_POSTFIELDS

So for example switching the above GET request to be a POST request, we would use the following code:

// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'http://testcURL.com',
    CURLOPT_USERAGENT => 'Codular Sample cURL Request',
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => array(
        item1 => 'value',
        item2 => 'value2'
    )
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);

There you have a POST request that will work the same as our GET request above and return the response back to the script so that you can use it as you want.

Errors

As much as we all hate errors, you really need to take care to account for any eventuality with cURL as ultimately you will not have control over the site(s) that you are sending your request to, you cannot guarantee that the response will be in the format that you want, or that the site will even be available.

There are a few functions that you can use to handle errors and these are:

  • curl_error() – returns a string error message, will be blank '' if the request doesn’t fail.
  • curl_errno() – which will return the cURL error number which you can then look up on this page listing error codes.

An example usage would be:

if(!curl_exec($curl)){
    die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
}

You might want to look at using the setting CURLOPT_FAILONERROR as true if you want any HTTP response code greater than 400 to cause an error, instead of returning the page HTML.

curl_exec($theEnd);

cURL is a behemoth, and has many many possibilities. Some sites might only serve pages to some user agents, and when working with APIs, some might request you send a specfici user agent, this is something to be aware of.

 

Source:  http://codular.com/

Stripe Payment Integration & Development in Codeigniter

This blog gives an overview on integration of stripe payment service in Codeigniter.

There are two types of payment services we can integrate using stripe.

  • Recurring Payment.
  • One Time Payment.

First step is to create a stripe account. Use the below link to create an account.

https://dashboard.stripe.com/register

Once registered, confirm your email address using the activation link received in email. It will redirect you to a login page of stripe website. After login, you will be redirected to dashboard.

Recurring Payment

For this, we need to create a new subscription plan which will be used for recurring payment. To create a plan, click on Subscriptions from left menu -> Plans -> New. It will open a popup to create new plan as shown below.

CreateNewPlan

We need to provide details for the below fields.

ID: Used for recurring payment which can be numeric or alpha numeric.

Name: Name of your subscription plan.

Currency: Select currency in which we want to accept payments.

Amount: Amount for the subscription.

Interval: Select subscription period. There are seven options available like daily, monthly, yearly, weekly, every 3 months, every 6 months and custom. In custom, we can set our own subscription period by entering number and selecting period from drop down like month(s), week(s) or day(s).

Trial period days: This field is optional and it is used if we want to give subscription as a trial for mentioned day(s).

Statement description: A description of the payment plan which optional and appear on statement.

When someone pays for the subscription or does a recurring payment, it is mandatory to create a customer. We can create customer through a php code.

 

$card_data = array(

            ‘number’ => $this->input->post(‘card_number’),

            ‘cvc’ => $this->input->post(‘cvv’),

            ‘exp_month’ => $this->input->post(‘exp_month’),

            ‘exp_year’ => $this->input->post(‘exp_year’),

            ‘name’ => $this->input->post(’email’),

 );

 $dollars = str_replace(‘$’, ”, $this->input->post(‘amount’));

$cents = number_format((float)$dollars*100., 0, ‘.’, ”);   

$tokenArray = json_decode($this->stripe->card_token_create($card_data,$cent));

$stripeToken = $tokenArray->id;

$card = $stripeToken;

$email = $this->input->post(’email’);

$desc = $this->input->post(‘service_name’);

$plan = $this->input->post(‘plan_name’);

$customerCreateArray = json_decode($this->stripe->customer_create( $card, $email, $desc, $plan));

$customer_id = $customerCreateArray->id; //return inserted customer id

 

How to integrate stripe payment gateway in codeigniter?

We need to create a basic view file which will accept the required data from the user like card number, card expiry month, card expiry year, card CVV number etc.

We need to mention controllerMethodName in the action of the form as shown below.

<form action=”controllerMethodName” method=”post”>

         

                  

Stripe Payment

                   $ 11.50

                  

                            

                                     

Card Number

                                     

                                     

                            

                            

                                     

Email Address

                                     

                            

                  

                            

                                     

Exp. Month

                                     

                            

                            

                                     

Exp. Year

                                     

                            

                            

                                     

CVV

                                     

                            

                            

                                      Pay Now

                            

                   </div>

          </div> 

</form>

To integrate stripe payment gateway, we need two files. One is the library file and another is the configuration file. Both these files can be downloaded from the below URL.

https://github.com/chrismackie28/php-stripe

After downloading the zip file from the above URL, we will get two files: one is README.md and another is Stripe.php

We need to create one configuration file and put it in codeigniter’s application/config/stripe.php and put the following configurations.

// Configuration options

$config[‘stripe_key_test_public’]         = ”;

$config[‘stripe_key_test_secret’]         = ”;

$config[‘stripe_key_live_public’]         = ”;

$config[‘stripe_key_live_secret’]         = ”;

$config[‘stripe_test_mode’]               = TRUE;

$stripe = new Stripe( $config ); // Create the library object

Copy the above code and save it as stripe.php in config folder so the path of this file will be like: <PROJECT_FOLDER>/application/config/stripe.php

Stripe.php file will be placed in our codeigniter’s application/libraries folder, so the path of the Stripe.php file is like: <PROJECT_FOLDER>/application/libraries/Stripe.php

The basic functions are defined in the Stripe.php.

Steps to integrate stripe in Codeigniter

Include library file

$this->load->library(‘stripe’);

Recurring Payment Code

Below piece of code is used to create a card token

$card_data = array(

          ‘number’ => $this->input->post(‘card_number’),

          ‘cvc’ => $this->input->post(‘cvv’),

          ‘exp_month’ => $this->input->post(‘exp_month’),

          ‘exp_year’ => $this->input->post(‘exp_year’),

          ‘name’ => $this->input->post(’email’),

);

$dollars = $this->input->post(‘amount’);

$cents = number_format((float)$dollars*100., 0, ‘.’, ”); // convert dollar to cent

$tokenArray = json_decode($this->stripe->card_token_create($card_data,$cents));

$stripeToken = $tokenArray->id;

NOTE: We need to convert the amount into cents because stripe accept payment in cents. (e.g. $2.5 = 250cents)

We need to create a customer using below piece of code.

$card = $stripeToken;

$email = $this->input->post(’email’);

$desc = $this->input->post(‘description’);

$plan = $this->input->post(‘plan_id’);

$customerCreateArray = json_decode($this->stripe->customer_create( $card, $email, $desc, $plan));

$customer_id = $customerCreateArray->id;

$amount =  $cents;

$card = $card_data;

$desc = $this->input->post(‘description’);

$payWithStripe = json_Decode($this->stripe->charge_card($amount, $card, $desc));

We need to store the data into database and get the transaction id.

$transaction_id = $payWithStripe->id;

To cancel the subscription, use the below code.

$customer_id = $this->input->post(‘customer_id’);

$result = json_decode($this->stripe->customer_unsubscribe($customer_id,true));

$cancel_date = $result->current_period_end;

In the above function if we pass true then the subscription will be cancel at the end of the subscription period and if we pass it false then subscription will cancel immediately.

One Time Payment

Code is same as the recurring payment code. The only change is that it is not necessary to create a customer for onetime payment in stripe.

One Time Payment Code

Below piece of code is used to create a card token

$card_data = array(

          ‘number’ => $this->input->post(‘card_number’),

          ‘cvc’ => $this->input->post(‘cvv’),

          ‘exp_month’ => $this->input->post(‘exp_month’),

          ‘exp_year’ => $this->input->post(‘exp_year’),

          ‘name’ => $this->input->post(’email’),

);

$dollars = $this->input->post(‘amount’);

$cents = number_format((float)$dollars*100., 0, ‘.’, ”); // convert dollar to cent

$tokenArray = json_decode($this->stripe->card_token_create($card_data,$cents));

$stripeToken = $tokenArray->id;

$amount =  $cents;

$card = $card_data;

$desc = $this->input->post(‘description’);

$payWithStripe = json_Decode($this->stripe->charge_card($amount, $card, $desc));

 

We need to store the data into database and get the transaction id.

 

$transaction_id = $payWithStripe->id;

How to zip, save and download a file in codeigniter

In this article we are going to see how to zip, save, download a file in codeigniter PHP framework. codeigniter is a very popular PHP framework.  Codeigniter framework you can do many tasks very easily. Compressing and downloading or saving can be done very easily.

Zip Encoding Class

Zip class is used to create and download archives.  In controller you can initialize the zip class using

$this->load->library('zip');

After loading the library we can use the zip object.

$this->zip

 Zip, Save and Download a file

The code snippet below shows how to create a zip file, save it and download it.

$filename = 'example.txt';

$filedata = 'This is an example file. Codeigniter zip class is used to zip, save and download the file';

$this->zip->add_data($filename, $filedata);

//Write the zip file to a folder on server with name. "example_backup.zip"

$this->zip->archive('/images/example_backup.zip');

//Download the file to system. Name it "my_backup.zip"
$this->zip->download('example_backup.zip');

Adding Controller in CodeIgniter

So if you want to zip, save, download a file in codeigniter then you have to do following

1. In Controller folder, Add a controller file and name it as, “Zip.php”2. Add a folder named “zippedfiles” in root folder.

3. Add the code below to the Zip.php file. 4. Run the code, a zip file is created and downloaded to your computer

Codeigniter controller code

<?php
    
  defined('BASEPATH') OR exit('No direct script access allowed');

  class Zip extends CI_Controller {

        public function __construct()
        {
            parent::__construct();
            $this->load->library('zip');
        }

        public function index()
        {
        
            $filename = 'example.txt';
            $filedata = 'This is an example file. Codeigniter zip class is 
                         used to zip, save and download the file';

            $this->zip->add_data($filename, $filedata); 
            
            //Create zip file on server with name."example_backup.zip"
            $this->zip->archive('/zippedfiles/example_backup.zip');  

            //Download the file to your system. It will be named "example_backup.zip"
            $this->zip->download('example_backup.zip');
        }
    }

Code Explanation

In code above We have created a class named Zip that extends CI_Controller. Inside constructor, that runs each time when a class object is created.  After calling parent constructor, we load zip library.

Inside index action we create a variable name $filename and a $filedata with content.

add_data method

$this->zip->add_data($filename, $filedata);

Zip object’s add_data method is called with $filename and $filedata params.

archive method

$this->zip->archive('/zippedfiles/example_backup.zip');  

The code above, archive method of zip object saves file to a specified path.

download method

$this->zip->download('example_backup.zip');

Finally the download method of zip class object downloads file to user’s computer.  The code above can be used in any of your project to zip and download zip archives.

 

source: https://programmerblog.net/