Search in sources :

Example 16 with PaymentTransaction

use of org.killbill.billing.payment.api.PaymentTransaction in project killbill by killbill.

the class AccountResource method processPayment.

private Response processPayment(final PaymentTransactionJson json, final Account account, final String paymentMethodIdStr, final List<String> paymentControlPluginNames, final List<String> pluginPropertiesString, final UriInfo uriInfo, final CallContext callContext, final HttpServletRequest request) throws PaymentApiException {
    verifyNonNullOrEmpty(json, "PaymentTransactionJson body should be specified");
    verifyNonNullOrEmpty(json.getTransactionType(), "PaymentTransactionJson transactionType needs to be set", json.getAmount(), "PaymentTransactionJson amount needs to be set");
    final Iterable<PluginProperty> pluginProperties = extractPluginProperties(pluginPropertiesString);
    final Currency currency = json.getCurrency() == null ? account.getCurrency() : Currency.valueOf(json.getCurrency());
    final UUID paymentId = json.getPaymentId() == null ? null : UUID.fromString(json.getPaymentId());
    //
    // If paymentId was specified, it means we are attempting a payment completion. The preferred way is to use the PaymentResource
    // (PUT /1.0/kb/payments/{paymentId}/completeTransaction), but for backward compatibility we still allow the call to proceed
    // as long as the request/existing state is healthy (i.e there is a matching PENDING transaction)
    //
    final UUID paymentMethodId;
    if (paymentId != null) {
        final Payment initialPayment = paymentApi.getPayment(paymentId, false, false, pluginProperties, callContext);
        final PaymentTransaction pendingOrSuccessTransaction = lookupPendingOrSuccessTransaction(initialPayment, json != null ? json.getTransactionId() : null, json != null ? json.getTransactionExternalKey() : null, json != null ? json.getTransactionType() : null);
        // If transaction was already completed, return early (See #626)
        if (pendingOrSuccessTransaction.getTransactionStatus() == TransactionStatus.SUCCESS) {
            return uriBuilder.buildResponse(uriInfo, PaymentResource.class, "getPayment", pendingOrSuccessTransaction.getPaymentId(), request);
        }
        paymentMethodId = initialPayment.getPaymentMethodId();
    } else {
        paymentMethodId = paymentMethodIdStr == null ? account.getPaymentMethodId() : UUID.fromString(paymentMethodIdStr);
    }
    validatePaymentMethodForAccount(account.getId(), paymentMethodId, callContext);
    final TransactionType transactionType = TransactionType.valueOf(json.getTransactionType());
    final PaymentOptions paymentOptions = createControlPluginApiPaymentOptions(paymentControlPluginNames);
    final Payment result;
    switch(transactionType) {
        case AUTHORIZE:
            result = paymentApi.createAuthorizationWithPaymentControl(account, paymentMethodId, paymentId, json.getAmount(), currency, json.getPaymentExternalKey(), json.getTransactionExternalKey(), pluginProperties, paymentOptions, callContext);
            break;
        case PURCHASE:
            result = paymentApi.createPurchaseWithPaymentControl(account, paymentMethodId, paymentId, json.getAmount(), currency, json.getPaymentExternalKey(), json.getTransactionExternalKey(), pluginProperties, paymentOptions, callContext);
            break;
        case CREDIT:
            result = paymentApi.createCreditWithPaymentControl(account, paymentMethodId, paymentId, json.getAmount(), currency, json.getPaymentExternalKey(), json.getTransactionExternalKey(), pluginProperties, paymentOptions, callContext);
            break;
        default:
            return Response.status(Status.PRECONDITION_FAILED).entity("TransactionType " + transactionType + " is not allowed for an account").build();
    }
    return createPaymentResponse(uriInfo, result, transactionType, json.getTransactionExternalKey(), request);
}
Also used : PaymentTransaction(org.killbill.billing.payment.api.PaymentTransaction) PluginProperty(org.killbill.billing.payment.api.PluginProperty) InvoicePayment(org.killbill.billing.invoice.api.InvoicePayment) Payment(org.killbill.billing.payment.api.Payment) TransactionType(org.killbill.billing.payment.api.TransactionType) Currency(org.killbill.billing.catalog.api.Currency) UUID(java.util.UUID) PaymentOptions(org.killbill.billing.payment.api.PaymentOptions)

