summaryrefslogtreecommitdiff
path: root/FS/FS/cust_main/Billing_ThirdParty.pm
blob: a1d19fb9ea5b20b5965d2474515a569e1284d8e3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
package FS::cust_main::Billing_ThirdParty;

use strict;
use vars qw( $DEBUG $me );
use FS::Record qw( qsearch qsearchs dbh );
use FS::cust_pay;
use FS::cust_pay_pending;

$DEBUG = 0;
$me = '[FS::cust_main::Billing_ThirdParty]';
# arguably doesn't even belong under cust_main...

=head1 METHODS

=over 4

=item create_payment OPTIONS

Create a pending payment for a third-party gateway.  OPTIONS must include:
- method: a Business::OnlineThirdPartyPayment method argument.  Currently 
  only supports PAYPAL.
- amount: a decimal amount.  Unlike in Billing_Realtime, there is NO default.
- session_id: the customer's self-service session ID.

and may optionally include:
- invnum: the invoice that this payment will apply to
- pkgnum: the package balance that this payment will apply to.
- description: the transaction description for the gateway.
- payip: the IP address the payment is initiated from

On failure, returns a simple string error message.  On success, returns 
a hashref of 'url' => the URL to redirect the user to to complete payment,
and optionally 'post_params' => a hashref of name/value pairs to be POSTed
to that URL.

=cut

my @methods = qw(PAYPAL CC);
my %method2payby = ( 'PAYPAL' => 'PPAL',
                     'CC'     => 'MCRD', #?  but doesn't MCRD mean _offline_
                                         #card, not third-party card?  but no
                                         #one is doing non-paypal right now
                   );

sub create_payment {
  my $self = shift;
  my %opt = @_;

  # avoid duplicating this--we just need description and invnum
  my $defaults;
  $self->_bop_defaults($defaults);
  
  my $method = $opt{'method'} or return 'method required';
  my $amount = $opt{'amount'} or return 'amount required';
  return "unknown method '$method'" unless grep {$_ eq $method} @methods;
  return "amount must be > 0" unless $amount > 0;
  return "session_id required" unless length($opt{'session_id'});

  my $gateway = $self->agent->payment_gateway(
    method      => $method,
    nofatal     => 1,
    thirdparty  => 1,
  );
  return "no third-party gateway enabled for method $method" if !$gateway;

  # create pending record
  $self->select_for_update;
  my @pending = qsearch('cust_pay_pending', {
      'custnum' => $self->custnum,
      'status'  => { op=>'!=', value=>'done' }
  });

  # if there are pending payments in the 'thirdparty' state,
  # we can safely remove them
  foreach (@pending) {
    if ( $_->status eq 'thirdparty' ) {
      my $error = $_->delete;
      return "Error deleting unfinished payment #".
        $_->paypendingnum . ": $error\n" if $error;
    } else {
      return "A payment is already being processed for this customer.";
    }
  }

  my $cpp = FS::cust_pay_pending->new({
      'custnum'         => $self->custnum,
      'status'          => 'new',
      'gatewaynum'      => $gateway->gatewaynum,
      'paid'            => sprintf('%.2f',$opt{'amount'}),
      'payby'           => $method2payby{ $opt{'method'} },
      'pkgnum'          => $opt{'pkgnum'},
      'invnum'          => $opt{'invnum'} || $defaults->{'invnum'},
      'session_id'      => $opt{'session_id'},
  });

  my $error = $cpp->insert;
  return $error if $error;

  my $transaction = $gateway->processor;
  # Not included in this content hash:
  # payinfo, paydate, paycvv, any kind of recurring billing indicator,
  # paystate, paytype (account type), stateid, ss, payname
  #
  # Also, unlike bop_realtime, we don't allow the magical %options hash
  # to override the customer's information.  If they need to enter a 
  # different address or something for the billing provider, they can do 
  # that after the redirect.
  my %content = (
    'action'      => 'create',
    'description' => $opt{'description'} || $defaults->{'description'},
    'amount'      => $amount,
    'customer_id' => $self->custnum,
    'email'       => $self->invoicing_list_emailonly_scalar,
    'customer_ip' => $opt{'payip'},
    'first_name'  => $self->first,
    'last_name'   => $self->last,
    'address1'    => $self->address1,
    'address2'    => $self->address2,
    'city'        => $self->city,
    'state'       => $self->state,
    'zip'         => $self->zip,
    'country'     => $self->country,
    'phone'       => ($self->daytime || $self->night),
  );

  {
    local $@;
    eval { $transaction->create(%content) };
    if ( $@ ) {
      warn "ERROR: Executing third-party payment:\n$@\n";
      return { error => $@ };
    }
  }

  if ($transaction->is_success) {
    $cpp->status('thirdparty');
    # for whatever is most identifiable as the "transaction ID"
    $cpp->payinfo($transaction->token);
    # for anything else the transaction needs to remember
    $cpp->statustext($transaction->statustext);
    $error = $cpp->replace;
    return $error if $error;

    return {url => $transaction->redirect,
            post_params => $transaction->post_params};

  } else {
    $cpp->status('done');
    $cpp->statustext($transaction->error_message);
    $error = $cpp->replace;
    return $error if $error;

    return $transaction->error_message;
  }

}

