| 1 | ##---------------------------------------------------------------------------- | ||
| 2 | ## A Stripe WebHook Implementation using Apache - ~/lib/Net/API/Stripe/WebHook/Apache.pm | ||
| 3 | ## Version v0.100.2 | ||
| 4 | ## Copyright(c) 2020 DEGUEST Pte. Ltd. | ||
| 5 | ## Author: Jacques Deguest <@sitael.tokyo.deguest.jp> | ||
| 6 | ## Created 2019/11/02 | ||
| 7 | ## Modified 2020/05/28 | ||
| 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.2'; | ||
| 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 | ## Returning an hash reference with properties: payload, headers, remote_addr, remote_host | ||
| 47 | my $q = $self->request->params; | ||
| 48 | my $check_ref = $self->validate_webhook || | ||
| 49 | return( $self->reply({ code => $self->error->code, message => $self->error->message }) ); | ||
| 50 | return( $self->reply({ code => Apache2::Const::HTTP_INTERNAL_SERVER_ERROR, message => "I was expecting an hash reference from validate_webhook() but got \"$check_ref\" instead." }) ) if( !$self->_is_hash( $check_ref ) ); | ||
| 51 | ## This is the json decoded payload | ||
| 52 | my $payload = $check_ref->{payload} || return( $self->reply({ code => Apache2::Const::HTTP_INTERNAL_SERVER_ERROR, message => "No payload property found in hash reference returned frm validate_webhook()" }) ); | ||
| 53 | return( $self->reply({ code => Apache2::Const::HTTP_INTERNAL_SERVER_ERROR, message => "I as expecting payload to be an hash reference, but instead got \"$payload\"" }) ) if( !$self->_is_hash( $payload ) ); | ||
| 54 | |||
| 55 | if( !scalar( keys( %$payload ) ) ) | ||
| 56 | { | ||
| 57 | return( $self->reply({ code => Apache2::Const::HTTP_BAD_REQUEST, message => "Malformed json error" }) ); | ||
| 58 | } | ||
| 59 | ## Don't wait, reply ok back to Stripe so our request does not time out | ||
| 60 | $self->response->code( Apache2::Const::HTTP_OK ); | ||
| 61 | ## the \1 is for JSON encoder to transform a perl true value into a JSON 'true' one | ||
| 62 | my $json = $self->json->utf8->encode({ code => 200, success => \1 }); | ||
| 63 | $self->response->print( $json ); | ||
| 64 | $self->response->rflush; | ||
| 65 | $self->request->socket->close; | ||
| 66 | |||
| 67 | ## Net::API::Stripe object | ||
| 68 | my $stripe = $self->stripe || return( $self->reply({ code => Apache2::Const::HTTP_INTERNAL_SERVER_ERROR, message => "No Stripe object set up. You need to properly initiate a Net::API::Stripe object in your $class module." }) ); | ||
| 69 | |||
| 70 | my $stripe_event; | ||
| 71 | try | ||
| 72 | { | ||
| 73 | $stripe_event = Net::API::Stripe::Event->new({ | ||
| 74 | '_parent' => $stripe, | ||
| 75 | '_debug' => $stripe->{debug}, | ||
| 76 | '_dbh' => $stripe->{_dbh}, | ||
| 77 | }, $payload ); | ||
| 78 | } | ||
| 79 | catch( $e ) | ||
| 80 | { | ||
| 81 | return( $self->reply({ code => Apache2::Const::HTTP_INTERNAL_SERVER_ERROR, message => "Unable to initiate a Net::API::Stripe::Event object: $e" }) ); | ||
| 82 | } | ||
| 83 | return( $self->reply({ code => Apache2::Const::HTTP_INTERNAL_SERVER_ERROR, message => Net::API::Stripe::Event->error }) ) if( !defined( $stripe_event ) ); | ||
| 84 | my $handlers = $self->event_handlers; | ||
| 85 | my $stripe_handler; | ||
| 86 | $stripe_handler = $self->event_handler( $stripe_event->type ) || do | ||
| 87 | { | ||
| 88 | if( CORE::exists( $handlers->{fallback} ) ) | ||
| 89 | { | ||
| 90 | if( CORE::ref( $handlers->{fallback} ) eq 'CODE' ) | ||
| 91 | { | ||
| 92 | $stripe_handler = $handlers->{fallback}; | ||
| 93 | } | ||
| 94 | else | ||
| 95 | { | ||
| 96 | return( $self->reply({ code => Apache2::Const::HTTP_INTERNAL_SERVER_ERROR, message => "Fallback method provided is not a subroutine reference." }) ); | ||
| 97 | } | ||
| 98 | } | ||
| 99 | else | ||
| 100 | { | ||
| 101 | return( $self->reply({ code => Apache2::Const::HTTP_NOT_IMPLEMENTED, message => "No function implemented to handle event of type \"", $stripe_event->type, "\"." }) ); | ||
| 102 | } | ||
| 103 | }; | ||
| 104 | |||
| 105 | my $rc = $stripe_handler->( $stripe_event ); | ||
| 106 | if( !defined( $rc ) ) | ||
| 107 | { | ||
| 108 | return( Apache2::Const::HTTP_INTERNAL_SERVER_ERROR ); | ||
| 109 | } | ||
| 110 | elsif( $rc == 1 || $rc == Apache2::Const::HTTP_OK ) | ||
| 111 | { | ||
| 112 | return( Apache2::Const::OK ); | ||
| 113 | } | ||
| 114 | else | ||
| 115 | { | ||
| 116 | return( $rc ); | ||
| 117 | } | ||
| 118 | } | ||
| 119 | |||
| 120 | sub event_handler | ||
| 121 | { | ||
| 122 | my $self = shift( @_ ); | ||
| 123 | ## e.g. invoice.created or charge.refunded | ||
| 124 | ## See the list of all events here: https://stripe.com/docs/api/events/types | ||
| 125 | my $type = shift( @_ ); | ||
| 126 | 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 } }" ) ); | ||
| 127 | return( $self->error( "Event handlers set in this object is not an hash reference." ) ) if( ref( $routes ) ne 'HASH' ); | ||
| 128 | return( $self->error( "Event handlers hash found, but no event hadnlers set up. It's empty!" ) ) if( !scalar( keys( %$routes ) ) ); | ||
| 129 | my $parts = split( /\./, $type ); | ||
| 130 | local $check = sub | ||
| 131 | { | ||
| 132 | my( $pos, $subroutes ) = @_; | ||
| 133 | my $part = $parts->[ $pos ]; | ||
| 134 | if( exists( $subroutes->{ lc( $part ) } ) ) | ||
| 135 | { | ||
| 136 | $part = lc( $part ); | ||
| 137 | ## Code reference | ||
| 138 | if( ref( $subroutes->{ $part } ) eq 'CODE' ) | ||
| 139 | { | ||
| 140 | return( $subroutes->{ $part } ); | ||
| 141 | } | ||
| 142 | ## path part has sub component, so we look for a key _handler in the sub hash | ||
| 143 | elsif( ref( $subroutes->{ $part } ) eq 'HASH' ) | ||
| 144 | { | ||
| 145 | my $ref = $subroutes->{ $part }; | ||
| 146 | 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 ); | ||
| 147 | return( $check->( $pos + 1, $ref ) ); | ||
| 148 | } | ||
| 149 | ## Not a code or a hash reference, so it has got to be a package name | ||
| 150 | elsif( $subroutes->{ $part } =~ /^([^\-]+)\-\>(\S+)$/ ) | ||
| 151 | { | ||
| 152 | my( $cl, $meth ) = ( $1, $2 ); | ||
| 153 | try | ||
| 154 | { | ||
| 155 | ## https://stackoverflow.com/questions/32608504/how-to-check-if-perl-module-is-available#comment53081298_32608860 | ||
| 156 | require $cl unless( defined( *{"${cl}::"} ) ); | ||
| 157 | my $o = $cl->new( request => $self->request, response => $self->response ) || return( $self->pass_error( $cl->error ) ); | ||
| 158 | my $code = $o->can( $meth ); | ||
| 159 | return( $self->error({ code => 500, message => "Class \"$cl\" does not have a method \"$meth\"." }) ) if( !$code ); | ||
| 160 | return( sub{ $code->( $o, api => $self, @_ ) } ); | ||
| 161 | } | ||
| 162 | catch( $e ) | ||
| 163 | { | ||
| 164 | return( $self->error({ code => 500, message => $e }) ); | ||
| 165 | } | ||
| 166 | } | ||
| 167 | else | ||
| 168 | { | ||
| 169 | 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" }) ); | ||
| 170 | } | ||
| 171 | } | ||
| 172 | ## Empty means not found | ||
| 173 | else | ||
| 174 | { | ||
| 175 | return( $self->error( "No event handler found for \"$part\"." ) ); | ||
| 176 | } | ||
| 177 | }; | ||
| 178 | my $sub = $check->( 0, $routes ) || return( undef() ); | ||
| 179 | return( $sub ); | ||
| 180 | } | ||
| 181 | |||
| 182 | sub event_handlers { return( shift->_set_get_hash( 'event_handlers', @_ ) ); } | ||
| 183 | |||
| 184 | sub ignore_ip { return( shift->_set_get_boolean( 'ignore_ip', @_ ) ); } | ||
| 185 | |||
| 186 | sub stripe { return( shift->_set_get_object( 'stripe', 'Net::API::Stripe', @_ ) ); } | ||
| 187 | |||
| 188 | sub validate_webhook | ||
| 189 | { | ||
| 190 | my $self = shift( @_ ); | ||
| 191 | return( $self->error({ code => Apache2::Const::HTTP_INTERNAL_SERVER_ERROR, message => 'validate_webhook must be called with a class object' }) ) if( !ref( $self ) ); | ||
| 192 | my $class = ref( $self ); | ||
| 193 | my $signing_secret = $self->{signing_secret} || | ||
| 194 | return( $self->error({ code => Apache2::Const::HTTP_INTERNAL_SERVER_ERROR, message => "No signing secret key was specified to verify webhook incoming queries." }) ); | ||
| 195 | my $max_time_spread = ( 5 * 60 ); | ||
| 196 | my $remote_ip = $self->request->remote_ip; | ||
| 197 | my $sig = $self->request->headers( 'Stripe-Signature' ); | ||
| 198 | return( $self->error({ code => Apache2::Const::HTTP_BAD_REQUEST, message => "No signature found" }) ) if( !CORE::length( $sig ) ); | ||
| 199 | |||
| 200 | if( $self->request->content_type =~ /^application\/json/i ) | ||
| 201 | { | ||
| 202 | $self->message( 3, "Receiving Stripe data as application/json" ); | ||
| 203 | if( $self->request->content_length > MAX_PAYLOAD_SIZE ) | ||
| 204 | { | ||
| 205 | return( $self->error({ code => Apache2::Const::HTTP_REQUEST_ENTITY_TOO_LARGE, message => sprintf( "Payload of %d bytes exceeds our limit", $self->request->content_length ) } ) ); | ||
| 206 | } | ||
| 207 | } | ||
| 208 | else | ||
| 209 | { | ||
| 210 | return( $self->error({ code => Apache2::Const::HTTP_BAD_REQUEST, message => sprintf( "I was expecting http request type of application/json, but received %s", $self->request->content_type ) }) ); | ||
| 211 | } | ||
| 212 | |||
| 213 | my $payload = $self->request->data || return( $self->error({ code => Apache2::Const::HTTP_BAD_REQUEST, message => "No payload data received from the client." }) ); | ||
| 214 | |||
| 215 | my $stripe = $self->stripe || return( $self->error({ code => Apache2::Const::HTTP_INTERNAL_SERVER_ERROR, message => "No Stripe object set up. You need to properly initiate a Net::API::Stripe object in your $class module." }) ); | ||
| 216 | ## Do an IP source check to be sure this is Stripe talking to us | ||
| 217 | if( !defined( my $ip_check = $stripe->webhook_validate_caller_ip({ ip => $remote_ip, ignore_ip => $self->ignore_ip }) ) ) | ||
| 218 | { | ||
| 219 | return( $self->error({ code => $stripe->error->code, message => $stripe->error->message }) ); | ||
| 220 | } | ||
| 221 | ## Now, we make sure this is Stripe sending this by checking the signature of the payload | ||
| 222 | my $check = $stripe->webhook_validate_signature({ | ||
| 223 | secret => $signing_secret, | ||
| 224 | signature => $sig, | ||
| 225 | payload => $payload, | ||
| 226 | time_tolerance => $max_time_spread, | ||
| 227 | }); | ||
| 228 | if( !defined( $check ) ) | ||
| 229 | { | ||
| 230 | return( $self->error({ code => Apache2::Const::HTTP_BAD_REQUEST, message => "Check failed: " . $stripe->error }) ); | ||
| 231 | } | ||
| 232 | |||
| 233 | my $payload_ref = {}; | ||
| 234 | try | ||
| 235 | { | ||
| 236 | $payload_ref = $self->json->relaxed->decode( $payload ); | ||
| 237 | } | ||
| 238 | catch( $e ) | ||
| 239 | { | ||
| 240 | $self->message( 3, "Error decoding event json data. Error was: $e" ); | ||
| 241 | return( $self->error({ code => Apache2::Const::HTTP_BAD_REQUEST, message => "Malformed json error" }) ); | ||
| 242 | } | ||
| 243 | |||
| 244 | my $headers = $self->request->headers_as_hashref; | ||
| 245 | my $hash = | ||
| 246 | { | ||
| 247 | payload => $payload_ref, | ||
| 248 | headers => $headers, | ||
| 249 | remote_addr => $remote_ip, | ||
| 250 | remote_host => $self->request->remote_host, | ||
| 251 | }; | ||
| 252 | return( $hash ); | ||
| 253 | } | ||
| 254 | |||
| 255 | 1; | ||
| 256 | |||
| 257 | __END__ | ||