Example 17 with PaymentTransaction

use of org.killbill.billing.payment.api.PaymentTransaction in project killbill by killbill.

the class DefaultPaymentDao method getByTransactionStatusAcrossTenants.

@Override
public Pagination<PaymentTransactionModelDao> getByTransactionStatusAcrossTenants(final Iterable<TransactionStatus> transactionStatuses, final DateTime createdBeforeDate, final DateTime createdAfterDate, final Long offset, final Long limit) {
    final Collection<String> allTransactionStatus = ImmutableList.copyOf(Iterables.transform(transactionStatuses, Functions.toStringFunction()));
    final Date createdBefore = createdBeforeDate.toDate();
    final Date createdAfter = createdAfterDate.toDate();
    return paginationHelper.getPagination(TransactionSqlDao.class, new PaginationIteratorBuilder<PaymentTransactionModelDao, PaymentTransaction, TransactionSqlDao>() {

        @Override
        public Long getCount(final TransactionSqlDao sqlDao, final InternalTenantContext context) {
            return sqlDao.getCountByTransactionStatusPriorDateAcrossTenants(allTransactionStatus, createdBefore, createdAfter);
        }

        @Override
        public Iterator<PaymentTransactionModelDao> build(final TransactionSqlDao sqlDao, final Long offset, final Long limit, final Ordering ordering, final InternalTenantContext context) {
            return sqlDao.getByTransactionStatusPriorDateAcrossTenants(allTransactionStatus, createdBefore, createdAfter, offset, limit, ordering.toString());
        }
    }, offset, limit, null);
}
Also used : PaymentTransaction(org.killbill.billing.payment.api.PaymentTransaction) InternalTenantContext(org.killbill.billing.callcontext.InternalTenantContext) Ordering(org.killbill.billing.util.entity.dao.DefaultPaginationSqlDaoHelper.Ordering) Iterator(java.util.Iterator) Date(java.util.Date)

Example 18 with PaymentTransaction

use of org.killbill.billing.payment.api.PaymentTransaction in project killbill by killbill.

the class TestJanitor method testCreateSuccessRefundPaymentControlWithItemAdjustments.