=item execute_payment SESSION_ID, PARAMS

Complete the payment and get the status.  Triggered from the return_url
handler; PARAMS are all of the CGI parameters we received in the redirect.
On failure, returns an error message.  On success, returns a hashref of 
'paynum', 'paid', 'order_number', and 'auth'.

=cut

sub execute_payment {
  my $self = shift;
  my $session_id = shift;
  my %params = @_;

  my $cpp = qsearchs('cust_pay_pending', {
      'session_id'  => uc($session_id),
      'custnum'     => $self->custnum,
      'status'      => 'thirdparty',
  })
    or return 'no payment in process for this session';

  my $gateway = FS::payment_gateway->by_key( $cpp->gatewaynum );
  my $transaction = $gateway->processor;
  $transaction->token($cpp->payinfo);
  $transaction->statustext($cpp->statustext);

  {
    local $@;
    eval { $transaction->execute(%params) };
    if ( $@ ) {
      warn "ERROR: Executing third-party payment:\n$@\n";
      return { error => $@ };
    }
  }

  my $error;

  if ( $transaction->is_success ) {

    $error = $cpp->approve(
                    'processor'     => $gateway->gateway_module,
                    'order_number'  => $transaction->order_number,
                    'auth'          => $transaction->authorization,
                    'payinfo'       => '',
                    'apply'         => 1,
                  );
    return $error if $error;

    return {
      'paynum'        => $cpp->paynum,
      'paid'          => $cpp->paid,
      'order_number'  => $transaction->order_number,
      'auth'          => $transaction->authorization,
    }

  } else {

    my $error = $gateway->gateway_module. " error: ".
      $transaction->error_message;

    my $jobnum = $cpp->jobnum;
    if ( $jobnum ) {
      my $placeholder = FS::queue->by_key($jobnum);

      if ( $placeholder ) {
        my $e = $placeholder->depended_delete || $placeholder->delete;
        warn "error removing provisioning jobs after declined paypendingnum ".
          $cpp->paypendingnum. ": $e\n\n"
          if $e;
      } else {
        warn "error finding job $jobnum for declined paypendingnum ".
          $cpp->paypendingnum. "\n\n";
      }
    }

    # not needed here:
    # the raw HTTP response thing when there's no error message
    # decline notices (the customer has already seen the decline message)

    # set the pending status
    my $e = $cpp->decline($error);
    if ( $e ) {
      $e = "WARNING: payment declined but pending payment not resolved - ".
           "error updating status for pendingnum :".$cpp->paypendingnum.
           ": $e\n\n";
      warn $e;
      $error = "$e ($error)";
    }

    return $error;
  }

}

=item cancel_payment SESSION_ID

Cancel a pending payment attempt.  This just cleans up the cust_pay_pending
record.

=cut

sub cancel_payment {
  my $self = shift;
  my $session_id = shift;
  my $cust_pay_pending = qsearchs('cust_pay_pending', {
      'session_id'  => uc($session_id),
      'status'      => 'thirdparty',
  });
  return { 'error' => $cust_pay_pending->delete };
}

1;