blib/lib/Net/API/Stripe/WebHook/Apache.pm

filter: Statementstmt 100% 6 / 6 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 2 / 2 Podpod n/a totaltotal 100% 8 / 8 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
↑ Summary
1 ##----------------------------------------------------------------------------
2 ## A Stripe WebHook Implementation using Apache - ~/lib/Net/API/Stripe/WebHook/Apache.pm
3 ## Version v0.100.1
4 ## Copyright(c) 2020 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <@sitael.tokyo.deguest.jp>
6 ## Created 2019/11/02
7 ## Modified 2020/05/21
8 ##
9 ##----------------------------------------------------------------------------
10 package Net::API::Stripe::WebHook::Apache;
11 BEGIN
12 {
13 1 ▶ use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶ use parent qw( Net::API::REST );
Subroutine BEGIN: called CC=1 SCAR=0.0
15 use Net::API::Stripe::Event;
16 use Nice::Try;
17 use Devel::Confess;
18 ## use Apache2::Const -compile => qw( :common :http DECLINED );
19 eval
20 {
21 require Apache2::Const;
22 Apache2::Const->import( 'compile', qw( :common :http DECLINED ) );
23 };
24 die( $@ ) if( $@ );
25 use constant MAX_PAYLOAD_SIZE => 524288;
26 our $VERSION = 'v0.100.1';
27 };
28  
29 sub handler
30 {
31 ## https://perl.apache.org/docs/2.0/user/handlers/http.html#HTTP_Request_Handler_Skeleton
32 my( $class, $r ) = @_;
33 ## $r->log_error( "Net::API::Stripe::WebHook::Apache(): Got here with Apache object '$r'." );
34 return( DECLINED ) if( !$r );
35 my $req = Net::API::REST::Request->new( $r );
36 ## $r->log_error( "Got here after getting a Net::API::REST::Request object." );
37 ## An error has occurred
38 if( !defined( $req ) )
39 {
40 return( 500 );
41 }
42 my $resp = Net::API::REST::Response->new( request => $req );
43 my $self = $class->new;
44 $self->request( $req );
45 $self->response( $resp );
46 my $sig = $self->request->headers( 'Stripe-Signature' );
47 my $q = $self->request->params;
48 my $payload = {};
49 if( $self->request->content_type =~ /^application\/json/i )
50 {
51 $self->message( 3, "Receiving Stripe data as application/json" );
52 if( $self->request->content_length > MAX_PAYLOAD_SIZE )
53 {
54 return( $self->reply( Apache2::Const::HTTP_REQUEST_ENTITY_TOO_LARGE, { message => sprintf( "Payload of %d bytes exceeds our limit", $self->request->content_length ) } ) );
55 }
56 my $buff = '';
57 $self->request->read( $buff, $self->request->content_length );
58 $self->message( 2, "Payload read from server is: '$buff'. Decoding it" );
59 my $payload = $self->decode_json( $buff );
60 if( !length( $payload ) )
61 {
62 return( $self->reply( Apache2::Const::HTTP_BAD_REQUEST, { message => "Malformed json error" }) );
63 }
64 }
65 else
66 {
67 return( $self->reply( Apache2::Const::HTTP_BAD_REQUEST, { message => sprintf( "I was expecting http request type of application/json, but received %s", $self->request->content_type ) }) );
68 }
69 ## Don't wait, reply ok back to Stripe so our request does not time out
70 $self->response->code( Apache2::Const::HTTP_OK );
71 my $json = $self->json->utf8->encode({ code => 200, success => \1 });
72 $self->response->print( $json );
73 $self->response->rflush;
74 $self->request->socket->close;
75
76 ## Net::API::Stripe object
77 my $stripe = $self->stripe || return( $self->error( "No Stripe object set up. You need to properly initiate a Net::API::Stripe object in your $class module." ) );
78
79 my $stripe_event;
80 try
81 {
82 $stripe_event = Net::API::Stripe::Event->new({
83 '_parent' => $stripe,
84 '_debug' => $stripe->{debug},
85 '_dbh' => $stripe->{_dbh},
86 }, $payload );
87 }
88 catch( $e )
89 {
90 return( $self->error( "Unable to initiate a Net::API::Stripe::Event object: $e" ) );
91 }
92 return( $self->pass_error( Net::API::Stripe::Event->error ) ) if( !defined( $stripe_event ) );
93 my $stripe_handler = $self->event_handler( $stripe_event->type );
94 return( $self->reply( Apache2::Const::HTTP_NOT_IMPLEMENTED, { message => "No function implemented to handle event of type \"", $stripe_event->type, "\"." }) );
95 my $rc = $stripe_handler->( $stripe_event );
96 if( !defined( $rc ) )
97 {
98 return( Apache2::Const::HTTP_INTERNAL_SERVER_ERROR );
99 }
100 elsif( $rc == 1 || $rc == Apache2::Const::HTTP_OK )
101 {
102 return( Apache2::Const::OK );
103 }
104 else
105 {
106 return( $rc );
107 }
108 }
109  
110 sub event_handler
111 {
112 my $self = shift( @_ );
113 ## e.g. invoice.created or charge.refunded
114 ## See the list of all events here: https://stripe.com/docs/api/events/types
115 my $type = shift( @_ );
116 my $routes = $self->event_handlers || return( $self->error( "No event handlers map is set up. You need to set up a hash \"event_handlers\" pointing to each sub routine that handle Stripe events like { account => { updated => \&account_updated } }" ) );
117 return( $self->error( "Event handlers set in this object is not an hash reference." ) ) if( ref( $routes ) ne 'HASH' );
118 return( $self->error( "Event handlers hash found, but no event hadnlers set up. It's empty!" ) ) if( !scalar( keys( %$routes ) ) );
119 my $parts = split( /\./, $type );
120 local $check = sub
121 {
122 my( $pos, $subroutes ) = @_;
123 my $part = $parts->[ $pos ];
124 if( exists( $subroutes->{ lc( $part ) } ) )
125 {
126 $part = lc( $part );
127 ## Code reference
128 if( ref( $subroutes->{ $part } ) eq 'CODE' )
129 {
130 return( $subroutes->{ $part } );
131 }
132 ## path part has sub component, so we look for a key _handler in the sub hash
133 elsif( ref( $subroutes->{ $part } ) eq 'HASH' )
134 {
135 my $ref = $subroutes->{ $part };
136 return( $self->error( "I was expecting a code reference to handle this event \"$part\", but instead found a hash reference. It seems there is a misconfiguration." ) ) if( $pos == $#$parts );
137 return( $check->( $pos + 1, $ref ) );
138 }
139 ## Not a code or a hash reference, so it has got to be a package name
140 elsif( $subroutes->{ $part } =~ /^([^\-]+)\-\>(\S+)$/ )
141 {
142 my( $cl, $meth ) = ( $1, $2 );
143 try
144 {
145 ## https://stackoverflow.com/questions/32608504/how-to-check-if-perl-module-is-available#comment53081298_32608860
146 require $cl unless( defined( *{"${cl}::"} ) );
147 my $o = $cl->new( request => $req, response => $resp ) || return( $self->pass_error( $cl->error ) );
148 my $code = $o->can( $meth );
149 return( $self->error({ code => 500, message => "Class \"$cl\" does not have a method \"$meth\"." }) ) if( !$code );
150 return( sub{ $code->( $o, api => $self, @_ ) } );
151 }
152 catch( $e )
153 {
154 return( $self->error({ code => 500, message => $e }) );
155 }
156 }
157 else
158 {
159 return( $self->error({ code => 500, message => "Found an entry for path part \"$part\" ($subroutes->{ $part }), but I do not know what to do with it. If this was supposed to be a package, the syntax needs to be My::Package->my_sub" }) );
160 }
161 }
162 ## Empty means not found
163 else
164 {
165 return( $self->error( "No event handler found for \"$part\"." ) );
166 }
167 };
168 my $sub = $check->( 0, $routes ) || return( undef() );
169 return( $sub );
170 }
171  
172 sub event_handlers { return( shift->_set_get_hash( 'event_handlers', @_ ) ); }
173  
174 sub stripe { return( shift->_set_get_object( 'stripe', 'Net::API::Stripe', @_ ) ); }
175  
176 1;
177  
178 __END__
179  
180 =encoding utf8
181  
182 =head1 NAME
183  
184 Net::API::Stripe::WebHook::Apache - An Apache handler for Stripe Web Hook
185  
186 =head1 SYNOPSIS
187  
188 package My::Module::WebHook;
189 BEGIN
190 {
191 use strict;
192 use curry;
193 use parent qw( Net::API::Stripe::WebHook::Apache );
194 };
195
196 sub init
197 {
198 my $self = shift( @_ );
199 $self->{event_handlers} =
200 {
201 account => { updated => $self->curry::account_updated,
202 # etc..
203 # See here for a list of Stripe events:
204 # https://stripe.com/docs/api/events/types
205 };
206 }
207  
208 =head1 VERSION
209  
210 v0.100.1
211  
212 =head1 DESCRIPTION
213  
214 This is the module to handle Stripe Web Hooks using Apache/mod_perl configuration
215  
216 The way this works is you create your own module which inherits from this one. You override the init method in which you create the object property I<event_handler> with an hash value with keys corresponding to the types of Stripe events. A dot in the Stripe event type corresponds to a sub hash in our I<event_handler> definition.
217  
218 When an http query is made by Stripe on your webhook, Apache will trigger the method B<handler>, which will check and create the object environment, and call the method B<event_handler> provided by this package to find out the sub in charge of this Stripe event type, as defined in your map I<event_handlers>. You own method is then called and you can do whatever you want with Stripe data.
219  
220 It is also worth mentioning that Stripe requires ssl to be enabled to perform webhook queries.
221  
222 =head1 CONFIGURATION
223  
224 Your Apache VirtualHost configuration would look something like this, assuming your module package is C<My::Module::WebHook>
225  
226 <VirtualHost *:443>
227 ServerName example.com:443
228 ServerAdmin www@example.com
229 DocumentRoot /home/john/example.com
230 DirectoryIndex "index.html" "index.php"
231 CustomLog "${APACHE_LOG_DIR}/example.com-access.log" combined
232 ErrorLog "${APACHE_LOG_DIR}/example.com-error.log"
233 LogLevel warn
234 <Directory "/home/john/example.com">
235 Options All +MultiViews -ExecCGI -Indexes +Includes +FollowSymLinks
236 AllowOverride All
237 </Directory>
238 ScriptAlias "/cgi-bin/" "/home/john/example.com/cgi-bin/"
239 <Directory "/home/john/example.com/cgi-bin/">
240 Options All +Includes +ExecCGI -Indexes -MultiViews
241 AllowOverride All
242 SetHandler cgi-script
243 AcceptPathInfo On
244 Require all granted
245 </Directory>
246 <IfModule mod_perl.c>
247 PerlOptions +GlobalRequest
248 PerlPassEnv MOD_PERL
249 PerlPassEnv PATH_INFO
250 PerlModule Apache2::Request
251 <Perl>
252 unshift( @INC, "/home/john/lib" );
253 </Perl>
254 <Location /hook>
255 SetHandler perl-script
256 ## Switch it back to modperl once the soft is stable
257 # SetHandler modperl
258 PerlSendHeader On
259 PerlSetupEnv On
260 PerlOptions +GlobalRequest
261 # PerlResponseHandler Net::API::Stripe::WebHook::Apache
262 PerlResponseHandler My::Module::WebHook
263 Options +ExecCGI
264 Order allow,deny
265 Allow from all
266 </Location>
267 </IfModule>
268  
269 SSLCertificateFile /etc/letsencrypt/live/example.com/cert.pem
270 SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
271 Include /etc/letsencrypt/options-ssl-apache.conf
272 SSLCertificateChainFile /etc/letsencrypt/live/example.com/chain.pem
273 </Virtualhost>
274  
275 The key part is the line with C<PerlResponseHandler> and value L<Net::API::Stripe::WebHook::Apache>. This will tell Apache/mod_perl that our module will handle all http request for this particular location.
276  
277 So, if we get an incoming event from Stripe at https://example.com/hook/d18bbab7-e537-4dba-9a1f-dd6cc70ea6c1, we receive C<d18bbab7-e537-4dba-9a1f-dd6cc70ea6c1> as part of the path info, and we call B<validate_webhook>() to validate it before processing the event incoming packet.
278  
279 Apache will call our special method B<handler>(), which will invoque B<validate_webhook>() that should be overriden by your module, and which must return either true or false. Upon successful return from B<validate_webhook>(), B<handler> will create a new constructor such as $class->new()
280  
281 What you want to do is inherit L<Net::API::Stripe::WebHook::Apache> and set your own module in Apache configuration, like so:
282  
283 PerlResponseHandler My::WebHookHandler
284  
285 The inherited handler will be called by Apache with the class My::WebHookHandler and the apache Apache2::RequestRec object. As we wrote above, once validated, B<handler> will initiate an object from your module by calling C<My::WebHookHandler->new( object => L<Net::API::Stripe::Event>, request => L<Net::API::REST::Request>, response => L<Net::API::REST::Response> )> where each package name are an object. C<object> represents the event packet received from Stripe. C<request> is an object to access great number of method to access the Apache API, and C<response> is an object to access Apache API to provide a reply. See the manual page for each of those package.
286  
287 =head1 CONSTRUCTOR
288  
289 =over 4
290  
291 =item B<new>( %args )
292  
293 Creates a new L<Net::API::Stripe::WebHook::Apache> object. This should be overriden by your own package.
294  
295 =over 4
296  
297 =item I<object> Net::API::Stripe::Event object
298  
299 =item I<request> Net::API::REST::Request
300  
301 =item I<request> Net::API::REST::Response
302  
303 =back
304  
305 =item B<handler>( $class, $r )
306  
307 This is called by Apache/mod_perl upon incoming http request
308  
309 =back
310  
311 =head1 METHODS
312  
313 =over 4
314  
315 =item handler( $r )
316  
317 This is called by Apache with an L<Apache2::Request> object and returns an L<Apache2::Constant> code such as 200
318  
319 =item B<event_handler>( Stripe event type )
320  
321 Provided with a Stripe event type, this checks for a suitable handler (set up in your B<init> method), then return the handler code reference.
322  
323 ~item B<event_handlers>
324  
325 Set/get an hash reference of Stripe event type to handling methods.
326  
327 Returns an hash reference.
328  
329 =item B<stripe>
330  
331 Set/get a L<Net::API::Stripe> object. It returns the current value.
332  
333 =back
334  
335 =head1 HISTORY
336  
337 =head2 v0.1
338  
339 Initial version
340  
341 =head1 AUTHOR
342  
343 Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>
344  
345 =head1 SEE ALSO
346  
347 Stripe API documentation: L<https://stripe.com/docs/api/events/types>
348  
349 L<Net::API::REST>, L<Apache2>
350  
351 L<ModPerl::Registry>, L<ModPerl::PerlRun>, L<http://perl.apache.org/>
352  
353 =head1 COPYRIGHT & LICENSE
354  
355 Copyright (c) 2019-2020 DEGUEST Pte. Ltd.
356  
357 You can use, copy, modify and redistribute this package and associated
358 files under the same terms as Perl itself.
359  
360 =cut
↑ Summary