@Test(groups = "slow")
public void testCreateSuccessRefundPaymentControlWithItemAdjustments() throws Exception {
    final BigDecimal requestedAmount = BigDecimal.TEN;
    final UUID subscriptionId = UUID.randomUUID();
    final UUID bundleId = UUID.randomUUID();
    final LocalDate now = clock.getUTCToday();
    testListener.pushExpectedEvent(NextEvent.INVOICE);
    final Invoice invoice = testHelper.createTestInvoice(account, now, Currency.USD);
    testListener.assertListenerStatus();
    final String paymentExternalKey = invoice.getId().toString();
    final String transactionExternalKey = "craboom";
    final String transactionExternalKey2 = "qwerty";
    final InvoiceItem invoiceItem = new MockRecurringInvoiceItem(invoice.getId(), account.getId(), subscriptionId, bundleId, "test plan", "test phase", null, now, now.plusMonths(1), requestedAmount, new BigDecimal("1.0"), Currency.USD);
    invoice.addInvoiceItem(invoiceItem);
    testListener.pushExpectedEvent(NextEvent.PAYMENT);
    final Payment payment = paymentApi.createPurchaseWithPaymentControl(account, account.getPaymentMethodId(), null, requestedAmount, Currency.USD, paymentExternalKey, transactionExternalKey, createPropertiesForInvoice(invoice), INVOICE_PAYMENT, callContext);
    testListener.assertListenerStatus();
    final List<PluginProperty> refundProperties = new ArrayList<PluginProperty>();
    final HashMap<UUID, BigDecimal> uuidBigDecimalHashMap = new HashMap<UUID, BigDecimal>();
    uuidBigDecimalHashMap.put(invoiceItem.getId(), new BigDecimal("1.0"));
    final PluginProperty refundIdsProp = new PluginProperty(InvoicePaymentControlPluginApi.PROP_IPCD_REFUND_IDS_WITH_AMOUNT_KEY, uuidBigDecimalHashMap, false);
    refundProperties.add(refundIdsProp);
    testListener.pushExpectedEvent(NextEvent.PAYMENT);
    final Payment payment2 = paymentApi.createRefundWithPaymentControl(account, payment.getId(), null, Currency.USD, transactionExternalKey2, refundProperties, INVOICE_PAYMENT, callContext);
    testListener.assertListenerStatus();
    assertEquals(payment2.getTransactions().size(), 2);
    PaymentTransaction refundTransaction = payment2.getTransactions().get(1);
    assertEquals(refundTransaction.getTransactionType(), TransactionType.REFUND);
    final List<PaymentAttemptModelDao> attempts = paymentDao.getPaymentAttempts(paymentExternalKey, internalCallContext);
    assertEquals(attempts.size(), 2);
    final PaymentAttemptModelDao refundAttempt = attempts.get(1);
    assertEquals(refundAttempt.getTransactionType(), TransactionType.REFUND);
    // Ok now the fun part starts... we modify the attempt state to be 'INIT' and wait the the Janitor to do its job.
    paymentDao.updatePaymentAttempt(refundAttempt.getId(), refundAttempt.getTransactionId(), "INIT", internalCallContext);
    final PaymentAttemptModelDao attempt2 = paymentDao.getPaymentAttempt(refundAttempt.getId(), internalCallContext);
    assertEquals(attempt2.getStateName(), "INIT");
    clock.addDays(1);
    await().atMost(TIMEOUT, TimeUnit.SECONDS).until(new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            final PaymentAttemptModelDao attempt3 = paymentDao.getPaymentAttempt(refundAttempt.getId(), internalCallContext);
            return "SUCCESS".equals(attempt3.getStateName());
        }
    });
}
Also used : PaymentAttemptModelDao(org.killbill.billing.payment.dao.PaymentAttemptModelDao) Invoice(org.killbill.billing.invoice.api.Invoice) InvoiceItem(org.killbill.billing.invoice.api.InvoiceItem) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) LocalDate(org.joda.time.LocalDate) BigDecimal(java.math.BigDecimal) InvoiceApiException(org.killbill.billing.invoice.api.InvoiceApiException) PaymentApiException(org.killbill.billing.payment.api.PaymentApiException) EventBusException(org.killbill.bus.api.PersistentBus.EventBusException) PaymentTransaction(org.killbill.billing.payment.api.PaymentTransaction) PluginProperty(org.killbill.billing.payment.api.PluginProperty) Payment(org.killbill.billing.payment.api.Payment) UUID(java.util.UUID) Test(org.testng.annotations.Test)

Example 19 with PaymentTransaction

use of org.killbill.billing.payment.api.PaymentTransaction in project killbill by killbill.

the class TestPaymentProcessor method testNotifyPendingPaymentOfStateChanged.

