billing event to call web services, RT#35167
[freeside.git] / FS / FS / part_event / Action / http.pm
1 package FS::part_event::Action::http;
2
3 use strict;
4 use base qw( FS::part_event::Action );
5 use LWP::UserAgent;
6 use HTTP::Request::Common;
7 use JSON::XS;
8 use FS::Misc::DateTime qw( iso8601 );
9
10 #sub description { 'Send an HTTP or HTTPS GET or POST request'; }
11 sub description { 'Send an HTTP or HTTPS POST request'; }
12
13 sub eventtable_hashref {
14   { 'cust_bill' => 1,
15     'cust_pay'  => 1,
16   },
17 }
18
19 sub option_fields {
20   (
21     'method'        => { label => 'Method',
22                          type  => 'select',
23                          options => [qw( POST )], #GET )],
24                        },
25     'url'           => { label => 'URL',
26                          type  => 'text',
27                          size  => 120,
28                        },
29     'ssl_no_verify' => { label => 'Skip SSL certificate validation',
30                          type  => 'checkbox',
31                        },
32     'encoding'      => { label => 'Encoding',
33                          type  => 'select',
34                          options => [qw( JSON )], #XML, Form, etc.
35                        },
36     'content'       => { label => 'Content', #nneed better inline docs on format
37                          type  => 'textarea',
38                        },
39     #'response_error_param' => 'Response error parameter',
40   );
41 }
42
43 sub default_weight { 57; }
44
45 our %content_type = (
46   'JSON' => 'application/json',
47 );
48
49 sub do_action {
50   my( $self, $object ) = @_;
51
52   my $cust_main = $self->cust_main($object);
53
54   my %content =
55     map {
56       /^\s*(\S+)\s+(.*)$/ or /()()/;
57       my( $field, $value_expression ) = ( $1, $2 );
58       my $value = eval $value_expression;
59       die $@ if $@;
60       ( $field, $value );
61     } split(/\n/, $self->option('content') );
62
63   my $content = encode_json( \%content );
64
65   my @lwp_opts = ();
66   push @lwp_opts, 'ssl_opts'=>{ 'verify_hostname'=>0 }
67     if $self->option('ssl_no_verify');
68   my $ua = LWP::UserAgent->new(@lwp_opts);
69
70   my $req = HTTP::Request::Common::POST(
71     $self->option('url'),
72     Content_Type => $content_type{ $self->option('encoding') },
73     Content      => $content,
74   );
75
76   my $response = $ua->request($req);
77
78   die $response->status_line if $response->is_error;
79
80   my $response_json = decode_json( $response->content );
81   die $response_json->{error} if $response_json->{error}; #XXX response_error_param
82
83 }
84
85 1;