merge webpay support in with autoselection of old realtime_bop and realtime_refund_bop
[freeside.git] / FS / FS / ClientAPI / Signup.pm
1 package FS::ClientAPI::Signup;
2
3 use strict;
4 use vars qw($DEBUG $me);
5 use Data::Dumper;
6 use Tie::RefHash;
7 use FS::Conf;
8 use FS::Record qw(qsearch qsearchs dbdef);
9 use FS::CGI qw(popurl);
10 use FS::Msgcat qw(gettext);
11 use FS::Misc qw(card_types);
12 use FS::ClientAPI_SessionCache;
13 use FS::agent;
14 use FS::cust_main_county;
15 use FS::part_pkg;
16 use FS::svc_acct_pop;
17 use FS::cust_main;
18 use FS::cust_pkg;
19 use FS::svc_acct;
20 use FS::svc_phone;
21 use FS::acct_snarf;
22 use FS::queue;
23 use FS::reg_code;
24 use FS::payby;
25
26 $DEBUG = 0;
27 $me = '[FS::ClientAPI::Signup]';
28
29 sub signup_info {
30   my $packet = shift;
31
32   warn "$me signup_info called on $packet\n" if $DEBUG;
33
34   my $conf = new FS::Conf;
35   my $svc_x = $conf->config('signup_server-service') || 'svc_acct';
36
37   my $cache = new FS::ClientAPI_SessionCache( {
38     'namespace' => 'FS::ClientAPI::Signup',
39   } );
40   my $signup_info_cache = $cache->get('signup_info_cache');
41
42   if ( $signup_info_cache ) {
43
44     warn "$me loading cached signup info\n" if $DEBUG > 1;
45
46   } else {
47
48     warn "$me populating signup info cache\n" if $DEBUG > 1;
49
50     my $agentnum2part_pkg = 
51       {
52         map {
53           my $agent = $_;
54           my $href = $agent->pkgpart_hashref;
55           $agent->agentnum =>
56             [
57               map { { 'payby'       => [ $_->payby ],
58                       'freq_pretty' => $_->freq_pretty,
59                       'options'     => { $_->options },
60                       %{$_->hashref}
61                   } }
62                 grep { $_->svcpart($svc_x)
63                        && ( $href->{ $_->pkgpart }
64                             || $_->agentnum == $agent->agentnum
65                           )
66                      }
67                   qsearch( 'part_pkg', { 'disabled' => '' } )
68             ];
69         } qsearch('agent', { 'disabled' => '' })
70       };
71
72     my $msgcat = { map { $_=>gettext($_) }
73                        qw( passwords_dont_match invalid_card unknown_card_type
74                            not_a empty_password illegal_or_empty_text )
75                  };
76     warn "msgcat: ". Dumper($msgcat). "\n" if $DEBUG > 2;
77
78     my $label = { map { $_ => FS::Msgcat::_gettext($_) }
79                       qw( stateid stateid_state )
80                 };
81     warn "label: ". Dumper($label). "\n" if $DEBUG > 2;
82
83     my @agent_fields = qw( agentnum agent );
84
85     $signup_info_cache = {
86       'cust_main_county' => [ map $_->hashref,
87                                   qsearch('cust_main_county', {} )
88                             ],
89
90       'agent' => [ map { my $agent = $_;
91                          map { $_ => $agent->get($_) } @agent_fields;
92                        }
93                        qsearch('agent', { 'disabled' => '' } )
94                  ],
95
96       'part_referral' => [ map $_->hashref,
97                                qsearch('part_referral', { 'disabled' => '' } )
98                          ],
99
100       'agentnum2part_pkg' => $agentnum2part_pkg,
101
102       'svc_acct_pop' => [ map $_->hashref, qsearch('svc_acct_pop',{} ) ],
103
104       'emailinvoiceonly' => $conf->exists('emailinvoiceonly'),
105
106       'security_phrase' => $conf->exists('security_phrase'),
107
108       'payby' => [ $conf->config('signup_server-payby') ],
109
110       'card_types' => card_types(),
111
112       'paytypes' => [ @FS::cust_main::paytypes ],
113
114       'cvv_enabled' => 1,
115
116       'stateid_enabled' => $conf->exists('show_stateid'),
117
118       'paystate_enabled' => $conf->exists('show_bankstate'),
119
120       'ship_enabled' => 1,
121
122       'msgcat' => $msgcat,
123
124       'label' => $label,
125
126       'statedefault' => scalar($conf->config('statedefault')) || 'CA',
127
128       'countrydefault' => scalar($conf->config('countrydefault')) || 'US',
129
130       'refnum' => scalar($conf->config('signup_server-default_refnum')),
131
132       'default_pkgpart' => scalar($conf->config('signup_server-default_pkgpart')),
133
134       'signup_service' => $svc_x,
135       'default_svcpart' => scalar($conf->config('signup_server-default_svcpart')),
136
137       'head'         => join("\n", $conf->config('selfservice-head') ),
138       'body_header'  => join("\n", $conf->config('selfservice-body_header') ),
139       'body_footer'  => join("\n", $conf->config('selfservice-body_footer') ),
140       'body_bgcolor' => scalar( $conf->config('selfservice-body_bgcolor') ),
141       'box_bgcolor'  => scalar( $conf->config('selfservice-box_bgcolor')  ),
142
143       'company_name'   => scalar($conf->config('company_name')),
144
145       #per-agent?
146       'agent_ship_address' => scalar($conf->exists('agent-ship_address')),
147
148       'no_company'        => scalar($conf->exists('signup-no_company')),
149       'require_phone'     => scalar($conf->exists('cust_main-require_phone')),
150       'recommend_daytime' => scalar($conf->exists('signup-recommend_daytime')),
151       'recommend_email'   => scalar($conf->exists('signup-recommend_email')),
152
153     };
154
155     $cache->set('signup_info_cache', $signup_info_cache);
156
157   }
158
159   my $signup_info = { %$signup_info_cache };
160   warn "$me signup info loaded\n" if $DEBUG > 1;
161   warn Dumper($signup_info). "\n" if $DEBUG > 2;
162
163   my @addl = qw( signup_server-classnum2 signup_server-classnum3 );
164
165   if ( grep { $conf->exists($_) } @addl ) {
166   
167     $signup_info->{optional_packages} = [];
168
169     foreach my $addl ( @addl ) {
170
171       warn "$me adding optional package info\n" if $DEBUG > 1;
172
173       my $classnum = $conf->config($addl) or next;
174
175       my @pkgs = map { {
176                          'freq_pretty' => $_->freq_pretty,
177                          'options'     => { $_->options },
178                          %{ $_->hashref }
179                        };
180                      }
181                      qsearch( 'part_pkg', { classnum => $classnum } );
182
183       push @{$signup_info->{optional_packages}}, \@pkgs;
184
185       warn "$me done adding opt. package info for $classnum\n" if $DEBUG > 1;
186
187     }
188
189   }
190
191   my $agentnum = $packet->{'agentnum'}
192                  || $conf->config('signup_server-default_agentnum');
193   $agentnum =~ /^(\d*)$/ or die "illegal agentnum";
194   $agentnum = $1;
195
196   my $session = '';
197   if ( exists $packet->{'session_id'} ) {
198
199     warn "$me loading agent session\n" if $DEBUG > 1;
200     my $cache = new FS::ClientAPI_SessionCache( {
201       'namespace' => 'FS::ClientAPI::Agent',
202     } );
203     $session = $cache->get($packet->{'session_id'});
204     if ( $session ) {
205       $agentnum = $session->{'agentnum'};
206     } else {
207       return { 'error' => "Can't resume session" }; #better error message
208     }
209     warn "$me done loading agent session\n" if $DEBUG > 1;
210
211   } elsif ( exists $packet->{'customer_session_id'} ) {
212
213     warn "$me loading customer session\n" if $DEBUG > 1;
214     my $cache = new FS::ClientAPI_SessionCache( {
215       'namespace' => 'FS::ClientAPI::MyAccount',
216     } );
217     $session = $cache->get($packet->{'customer_session_id'});
218     if ( $session ) {
219       my $custnum = $session->{'custnum'};
220       my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum });
221       return { 'error' => "Can't find your customer record" } unless $cust_main;
222       $agentnum = $cust_main->agentnum;
223     } else {
224       return { 'error' => "Can't resume session" }; #better error message
225     }
226     warn "$me done loading customer session\n" if $DEBUG > 1;
227
228   }
229
230   $signup_info->{'part_pkg'} = [];
231
232   if ( $packet->{'reg_code'} ) {
233
234     warn "$me setting package list via reg_code\n" if $DEBUG > 1;
235
236     $signup_info->{'part_pkg'} = 
237       [ map { { 'payby'       => [ $_->payby ],
238                 'freq_pretty' => $_->freq_pretty,
239                 'options'     => { $_->options },
240                 %{$_->hashref}
241               };
242             }
243           grep { $_->svcpart($svc_x) }
244           map { $_->part_pkg }
245             qsearchs( 'reg_code', { 'code'     => $packet->{'reg_code'},
246                                     'agentnum' => $agentnum,              } )
247
248       ];
249
250     $signup_info->{'error'} = 'Unknown registration code'
251       unless @{ $signup_info->{'part_pkg'} };
252
253     warn "$me done setting package list via reg_code\n" if $DEBUG > 1;
254
255   } elsif ( $packet->{'promo_code'} ) {
256
257     warn "$me setting package list via promo_code\n" if $DEBUG > 1;
258
259     $signup_info->{'part_pkg'} =
260       [ map { { 'payby'   => [ $_->payby ],
261                 'freq_pretty' => $_->freq_pretty,
262                 'options'     => { $_->options },
263                 %{$_->hashref}
264             } }
265           grep { $_->svcpart($svc_x) }
266             qsearch( 'part_pkg', { 'promo_code' => {
267                                      op=>'ILIKE',
268                                      value=>$packet->{'promo_code'}
269                                    },
270                                    'disabled'   => '',                  } )
271       ];
272
273     $signup_info->{'error'} = 'Unknown promotional code'
274       unless @{ $signup_info->{'part_pkg'} };
275
276     warn "$me done setting package list via promo_code\n" if $DEBUG > 1;
277   }
278
279   if ( $agentnum ) {
280
281     warn "$me setting agent-specific payment flag\n" if $DEBUG > 1;
282     my $agent = qsearchs('agent', { 'agentnum' => $agentnum } );
283     warn "$me has agent $agent\n" if $DEBUG > 1;
284     if ( $agent ) { #else complain loudly?
285       $signup_info->{'hide_payment_fields'} = [];
286       foreach my $payby (@{$signup_info->{payby}}) {
287         warn "$me checking $payby payment fields\n" if $DEBUG > 1;
288         my $hide = 0;
289         if (FS::payby->realtime($payby)) {
290           my $payment_gateway =
291             $agent->payment_gateway( 'method' => FS::payby->payby2bop($payby) );
292           if ($payment_gateway->gateway_namespace eq
293               'Business::OnlineThirdPartyPayment'
294              ) {
295             warn "$me hiding $payby payment fields\n" if $DEBUG > 1;
296             $hide = 1;
297           }
298         }
299         push @{$signup_info->{'hide_payment_fields'}}, $hide;
300       }
301     }
302     warn "$me done setting agent-specific payment flag\n" if $DEBUG > 1;
303
304     warn "$me setting agent-specific package list\n" if $DEBUG > 1;
305     $signup_info->{'part_pkg'} = $signup_info->{'agentnum2part_pkg'}{$agentnum}
306       unless @{ $signup_info->{'part_pkg'} };
307     warn "$me done setting agent-specific package list\n" if $DEBUG > 1;
308
309     warn "$me setting agent-specific adv. source list\n" if $DEBUG > 1;
310     $signup_info->{'part_referral'} =
311       [
312         map { $_->hashref }
313           qsearch( {
314                      'table'     => 'part_referral',
315                      'hashref'   => { 'disabled' => '' },
316                      'extra_sql' => "AND (    agentnum = $agentnum  ".
317                                     "      OR agentnum IS NULL    ) ",
318                    },
319                  )
320       ];
321     warn "$me done setting agent-specific adv. source list\n" if $DEBUG > 1;
322
323     $signup_info->{'agent_name'} = $agent->agent;
324
325     $signup_info->{'company_name'} = $conf->config('company_name', $agentnum);
326
327     if ( $signup_info->{'agent_ship_address'} && $agent->agent_custnum ) {
328       my $cust_main = $agent->agent_cust_main;
329       my $prefix = length($cust_main->ship_last) ? 'ship_' : '';
330       $signup_info->{"ship_$_"} = $cust_main->get("$prefix$_")
331         foreach qw( address1 city county state zip country );
332     }
333
334   }
335   # else {
336   # delete $signup_info->{'part_pkg'};
337   #}
338
339   warn "$me sorting package list\n" if $DEBUG > 1;
340   $signup_info->{'part_pkg'} = [ sort { $a->{pkg} cmp $b->{pkg} }  # case?
341                                       @{ $signup_info->{'part_pkg'} }
342                                ];
343   warn "$me done sorting package list\n" if $DEBUG > 1;
344
345   if ( exists $packet->{'session_id'} ) {
346     my $agent_signup_info = { %$signup_info };
347     delete $agent_signup_info->{agentnum2part_pkg};
348     $agent_signup_info->{'agent'} = $session->{'agent'};
349     $agent_signup_info;
350   } else {
351     $signup_info;
352   }
353
354 }
355
356 sub domain_select_hash {
357   my $packet = shift;
358
359   my $response = {};
360
361   if ($packet->{pkgpart}) {
362     my $part_pkg = qsearchs('part_pkg' => { 'pkgpart' => $packet->{pkgpart} } );
363     #$packet->{svcpart} = $part_pkg->svcpart('svc_acct')
364     $packet->{svcpart} = $part_pkg->svcpart
365       if $part_pkg;
366   }
367
368   if ($packet->{svcpart}) {
369     my $part_svc = qsearchs('part_svc' => { 'svcpart' => $packet->{svcpart} } );
370     $response->{'domsvc'} = $part_svc->part_svc_column('domsvc')->columnvalue
371       if ($part_svc && $part_svc->part_svc_column('domsvc')->columnflag  eq 'D');
372   }
373
374   $response->{'domains'}
375     = { domain_select_hash FS::svc_acct( map { $_ => $packet->{$_} }
376                                                  qw(svcpart pkgnum)
377                                        ) };
378
379   $response;
380 }
381
382 sub new_customer {
383   my $packet = shift;
384
385   my $conf = new FS::Conf;
386   my $svc_x = $conf->config('signup_server-service') || 'svc_acct';
387
388   if ( $svc_x eq 'svc_acct' ) {
389   
390     #things that aren't necessary in base class, but are for signup server
391       #return "Passwords don't match"
392       #  if $hashref->{'_password'} ne $hashref->{'_password2'}
393     return { 'error' => gettext('empty_password') }
394       unless length($packet->{'_password'});
395     # a bit inefficient for large numbers of pops
396     return { 'error' => gettext('no_access_number_selected') }
397       unless $packet->{'popnum'} || !scalar(qsearch('svc_acct_pop',{} ));
398
399   }
400
401   my $agentnum;
402   if ( exists $packet->{'session_id'} ) {
403     my $cache = new FS::ClientAPI_SessionCache( {
404       'namespace' => 'FS::ClientAPI::Agent',
405     } );
406     my $session = $cache->get($packet->{'session_id'});
407     if ( $session ) {
408       $agentnum = $session->{'agentnum'};
409     } else {
410       return { 'error' => "Can't resume session" }; #better error message
411     }
412   } else {
413     $agentnum = $packet->{agentnum}
414                 || $conf->config('signup_server-default_agentnum');
415   }
416
417   #shares some stuff with htdocs/edit/process/cust_main.cgi... take any
418   # common that are still here and library them.
419   my $cust_main = new FS::cust_main ( {
420     #'custnum'          => '',
421     'agentnum'      => $agentnum,
422     'refnum'        => $packet->{refnum}
423                        || $conf->config('signup_server-default_refnum'),
424
425     map { $_ => $packet->{$_} } qw(
426
427       last first ss company address1 address2
428       city county state zip country
429       daytime night fax stateid stateid_state
430
431       ship_last ship_first ship_ss ship_company ship_address1 ship_address2
432       ship_city ship_county ship_state ship_zip ship_country
433       ship_daytime ship_night ship_fax
434
435       payby
436       payinfo paycvv paydate payname paystate paytype
437       paystart_month paystart_year payissue
438       payip
439
440       referral_custnum comments
441     )
442
443   } );
444
445   my $agent = qsearchs('agent', { 'agentnum' => $agentnum } );
446   if ( $conf->exists('agent_ship_address') && $agent->agent_custnum ) {
447     my $agent_cust_main = $agent->agent_cust_main;
448     my $prefix = length($agent_cust_main->ship_last) ? 'ship_' : '';
449     $cust_main->set("ship_$_", $agent_cust_main->get("$prefix$_") )
450       foreach qw( address1 city county state zip country );
451
452     $cust_main->set("ship_$_", $cust_main->get($_))
453       foreach qw( last first );
454
455   }
456
457
458   return { 'error' => "Illegal payment type" }
459     unless grep { $_ eq $packet->{'payby'} }
460                 $conf->config('signup_server-payby');
461
462   if (FS::payby->realtime($packet->{payby})) {
463     my $payby = $packet->{payby};
464
465     my $agent = qsearchs('agent', { 'agentnum' => $agentnum });
466     return { 'error' => "Unknown reseller" }
467       unless $agent;
468
469     my $payment_gateway =
470       $agent->payment_gateway( 'method' => FS::payby->payby2bop($payby) );
471
472     if ($payment_gateway->gateway_namespace eq
473         'Business::OnlineThirdPartyPayment'
474        ) {
475       $cust_main->payby('BILL');   # MCRD better?
476     }
477   }
478
479   $cust_main->payinfo($cust_main->daytime)
480     if $cust_main->payby eq 'LECB' && ! $cust_main->payinfo;
481
482   my @invoicing_list = $packet->{'invoicing_list'}
483                          ? split( /\s*\,\s*/, $packet->{'invoicing_list'} )
484                          : ();
485
486   $packet->{'pkgpart'} =~ /^(\d+)$/ or '' =~ /^()$/;
487   my $pkgpart = $1;
488   return { 'error' => 'Please select a package' } unless $pkgpart; #msgcat
489
490   my $part_pkg =
491     qsearchs( 'part_pkg', { 'pkgpart' => $pkgpart } )
492       or return { 'error' => "WARNING: unknown pkgpart: $pkgpart" };
493   my $svcpart = $part_pkg->svcpart($svc_x);
494
495   my $reg_code = '';
496   if ( $packet->{'reg_code'} ) {
497     $reg_code = qsearchs( 'reg_code', { 'code'     => $packet->{'reg_code'},
498                                         'agentnum' => $agentnum,             } )
499       or return { 'error' => 'Unknown registration code' };
500   }
501
502   my $cust_pkg = new FS::cust_pkg ( {
503     #later#'custnum' => $custnum,
504     'pkgpart'    => $packet->{'pkgpart'},
505     'promo_code' => $packet->{'promo_code'},
506     'reg_code'   => $packet->{'reg_code'},
507   } );
508   #my $error = $cust_pkg->check;
509   #return { 'error' => $error } if $error;
510
511   #should be all auto-magic and shit
512   my $svc;
513   if ( $svc_x eq 'svc_acct' ) {
514
515     $svc = new FS::svc_acct ( {
516       'svcpart'   => $svcpart,
517       map { $_ => $packet->{$_} }
518         qw( username _password sec_phrase popnum ),
519     } );
520
521     my @acct_snarf;
522     my $snarfnum = 1;
523     while (    exists($packet->{"snarf_machine$snarfnum"})
524             && length($packet->{"snarf_machine$snarfnum"}) ) {
525       my $acct_snarf = new FS::acct_snarf ( {
526         'machine'   => $packet->{"snarf_machine$snarfnum"},
527         'protocol'  => $packet->{"snarf_protocol$snarfnum"},
528         'username'  => $packet->{"snarf_username$snarfnum"},
529         '_password' => $packet->{"snarf_password$snarfnum"},
530       } );
531       $snarfnum++;
532       push @acct_snarf, $acct_snarf;
533     }
534     $svc->child_objects( \@acct_snarf );
535
536   } elsif ( $svc_x eq 'svc_phone' ) {
537
538     $svc = new FS::svc_phone ( {
539       'svcpart' => $svcpart,
540        map { $_ => $packet->{$_} }
541          qw( countrycode phonenum sip_password pin ),
542     } );
543
544   } else {
545     die "unknown signup service $svc_x";
546   }
547
548   my $y = $svc->setdefault; # arguably should be in new method
549   return { 'error' => $y } if $y && !ref($y);
550
551   #$error = $svc->check;
552   #return { 'error' => $error } if $error;
553
554   #setup a job dependancy to delay provisioning
555   my $placeholder = new FS::queue ( {
556     'job'    => 'FS::ClientAPI::Signup::__placeholder',
557     'status' => 'locked',
558   } );
559   my $error = $placeholder->insert;
560   return { 'error' => $error } if $error;
561
562   use Tie::RefHash;
563   tie my %hash, 'Tie::RefHash';
564   %hash = ( $cust_pkg => [ $svc ] );
565   #msgcat
566   $error = $cust_main->insert(
567     \%hash,
568     \@invoicing_list,
569     'depend_jobnum' => $placeholder->jobnum,
570   );
571   if ( $error ) {
572     my $perror = $placeholder->delete;
573     $error .= " (Additionally, error removing placeholder: $perror)" if $perror;
574     return { 'error' => $error };
575   }
576
577   if ( $conf->exists('signup_server-realtime') ) {
578
579     #warn "[fs_signup_server] Billing customer...\n" if $Debug;
580
581     my $bill_error = $cust_main->bill;
582     #warn "[fs_signup_server] error billing new customer: $bill_error"
583     #  if $bill_error;
584
585     $bill_error = $cust_main->apply_payments_and_credits;
586     #warn "[fs_signup_server] error applying payments and credits for".
587     #     " new customer: $bill_error"
588     #  if $bill_error;
589
590     if ($cust_main->_new_bop_required()) {
591       $bill_error = $cust_main->realtime_collect(
592          method        => FS::payby->payby2bop( $packet->{payby} ),
593          depend_jobnum => $placeholder->jobnum,
594       );
595     } else {
596       $bill_error = $cust_main->collect('realtime' => 1);
597     }
598     #warn "[fs_signup_server] error collecting from new customer: $bill_error"
599     #  if $bill_error;
600
601     if ($bill_error && ref($bill_error) eq 'HASH') {
602       return { 'error' => '_collect',
603                ( map { $_ => $bill_error->{$_} }
604                  qw(popup_url reference collectitems)
605                ),
606                amount => $cust_main->balance,
607              };
608     }
609
610     if ( $cust_main->balance > 0 ) {
611
612       #this makes sense.  credit is "un-doing" the invoice
613       $cust_main->credit( $cust_main->balance, 'signup server decline',
614                           'reason_type' => $conf->config('signup_credit_type'),
615                         );
616       $cust_main->apply_credits;
617
618       #should check list for errors...
619       #$cust_main->suspend;
620       local $FS::svc_Common::noexport_hack = 1;
621       $cust_main->cancel('quiet'=>1);
622
623       my $perror = $placeholder->depended_delete;
624       warn "error removing provisioning jobs after decline: $perror" if $perror;
625       unless ( $perror ) {
626         $perror = $placeholder->delete;
627         warn "error removing placeholder after decline: $perror" if $perror;
628       }
629
630       return { 'error' => '_decline' };
631     }
632
633   }
634
635   if ( $reg_code ) {
636     $error = $reg_code->delete;
637     return { 'error' => $error } if $error;
638   }
639
640   $error = $placeholder->delete;
641   return { 'error' => $error } if $error;
642
643   my %return = ( 'error'          => '',
644                  'signup_service' => $svc_x,
645                );
646
647   if ( $svc_x eq 'svc_acct' ) {
648     $return{$_} = $svc->$_() for qw( username _password );
649   } elsif ( $svc_x eq 'svc_phone' ) {
650     $return{$_} = $svc->$_() for qw( countrycode phonenum sip_password pin );
651   } else {
652     die "unknown signup service $svc_x";
653   }
654
655   return \%return;
656
657 }
658
659 sub capture_payment {
660   my $packet = shift;
661
662   warn "$me capture_payment called on $packet\n" if $DEBUG;
663
664   ###
665   # identify processor/gateway from called back URL
666   ###
667
668   my $conf = new FS::Conf;
669
670   my $url = $packet->{url};
671   my $payment_gateway =
672     qsearchs('payment_gateway', { 'gateway_callback_url' => popurl(0, $url) } );
673
674   unless ($payment_gateway) {
675
676     my ( $processor, $login, $password, $action, @bop_options ) =
677       $conf->config('business-onlinepayment');
678     $action ||= 'normal authorization';
679     pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
680     die "No real-time processor is enabled - ".
681         "did you set the business-onlinepayment configuration value?\n"
682       unless $processor;
683
684     $payment_gateway = new FS::payment_gateway( {
685       gateway_namespace => $conf->config('business-onlinepayment-namespace'),
686       gateway_module    => $processor,
687       gateway_username  => $login,
688       gateway_password  => $password,
689       gateway_action    => $action,
690       options   => [ ( @bop_options ) ],
691     });
692
693   }
694  
695   die "No real-time third party processor is enabled - ".
696       "did you set the business-onlinepayment configuration value?\n*"
697     unless $payment_gateway->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
698
699   ###
700   # locate pending transaction
701   ###
702
703   eval "use Business::OnlineThirdPartyPayment";
704   die $@ if $@;
705
706   my $transaction =
707     new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
708                                            @{ [ $payment_gateway->options ] },
709                                          );
710
711   my $paypendingnum = $transaction->reference($packet->{data});
712
713   my $cust_pay_pending =
714     qsearchs('cust_pay_pending', { paypendingnum => $paypendingnum } );
715
716   unless ($cust_pay_pending) {
717     my $bill_error = "No payment is being processed with id $paypendingnum".
718                      "; Transaction aborted.";
719     return { error => '_decline', bill_error => $bill_error };
720   }
721
722   if ($cust_pay_pending->status ne 'pending') {
723     my $bill_error = "Payment with id $paypendingnum is not pending, but ".
724                      $cust_pay_pending->status.  "; Transaction aborted.";
725     return { error => '_decline', bill_error => $bill_error };
726   }
727
728   my $cust_main = $cust_pay_pending->cust_main;
729   my $bill_error =
730     $cust_main->realtime_botpp_capture( $cust_pay_pending, %{$packet->{data}} );
731
732   return { 'error'      => ( $bill_error->{bill_error} ? '_decline' : '' ),
733            %$bill_error,
734          };
735
736 }
737
738 1;