@Test(groups = "slow")
public void testNotifyPendingPaymentOfStateChanged() throws Exception {
    final String paymentExternalKey = UUID.randomUUID().toString();
    final Iterable<PluginProperty> pluginPropertiesToDriveTransationToPending = ImmutableList.<PluginProperty>of(new PluginProperty(MockPaymentProviderPlugin.PLUGIN_PROPERTY_PAYMENT_PLUGIN_STATUS_OVERRIDE, PaymentPluginStatus.PENDING, false));
    // Create Pending AUTH
    final String authorizationKey = UUID.randomUUID().toString();
    final Payment authorization = paymentProcessor.createAuthorization(true, null, account, null, null, TEN, CURRENCY, paymentExternalKey, authorizationKey, null, null, SHOULD_LOCK_ACCOUNT, pluginPropertiesToDriveTransationToPending, callContext, internalCallContext);
    final PaymentTransaction pendingTransaction = authorization.getTransactions().get(0);
    Assert.assertEquals(pendingTransaction.getTransactionStatus(), TransactionStatus.PENDING);
    final UUID transactionId = pendingTransaction.getId();
    // Override plugin status of payment
    mockPaymentProviderPlugin.overridePaymentPluginStatus(authorization.getId(), transactionId, PaymentPluginStatus.PROCESSED);
    // Notify that state has changed, after changing the state in the plugin
    final Payment updatedPayment = paymentProcessor.notifyPendingPaymentOfStateChanged(account, transactionId, true, callContext, internalCallContext);
    verifyPayment(updatedPayment, paymentExternalKey, TEN, ZERO, ZERO, 1);
    final PaymentTransaction updatedTransaction = updatedPayment.getTransactions().get(0);
    Assert.assertEquals(updatedTransaction.getTransactionStatus(), TransactionStatus.SUCCESS);
}
Also used : PaymentTransaction(org.killbill.billing.payment.api.PaymentTransaction) PluginProperty(org.killbill.billing.payment.api.PluginProperty) Payment(org.killbill.billing.payment.api.Payment) UUID(java.util.UUID) Test(org.testng.annotations.Test)

Example 20 with PaymentTransaction

use of org.killbill.billing.payment.api.PaymentTransaction in project killbill by killbill.

the class TestInvoicePayment method testWithFailedPaymentFixedToSuccess.

