fix signups for the no-gateway-at-all case, RT#5673
[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
293                  && $payment_gateway->gateway_namespace
294                       eq 'Business::OnlineThirdPartyPayment'
295              ) {
296             warn "$me hiding $payby payment fields\n" if $DEBUG > 1;
297             $hide = 1;
298           }
299         }
300         push @{$signup_info->{'hide_payment_fields'}}, $hide;
301       }
302     }
303     warn "$me done setting agent-specific payment flag\n" if $DEBUG > 1;
304
305     warn "$me setting agent-specific package list\n" if $DEBUG > 1;
306     $signup_info->{'part_pkg'} = $signup_info->{'agentnum2part_pkg'}{$agentnum}
307       unless @{ $signup_info->{'part_pkg'} };
308     warn "$me done setting agent-specific package list\n" if $DEBUG > 1;
309
310     warn "$me setting agent-specific adv. source list\n" if $DEBUG > 1;
311     $signup_info->{'part_referral'} =
312       [
313         map { $_->hashref }
314           qsearch( {
315                      'table'     => 'part_referral',
316                      'hashref'   => { 'disabled' => '' },
317                      'extra_sql' => "AND (    agentnum = $agentnum  ".
318                                     "      OR agentnum IS NULL    ) ",
319                    },
320                  )
321       ];
322     warn "$me done setting agent-specific adv. source list\n" if $DEBUG > 1;
323
324     $signup_info->{'agent_name'} = $agent->agent;
325
326     $signup_info->{'company_name'} = $conf->config('company_name', $agentnum);
327
328     if ( $signup_info->{'agent_ship_address'} && $agent->agent_custnum ) {
329       my $cust_main = $agent->agent_cust_main;
330       my $prefix = length($cust_main->ship_last) ? 'ship_' : '';
331       $signup_info->{"ship_$_"} = $cust_main->get("$prefix$_")
332         foreach qw( address1 city county state zip country );
333     }
334
335   }
336   # else {
337   # delete $signup_info->{'part_pkg'};
338   #}
339
340   warn "$me sorting package list\n" if $DEBUG > 1;
341   $signup_info->{'part_pkg'} = [ sort { $a->{pkg} cmp $b->{pkg} }  # case?
342                                       @{ $signup_info->{'part_pkg'} }
343                                ];
344   warn "$me done sorting package list\n" if $DEBUG > 1;
345
346   if ( exists $packet->{'session_id'} ) {
347     my $agent_signup_info = { %$signup_info };
348     delete $agent_signup_info->{agentnum2part_pkg};
349     $agent_signup_info->{'agent'} = $session->{'agent'};
350     $agent_signup_info;
351   } else {
352     $signup_info;
353   }
354
355 }
356
357 sub domain_select_hash {
358   my $packet = shift;
359
360   my $response = {};
361
362   if ($packet->{pkgpart}) {
363     my $part_pkg = qsearchs('part_pkg' => { 'pkgpart' => $packet->{pkgpart} } );
364     #$packet->{svcpart} = $part_pkg->svcpart('svc_acct')
365     $packet->{svcpart} = $part_pkg->svcpart
366       if $part_pkg;
367   }
368
369   if ($packet->{svcpart}) {
370     my $part_svc = qsearchs('part_svc' => { 'svcpart' => $packet->{svcpart} } );
371     $response->{'domsvc'} = $part_svc->part_svc_column('domsvc')->columnvalue
372       if ($part_svc && $part_svc->part_svc_column('domsvc')->columnflag  eq 'D');
373   }
374
375   $response->{'domains'}
376     = { domain_select_hash FS::svc_acct( map { $_ => $packet->{$_} }
377                                                  qw(svcpart pkgnum)
378                                        ) };
379
380   $response;
381 }
382
383 sub new_customer {
384   my $packet = shift;
385
386   my $conf = new FS::Conf;
387   my $svc_x = $conf->config('signup_server-service') || 'svc_acct';
388
389   if ( $svc_x eq 'svc_acct' ) {
390   
391     #things that aren't necessary in base class, but are for signup server
392       #return "Passwords don't match"
393       #  if $hashref->{'_password'} ne $hashref->{'_password2'}
394     return { 'error' => gettext('empty_password') }
395       unless length($packet->{'_password'});
396     # a bit inefficient for large numbers of pops
397     return { 'error' => gettext('no_access_number_selected') }
398       unless $packet->{'popnum'} || !scalar(qsearch('svc_acct_pop',{} ));
399
400   }
401
402   my $agentnum;
403   if ( exists $packet->{'session_id'} ) {
404     my $cache = new FS::ClientAPI_SessionCache( {
405       'namespace' => 'FS::ClientAPI::Agent',
406     } );
407     my $session = $cache->get($packet->{'session_id'});
408     if ( $session ) {
409       $agentnum = $session->{'agentnum'};
410     } else {
411       return { 'error' => "Can't resume session" }; #better error message
412     }
413   } else {
414     $agentnum = $packet->{agentnum}
415                 || $conf->config('signup_server-default_agentnum');
416   }
417
418   #shares some stuff with htdocs/edit/process/cust_main.cgi... take any
419   # common that are still here and library them.
420   my $cust_main = new FS::cust_main ( {
421     #'custnum'          => '',
422     'agentnum'      => $agentnum,
423     'refnum'        => $packet->{refnum}
424                        || $conf->config('signup_server-default_refnum'),
425
426     map { $_ => $packet->{$_} } qw(
427
428       last first ss company address1 address2
429       city county state zip country
430       daytime night fax stateid stateid_state
431
432       ship_last ship_first ship_ss ship_company ship_address1 ship_address2
433       ship_city ship_county ship_state ship_zip ship_country
434       ship_daytime ship_night ship_fax
435
436       payby
437       payinfo paycvv paydate payname paystate paytype
438       paystart_month paystart_year payissue
439       payip
440
441       referral_custnum comments
442     )
443
444   } );
445
446   my $agent = qsearchs('agent', { 'agentnum' => $agentnum } );
447   if ( $conf->exists('agent_ship_address') && $agent->agent_custnum ) {
448     my $agent_cust_main = $agent->agent_cust_main;
449     my $prefix = length($agent_cust_main->ship_last) ? 'ship_' : '';
450     $cust_main->set("ship_$_", $agent_cust_main->get("$prefix$_") )
451       foreach qw( address1 city county state zip country );
452
453     $cust_main->set("ship_$_", $cust_main->get($_))
454       foreach qw( last first );
455
456   }
457
458
459   return { 'error' => "Illegal payment type" }
460     unless grep { $_ eq $packet->{'payby'} }
461                 $conf->config('signup_server-payby');
462
463   if (FS::payby->realtime($packet->{payby})) {
464     my $payby = $packet->{payby};
465
466     my $agent = qsearchs('agent', { 'agentnum' => $agentnum });
467     return { 'error' => "Unknown reseller" }
468       unless $agent;
469
470     my $payment_gateway =
471       $agent->payment_gateway( 'method' => FS::payby->payby2bop($payby) );
472
473     if ($payment_gateway->gateway_namespace eq
474         'Business::OnlineThirdPartyPayment'
475        ) {
476       $cust_main->payby('BILL');   # MCRD better?
477     }
478   }
479
480   $cust_main->payinfo($cust_main->daytime)
481     if $cust_main->payby eq 'LECB' && ! $cust_main->payinfo;
482
483   my @invoicing_list = $packet->{'invoicing_list'}
484                          ? split( /\s*\,\s*/, $packet->{'invoicing_list'} )
485                          : ();
486
487   $packet->{'pkgpart'} =~ /^(\d+)$/ or '' =~ /^()$/;
488   my $pkgpart = $1;
489   return { 'error' => 'Please select a package' } unless $pkgpart; #msgcat
490
491   my $part_pkg =
492     qsearchs( 'part_pkg', { 'pkgpart' => $pkgpart } )
493       or return { 'error' => "WARNING: unknown pkgpart: $pkgpart" };
494   my $svcpart = $part_pkg->svcpart($svc_x);
495
496   my $reg_code = '';
497   if ( $packet->{'reg_code'} ) {
498     $reg_code = qsearchs( 'reg_code', { 'code'     => $packet->{'reg_code'},
499                                         'agentnum' => $agentnum,             } )
500       or return { 'error' => 'Unknown registration code' };
501   }
502
503   my $cust_pkg = new FS::cust_pkg ( {
504     #later#'custnum' => $custnum,
505     'pkgpart'    => $packet->{'pkgpart'},
506     'promo_code' => $packet->{'promo_code'},
507     'reg_code'   => $packet->{'reg_code'},
508   } );
509   #my $error = $cust_pkg->check;
510   #return { 'error' => $error } if $error;
511
512   #should be all auto-magic and shit
513   my $svc;
514   if ( $svc_x eq 'svc_acct' ) {
515
516     $svc = new FS::svc_acct ( {
517       'svcpart'   => $svcpart,
518       map { $_ => $packet->{$_} }
519         qw( username _password sec_phrase popnum ),
520     } );
521
522     my @acct_snarf;
523     my $snarfnum = 1;
524     while (    exists($packet->{"snarf_machine$snarfnum"})
525             && length($packet->{"snarf_machine$snarfnum"}) ) {
526       my $acct_snarf = new FS::acct_snarf ( {
527         'machine'   => $packet->{"snarf_machine$snarfnum"},
528         'protocol'  => $packet->{"snarf_protocol$snarfnum"},
529         'username'  => $packet->{"snarf_username$snarfnum"},
530         '_password' => $packet->{"snarf_password$snarfnum"},
531       } );
532       $snarfnum++;
533       push @acct_snarf, $acct_snarf;
534     }
535     $svc->child_objects( \@acct_snarf );
536
537   } elsif ( $svc_x eq 'svc_phone' ) {
538
539     $svc = new FS::svc_phone ( {
540       'svcpart' => $svcpart,
541        map { $_ => $packet->{$_} }
542          qw( countrycode phonenum sip_password pin ),
543     } );
544
545   } else {
546     die "unknown signup service $svc_x";
547   }
548
549   my $y = $svc->setdefault; # arguably should be in new method
550   return { 'error' => $y } if $y && !ref($y);
551
552   #$error = $svc->check;
553   #return { 'error' => $error } if $error;
554
555   #setup a job dependancy to delay provisioning
556   my $placeholder = new FS::queue ( {
557     'job'    => 'FS::ClientAPI::Signup::__placeholder',
558     'status' => 'locked',
559   } );
560   my $error = $placeholder->insert;
561   return { 'error' => $error } if $error;
562
563   use Tie::RefHash;
564   tie my %hash, 'Tie::RefHash';
565   %hash = ( $cust_pkg => [ $svc ] );
566   #msgcat
567   $error = $cust_main->insert(
568     \%hash,
569     \@invoicing_list,
570     'depend_jobnum' => $placeholder->jobnum,
571   );
572   if ( $error ) {
573     my $perror = $placeholder->delete;
574     $error .= " (Additionally, error removing placeholder: $perror)" if $perror;
575     return { 'error' => $error };
576   }
577
578   if ( $conf->exists('signup_server-realtime') ) {
579
580     #warn "[fs_signup_server] Billing customer...\n" if $Debug;
581
582     my $bill_error = $cust_main->bill;
583     #warn "[fs_signup_server] error billing new customer: $bill_error"
584     #  if $bill_error;
585
586     $bill_error = $cust_main->apply_payments_and_credits;
587     #warn "[fs_signup_server] error applying payments and credits for".
588     #     " new customer: $bill_error"
589     #  if $bill_error;
590
591     if ($cust_main->_new_bop_required()) {
592       $bill_error = $cust_main->realtime_collect(
593          method        => FS::payby->payby2bop( $packet->{payby} ),
594          depend_jobnum => $placeholder->jobnum,
595       );
596     } else {
597       $bill_error = $cust_main->collect('realtime' => 1);
598     }
599     #warn "[fs_signup_server] error collecting from new customer: $bill_error"
600     #  if $bill_error;
601
602     if ($bill_error && ref($bill_error) eq 'HASH') {
603       return { 'error' => '_collect',
604                ( map { $_ => $bill_error->{$_} }
605                  qw(popup_url reference collectitems)
606                ),
607                amount => $cust_main->balance,
608              };
609     }
610
611     if ( $cust_main->balance > 0 ) {
612
613       #this makes sense.  credit is "un-doing" the invoice
614       $cust_main->credit( $cust_main->balance, 'signup server decline',
615                           'reason_type' => $conf->config('signup_credit_type'),
616                         );
617       $cust_main->apply_credits;
618
619       #should check list for errors...
620       #$cust_main->suspend;
621       local $FS::svc_Common::noexport_hack = 1;
622       $cust_main->cancel('quiet'=>1);
623
624       my $perror = $placeholder->depended_delete;
625       warn "error removing provisioning jobs after decline: $perror" if $perror;
626       unless ( $perror ) {
627         $perror = $placeholder->delete;
628         warn "error removing placeholder after decline: $perror" if $perror;
629       }
630
631       return { 'error' => '_decline' };
632     }
633
634   }
635
636   if ( $reg_code ) {
637     $error = $reg_code->delete;
638     return { 'error' => $error } if $error;
639   }
640
641   $error = $placeholder->delete;
642   return { 'error' => $error } if $error;
643
644   my %return = ( 'error'          => '',
645                  'signup_service' => $svc_x,
646                );
647
648   if ( $svc_x eq 'svc_acct' ) {
649     $return{$_} = $svc->$_() for qw( username _password );
650   } elsif ( $svc_x eq 'svc_phone' ) {
651     $return{$_} = $svc->$_() for qw( countrycode phonenum sip_password pin );
652   } else {
653     die "unknown signup service $svc_x";
654   }
655
656   return \%return;
657
658 }
659
660 sub capture_payment {
661   my $packet = shift;
662
663   warn "$me capture_payment called on $packet\n" if $DEBUG;
664
665   ###
666   # identify processor/gateway from called back URL
667   ###
668
669   my $conf = new FS::Conf;
670
671   my $url = $packet->{url};
672   my $payment_gateway =
673     qsearchs('payment_gateway', { 'gateway_callback_url' => popurl(0, $url) } );
674
675   unless ($payment_gateway) {
676
677     my ( $processor, $login, $password, $action, @bop_options ) =
678       $conf->config('business-onlinepayment');
679     $action ||= 'normal authorization';
680     pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
681     die "No real-time processor is enabled - ".
682         "did you set the business-onlinepayment configuration value?\n"
683       unless $processor;
684
685     $payment_gateway = new FS::payment_gateway( {
686       gateway_namespace => $conf->config('business-onlinepayment-namespace'),
687       gateway_module    => $processor,
688       gateway_username  => $login,
689       gateway_password  => $password,
690       gateway_action    => $action,
691       options   => [ ( @bop_options ) ],
692     });
693
694   }
695  
696   die "No real-time third party processor is enabled - ".
697       "did you set the business-onlinepayment configuration value?\n*"
698     unless $payment_gateway->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
699
700   ###
701   # locate pending transaction
702   ###
703
704   eval "use Business::OnlineThirdPartyPayment";
705   die $@ if $@;
706
707   my $transaction =
708     new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
709                                            @{ [ $payment_gateway->options ] },
710                                          );
711
712   my $paypendingnum = $transaction->reference($packet->{data});
713
714   my $cust_pay_pending =
715     qsearchs('cust_pay_pending', { paypendingnum => $paypendingnum } );
716
717   unless ($cust_pay_pending) {
718     my $bill_error = "No payment is being processed with id $paypendingnum".
719                      "; Transaction aborted.";
720     return { error => '_decline', bill_error => $bill_error };
721   }
722
723   if ($cust_pay_pending->status ne 'pending') {
724     my $bill_error = "Payment with id $paypendingnum is not pending, but ".
725                      $cust_pay_pending->status.  "; Transaction aborted.";
726     return { error => '_decline', bill_error => $bill_error };
727   }
728
729   my $cust_main = $cust_pay_pending->cust_main;
730   my $bill_error =
731     $cust_main->realtime_botpp_capture( $cust_pay_pending, %{$packet->{data}} );
732
733   return { 'error'      => ( $bill_error->{bill_error} ? '_decline' : '' ),
734            %$bill_error,
735          };
736
737 }
738
739 1;