@Test(groups = "slow")
public void testWithFailedPaymentFixedToSuccess() throws Exception {
    // Verify integration with Overdue in that particular test
    final String configXml = "<overdueConfig>" + "   <accountOverdueStates>" + "       <initialReevaluationInterval>" + "           <unit>DAYS</unit><number>1</number>" + "       </initialReevaluationInterval>" + "       <state name=\"OD1\">" + "           <condition>" + "               <timeSinceEarliestUnpaidInvoiceEqualsOrExceeds>" + "                   <unit>DAYS</unit><number>1</number>" + "               </timeSinceEarliestUnpaidInvoiceEqualsOrExceeds>" + "           </condition>" + "           <externalMessage>Reached OD1</externalMessage>" + "           <blockChanges>true</blockChanges>" + "           <disableEntitlementAndChangesBlocked>false</disableEntitlementAndChangesBlocked>" + "       </state>" + "   </accountOverdueStates>" + "</overdueConfig>";
    final InputStream is = new ByteArrayInputStream(configXml.getBytes());
    final DefaultOverdueConfig config = XMLLoader.getObjectFromStreamNoValidation(is, DefaultOverdueConfig.class);
    overdueConfigCache.loadDefaultOverdueConfig(config);
    clock.setDay(new LocalDate(2012, 4, 1));
    final AccountData accountData = getAccountData(1);
    final Account account = createAccountWithNonOsgiPaymentMethod(accountData);
    accountChecker.checkAccount(account.getId(), accountData, callContext);
    checkODState(OverdueWrapper.CLEAR_STATE_NAME, account.getId());
    paymentPlugin.makeNextPaymentFailWithError();
    final DefaultEntitlement baseEntitlement = createBaseEntitlementAndCheckForCompletion(account.getId(), "bundleKey", "Shotgun", ProductCategory.BASE, BillingPeriod.MONTHLY, NextEvent.CREATE, NextEvent.BLOCK, NextEvent.INVOICE);
    addDaysAndCheckForCompletion(30, NextEvent.PHASE, NextEvent.INVOICE, NextEvent.PAYMENT_ERROR, NextEvent.INVOICE_PAYMENT_ERROR);
    invoiceChecker.checkChargedThroughDate(baseEntitlement.getId(), new LocalDate(2012, 6, 1), callContext);
    final List<Invoice> invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), false, callContext);
    assertEquals(invoices.size(), 2);
    final Invoice invoice1 = invoices.get(0).getInvoiceItems().get(0).getInvoiceItemType() == InvoiceItemType.RECURRING ? invoices.get(0) : invoices.get(1);
    assertTrue(invoice1.getBalance().compareTo(new BigDecimal("249.95")) == 0);
    assertTrue(invoice1.getPaidAmount().compareTo(BigDecimal.ZERO) == 0);
    assertTrue(invoice1.getChargedAmount().compareTo(new BigDecimal("249.95")) == 0);
    assertEquals(invoice1.getPayments().size(), 1);
    assertEquals(invoice1.getPayments().get(0).getAmount().compareTo(BigDecimal.ZERO), 0);
    assertEquals(invoice1.getPayments().get(0).getCurrency(), Currency.USD);
    assertFalse(invoice1.getPayments().get(0).isSuccess());
    assertNotNull(invoice1.getPayments().get(0).getPaymentId());
    final BigDecimal accountBalance1 = invoiceUserApi.getAccountBalance(account.getId(), callContext);
    assertTrue(accountBalance1.compareTo(new BigDecimal("249.95")) == 0);
    final List<Payment> payments = paymentApi.getAccountPayments(account.getId(), false, true, ImmutableList.<PluginProperty>of(), callContext);
    assertEquals(payments.size(), 1);
    assertEquals(payments.get(0).getPurchasedAmount().compareTo(BigDecimal.ZERO), 0);
    assertEquals(payments.get(0).getTransactions().size(), 1);
    assertEquals(payments.get(0).getTransactions().get(0).getAmount().compareTo(new BigDecimal("249.95")), 0);
    assertEquals(payments.get(0).getTransactions().get(0).getCurrency(), Currency.USD);
    assertEquals(payments.get(0).getTransactions().get(0).getProcessedAmount().compareTo(BigDecimal.ZERO), 0);
    assertEquals(payments.get(0).getTransactions().get(0).getProcessedCurrency(), Currency.USD);
    assertEquals(payments.get(0).getTransactions().get(0).getTransactionStatus(), TransactionStatus.PAYMENT_FAILURE);
    assertEquals(payments.get(0).getPaymentAttempts().size(), 2);
    assertEquals(payments.get(0).getPaymentAttempts().get(0).getPluginName(), InvoicePaymentControlPluginApi.PLUGIN_NAME);
    assertEquals(payments.get(0).getPaymentAttempts().get(0).getStateName(), "RETRIED");
    assertEquals(payments.get(0).getPaymentAttempts().get(1).getPluginName(), InvoicePaymentControlPluginApi.PLUGIN_NAME);
    assertEquals(payments.get(0).getPaymentAttempts().get(1).getStateName(), "SCHEDULED");
    // Verify account transitions to OD1
    addDaysAndCheckForCompletion(2, NextEvent.BLOCK);
    checkODState("OD1", account.getId());
    // Transition the payment to success
    final PaymentTransaction existingPaymentTransaction = payments.get(0).getTransactions().get(0);
    final PaymentTransaction updatedPaymentTransaction = Mockito.mock(PaymentTransaction.class);
    Mockito.when(updatedPaymentTransaction.getId()).thenReturn(existingPaymentTransaction.getId());
    Mockito.when(updatedPaymentTransaction.getExternalKey()).thenReturn(existingPaymentTransaction.getExternalKey());
    Mockito.when(updatedPaymentTransaction.getTransactionType()).thenReturn(existingPaymentTransaction.getTransactionType());
    Mockito.when(updatedPaymentTransaction.getProcessedAmount()).thenReturn(new BigDecimal("249.95"));
    Mockito.when(updatedPaymentTransaction.getProcessedCurrency()).thenReturn(existingPaymentTransaction.getCurrency());
    busHandler.pushExpectedEvents(NextEvent.PAYMENT, NextEvent.INVOICE_PAYMENT, NextEvent.BLOCK);
    adminPaymentApi.fixPaymentTransactionState(payments.get(0), updatedPaymentTransaction, TransactionStatus.SUCCESS, null, null, ImmutableList.<PluginProperty>of(), callContext);
    assertListenerStatus();
    checkODState(OverdueWrapper.CLEAR_STATE_NAME, account.getId());
    final Invoice invoice2 = invoiceUserApi.getInvoice(invoice1.getId(), callContext);
    assertTrue(invoice2.getBalance().compareTo(BigDecimal.ZERO) == 0);
    assertTrue(invoice2.getPaidAmount().compareTo(new BigDecimal("249.95")) == 0);
    assertTrue(invoice2.getChargedAmount().compareTo(new BigDecimal("249.95")) == 0);
    assertEquals(invoice2.getPayments().size(), 1);
    assertEquals(invoice2.getPayments().get(0).getAmount().compareTo(new BigDecimal("249.95")), 0);
    assertEquals(invoice2.getPayments().get(0).getCurrency(), Currency.USD);
    assertTrue(invoice2.getPayments().get(0).isSuccess());
    assertNotNull(invoice2.getPayments().get(0).getPaymentId());
    final BigDecimal accountBalance2 = invoiceUserApi.getAccountBalance(account.getId(), callContext);
    assertTrue(accountBalance2.compareTo(BigDecimal.ZERO) == 0);
    final List<Payment> payments2 = paymentApi.getAccountPayments(account.getId(), false, true, ImmutableList.<PluginProperty>of(), callContext);
    assertEquals(payments2.size(), 1);
    assertEquals(payments2.get(0).getPurchasedAmount().compareTo(new BigDecimal("249.95")), 0);
    assertEquals(payments2.get(0).getTransactions().size(), 1);
    assertEquals(payments2.get(0).getTransactions().get(0).getAmount().compareTo(new BigDecimal("249.95")), 0);
    assertEquals(payments2.get(0).getTransactions().get(0).getCurrency(), Currency.USD);
    assertEquals(payments2.get(0).getTransactions().get(0).getProcessedAmount().compareTo(new BigDecimal("249.95")), 0);
    assertEquals(payments2.get(0).getTransactions().get(0).getProcessedCurrency(), Currency.USD);
    assertEquals(payments2.get(0).getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS);
    assertEquals(payments2.get(0).getPaymentAttempts().size(), 1);
    assertEquals(payments2.get(0).getPaymentAttempts().get(0).getPluginName(), InvoicePaymentControlPluginApi.PLUGIN_NAME);
    assertEquals(payments2.get(0).getPaymentAttempts().get(0).getStateName(), "SUCCESS");
}
Also used : Account(org.killbill.billing.account.api.Account) Invoice(org.killbill.billing.invoice.api.Invoice) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) DefaultOverdueConfig(org.killbill.billing.overdue.config.DefaultOverdueConfig) LocalDate(org.joda.time.LocalDate) BigDecimal(java.math.BigDecimal) PaymentTransaction(org.killbill.billing.payment.api.PaymentTransaction) Payment(org.killbill.billing.payment.api.Payment) ByteArrayInputStream(java.io.ByteArrayInputStream) AccountData(org.killbill.billing.account.api.AccountData) DefaultEntitlement(org.killbill.billing.entitlement.api.DefaultEntitlement) Test(org.testng.annotations.Test)

Aggregations

PaymentTransaction (org.killbill.billing.payment.api.PaymentTransaction)20 Payment (org.killbill.billing.payment.api.Payment)12 PluginProperty (org.killbill.billing.payment.api.PluginProperty)7 PaymentApiException (org.killbill.billing.payment.api.PaymentApiException)6 BigDecimal (java.math.BigDecimal)5 UUID (java.util.UUID)5 Account (org.killbill.billing.account.api.Account)5 InvoicePayment (org.killbill.billing.invoice.api.InvoicePayment)4 CallContext (org.killbill.billing.util.callcontext.CallContext)4 Predicate (com.google.common.base.Predicate)3 ArrayList (java.util.ArrayList)3 LocalDate (org.joda.time.LocalDate)3 Invoice (org.killbill.billing.invoice.api.Invoice)3 Test (org.testng.annotations.Test)3 AccountApiException (org.killbill.billing.account.api.AccountApiException)2 AccountData (org.killbill.billing.account.api.AccountData)2 InternalCallContext (org.killbill.billing.callcontext.InternalCallContext)2 Currency (org.killbill.billing.catalog.api.Currency)2 DefaultEntitlement (org.killbill.billing.entitlement.api.DefaultEntitlement)2 DefaultPayment (org.killbill.billing.payment.api.DefaultPayment)2