You are on page 1of 90

TheOpenSourceEnterpriseBillingSystem

www.jBilling.com

EnterpriseEdition3.2IntegrationGuide

Thisversionpublished:29.08.13
DocumentRevisionNo.:1.5

Copyright2013EnterprisejBillingSoftwareLtd

jBillingIntegrationGuide
Introduction

ThankyouforyourinterestinjBilling!
In this document, we will explore in detail the integration features of jBilling that help external
applications to connect with the billing infrastructure provided by jBilling and perform seamless
interaction.
jBilling provides a comprehensive set of GUI enabled features for viewing, managing, and
keeping track of all billing and invoicing operations for your organization. Along with its core
functionality, jBilling provides a rich integration layer that enables your applications to tightly
interact with the billing infrastructure and streamline all billingrelated operations into your
organization'sworkflow.
This documentcontains valuableinformationforapplicationdevelopers andarchitects whatwant
to integrate jBilling with their own systems, or perform actions in jBilling from external
applications. Here, you'll find a comprehensive reference to the jBilling Web Services APIs and
an introductory examples including the glue code that explains how many of these integration
taskscanbeaccomplished.

TheNeedforIntegration
Applicationsneedtointerfacewithother
applications.Moreso,forabilling
applicationthatcontainssignificant
informationaboutthingslikeCustomer
Status,PaymentsOverdue,Subscriptions
forCustomeretc.Thisinformationislikely
tobeimportantinputsfordecisionmaking
inotherbusinessapplicationsand
processes.

Aselfcontainedbillingapplication,onthe
otherhand,hasanotherbigdrawback:to
keepitupdated,youwouldneeda

Copyright2013EnterprisejBillingSoftwareLtd

separatedataentryprocessthatfeedsthebillingdatafromyoursystemintothebilling
application.Thisisbothtimeandresourceconsuming.Forexample:
Let's suppose you own a website with a member's area. In order to access the member area,
the customer would need to pay a monthly fee. Ifthebillingdatais keptseparately,whenanew
user subscribes to the website, the billing data would need to wait until somebody enters data
into the billing application, and after the payment is cleared the same person would need to
updatethewebsiteinordertograntaccesstotheuser.
The manual authorization process would have a heavy impactonthesite's functionality.Evenif
there are instant payment options, such as credit cards, the user would have to wait for a
manualoperationtotakeplacebeforebeinggrantedaccesstotheservicehepaidfor.
jBilling solves this problemby renderingcommonbillinganddataretrievaloperations availableto
your system via service calls. With a relatively small programming effort, you can integrate the
billing application with your own systems or business processes, so that when the new user
signs in, you can instantly pass the datatothebillingapplication,havethepaymentclearedand
grantaccesswithouttheneedformanualoperations.
As we'll see in the following sections, integration services in jBilling are almost as
comprehensiveas thebillingfunctionality providedthroughthestandardwebinterface.Usingthe
integration layer, you can retrieve lots of useful data from jBilling, as well as create, update or
deleteUsers,Items,OrdersandInvoices.

jBillingIntegrationRequirements
jBillingprovidesits'integration'servicesinthreedistinctflavors:
1. SOAP(SimpleObjectAccessProtocol)
2. Hessian/Burlap(lightweightwebserviceprotocols)
3. SpringHTTPInvoker
In order to fully acquire, and take advantage of, the informationcontainedherein,youmay need
tohaveatleastabasicgraspofwhatSOAPisandhowitworks.
TolearnaboutHessianandBurlap,visittheirhomepageathttp://hessian.caucho.com
SOAP is a XMLbased 'programminglanguageindependent'protocolforexchanginginformation
over HTTP. Therefore, it enables diverse platforms to communicate without bias. Since jBilling
implements its services through SOAP, even business applications running on nonJava
platformscancommunicatetoorintegratewithjBillingbecauseofitsSOAPsupport.
Hessian is a fast binary web services protocol that works over HTTP, with implementations
available in a number of languages. Like SOAP, it has the advantages of being firewall friendly
and the ability to make use of authentication and encryption, yet it is similar in speed and

Copyright2013EnterprisejBillingSoftwareLtd

bandwidth performance to Java RMI. Hessian 2 provides even much better performance as
compared to its previous version.Burlapis closely relatedtoHessianexceptthatituses human
readable XML instead of binary messages. However, neither Hessian nor Burlap require an
externallydefinedWSDLfile,whichisrequiredbySOAP.
Most examples provided in this document are explained in Java, therefore, some knowledge of
Java programming language would prove very useful. There is still a smallsectiondedicatedto
implementing jBilling integration in other languages such as C#.NET and PHP. Please refer to
your language/platform's documentation in order to determine what specific SOAP support it
provides, and howtomakeuseofit(specifically,howtocallremoteSOAPservices,andhowto
passparametersanddecodethereturnedvalues).
It is also recommended thatyouhaveabasic understandingofjBilling's functionality andusage.
You can find this information in other documents available from jBilling User Guide and
Getting Started. Knowing how the program works is of course necessary to understand the
scope and usage of each service call. Last but notleast,youwillneedarunningcopy ofjBilling
in order to execute the examples containedinthis document.FollowingtheTrendtutorialonthe
Getting Started document is also necessary to generate some of the data required for the
examplestowork.

PreparingjBillingforIntegration
ConfiguringandUsingaRemotingMethod
Configuration
You can make use of the jBilling API in any java application by including the jbilling.jar
and jbillingremotebeans.xmlfiles

in your classpath. Both of these artifacts can be


found in the jbilling/resources/api/folder

that was packaged with the binary jBilling


distribution.
The jbillingremotebeans.xmlfile
contains the Spring configuration for accessing the
jBilling remote webservices API using the JbillingAPIFactory and JbillingAPI
classes. This file contains three different Spring bean configurations, one for each of the 3
supported webservice protocols available in jBilling outofthebox. jBilling comes
preconfiguredwith:
Hessian/Burlap(beanname"apiClient")
SOAP(beanname"apiClient2")
SpringHTTPInvoker(beanname"_apiClient3")

Copyright2013EnterprisejBillingSoftwareLtd

<xml...>
<beans....>
<!HessianRemoteWSBean>
<beanid="apiClient">
<property.../>
</bean>
<!SOAPWSBean>
<jaxws:clientid="apiClient2"/>
<!SpringHTTPInvokerRemoteWSBean>
<beanid="apiClient3">
<property.../>
</bean>
</beans>
These Spring beans connect to the exposed webservices in jBilling and provide access tothe
jBilling integration services. Unlike the others, the Spring HTTP Invoker protocol is an
unauthenticated protocol. If you wish to use Spring HTTP Invoker for integration you'll need to
configure an alternate authentication filter that forces the credentials to be used when making
nonauthenticated API calls. See the section Enabling/Disabling authentication for jBilling
webservicessectionbelowforinformationregardingthis.

Copyright2013EnterprisejBillingSoftwareLtd

SecuringIntegrationAccess
Overview
While integration services could be an extremely useful feature, they dobringupsomesecurity
concerns you'll need to take into account. It is critical that the services are not exposed to
external parties, otherwise it could be possible for them to invoke the same functionality you're
using(and,mostprobably,youdon'twantanoutsidertobeabletocreateapaymentorinvoice).
Therefore, the integration services should be exposed only to properly authorized parties. This
is,atleastinpart,guaranteedby jBilling,sinceby defaultitrequires aclientapplicationtoidentify
itself via a user name/password pair, before servicing any of its requests. It would also be
important to transmit all data over a secure channel, which can be accomplished by using the
SOAPorHessian/BurlapcallsoveranSSLtunnel,somethingwe'llcovershortly.
Ideally, the web services would be exposed only to the server(s) that require it, and any other
parties should be excluded. This can be accomplished by using a firewall application that limits
the IP addresses that have access to jBilling's integration services. Please refer to the
documentation of the Operating System or platform in which your copy of jBilling is to run, in

Copyright2013EnterprisejBillingSoftwareLtd

ordertohavesomeinformationonhowtorestrictaccesstospecificTCPportsinyoursystem.
It is also recommended that all service calls are performed by means of an encryptedchannel,
as provided by the SSL (Secure Socket Layer) protocol. This effectively avoids any threats
related to unauthorized interception or decryption oftheservicecalls.SSLalsoensures thatthe
party you're engaging communication with is actually your intended recipient, nullifying any
impersonationattempts.
In order to determineiftheparty engagedincommunicationis actually whoitis pretendingtobe,
SSL uses certificates. Therefore, in order to establish an SSL connection to jBilling, it could be
requiredtohaveacopyofjBilling'scertificateinyourdevelopmentandproductionsystems.

RestrictingAccesstoKnownIPAddresses
By default, jBilling will accept webservice calls from any IP address. You can change this
behaviourtorestrictAPIclientrequests toknownmachines withinyourownnetwork.Tochange
this, edit the jbilling/jbillingConfig.groovy script and uncomment the
grails.plugins.springsecurity.ipRestrictionsproperty.
IP restriction patterns can be provided as singlevalue strings, or a multivalue list of strings.
TheycanalsouseCIDRmasks,andcanspecifyeitherIPv4orIPV6patterns.
grails.plugins.springsecurity.ipRestrictions=[
'/services/**':'192.168.0.110',
'/hessian/**':['192.168.0.110','192.168.0.111'],
'/httpinvoker/**':'192.168.0.0/24']
NotethatyoucanalwaysaccesstheseURLsfromlocalhost,regardlessoftheIPrestriction.

Enabling/DisablingauthenticationforjBillingwebservices
By default, all calls to jBilling must be authenticated.Inmostcases,this is thedesiredbehavior.
If Spring HTTP Invoker is used to make calls to jBilling, authentication is not available. If the
jBilling server is called by clients withinaninternalnetwork securedfromoutsideaccess,itmay
alsobepreferabletoremovetheneedtoforceclientstoauthenticatethemselves.
You can force any exposed webservice to use a specific set of credentials (instead of asking
for authentication) by editing the jbilling/jbillingConfig.groovy script. Find the
grails.plugins.springsecurity.filterChain.chainMapproperty

and change the


authentication filter set to ignore the default JOINED_FILTERS, and instead use a filter chain
that contains the staticAuthenticationProcessingFilter(copy

the filter chain used


for"/httpinvoker/"):
grails.plugins.springsecurity.filterChain.chainMap=[
'/services/**':'JOINED_FILTERS,exceptionTranslationFilter',
'/hessian/**':'JOINED_FILTERS,exceptionTranslationFilter',

Copyright2013EnterprisejBillingSoftwareLtd

'/httpinvoker/**':
'securityContextPersistenceFilter,staticAuthenticationProcessingFilte
r,securityContextHolderAwareRequestFilter,basicExceptionTranslationFi
lter,filterInvocationInterceptor',

'/**':
'JOINED_FILTERS,basicAuthenticationFilter,basicExceptionTranslation
Filter'
]
The staticAuthenticationProcessingFilter itself is configured in the jBilling
resources.groovyfile.

You'll need to recompile jBilling to access this configuration file so


youcanchangethestaticauthenticationcredentials.

Enabling/Disablingcompanysecuritychecks
If only one company is using the jBilling installation, unnecessary security checks,whichmake
sure onecompany is notaccessinganothercompany's data,canbedisabledtofurtherincrease
performance.Todisablethecheck,editthefollowingfile:
./grailsapp/conf/spring/resources.xml
Comment out or delete the two XML beans under the section AOP: Security / Logging: Bean
idswebServicesSecurityAdviceandwebServicesSecurityAdvisor).

SettingupjBillingtoacceptexternalcalls
As mentioned earlier, jBilling will not accept all external calls it gets, but will requirethecallerto
identify itself with a user name and password in order to service the request. Otherwise, the
request will receive an error in response. This is a simple but effective measure that improves
overall security. Of course,this alsomeans you(orthesystemadministrator)willneedtosetup
anaccountinjBillingthatwillbeauthorizedtoperformexternalcalls.
Once you've followed the Getting Started tutorial and created the initial billing entity, the user
name and password you entered in the entity setup screen will represent the user name and
password of jBilling's administrator account. Youcangrantaccess tothis administratoraccount
(or any other account you create for this purpose) to connect remotely and perform service
calls.
In order todoso,you'llneedtologinas theadministratorandgiveanaccountthe"WebService
APIaccess"permissiontoallowtheaccounttobeusedtoauthenticatewebserviceaccess.
You can do this from either the Roles configuration screen (Configuration > Roles) to grant
access to an entire group ofusers,orby editingtheindividualuserpermissions (Configuration
>Users>Permissions).

Copyright2013EnterprisejBillingSoftwareLtd

AuthenticatingaWebServiceclient
SOAP, Hessian and Burlap all use HTTP Basic authentication to gain access to the jBilling
webservice endpoint. All web service clients must authenticate themselves so that jBilling can
enforcerestrictionsondataaccessandpreventunauthorizedaccesstointegrationservices.
The user name string must contain both the login name of thejBillinguserattemptingtoaccess
AND the company ID of the company you are trying to access. If you do not provide the
companyIDyouwillnotbeabletoauthenticateyourwebserviceclient.
Credentialsmustbeprovidedintheformat:
username="userNamecompanyId"
password="user'spassword"
For example, you can access the Trend webservice using the user name "admin1" and the
password"123qwe".
IfyouarenotsureoftheIDofyourcompany,lookattheENTITYtableinthejBillingdatabase.
SELECT*FROMENTITY

ConnectingtojBilling
SOAP
Once it is properly configured,you'llneedtoaddress allintegrationcalls tojBilling's webservice
endpoint. This endpoint is accessible at the same server where jBilling was deployed, in a
specificURLaddress,whichfollowsthisform:
http://localhost:8080/jbilling/services/api
You can query the service's WSDL (Web Service Description Language) file. It consists of an
XML containing a description of the available service calls and parameters used by each call,
and could be useful if your programming platform provides a way of automatically generating
code for service calls from a WSDL, or you have a tool that can perform test calls (such as
SoapUI).
ToquerytheWSDLfile,you'llneedtoappendthe?wsdlparametertothecall,forexample:
http://localhost:8080/jbilling/services/api?wsdl
BelowisasnapshotoftheWSDLshowingoperationgetLatestInvoice:
<?xmlversion="1.0"encoding="UTF8"?>

Copyright2013EnterprisejBillingSoftwareLtd

<wsdl:definitions
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:tns="http://jbilling/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:ns2="http://schemas.xmlsoap.org/wsdl/soap/http"
xmlns:ns1="http://util.server.jbilling.sapienter.com/"
targetNamespace="http://jbilling/"name="ApiServiceService">
<wsdl:import
namespace="http://util.server.jbilling.sapienter.com/"
location="http://localhost:9090/jbilling/services/api?wsdl=IWebServicesSession
Bean.wsdl">
</wsdl:import>
<wsdl:binding
type="ns1:IWebServicesSessionBean"
name="ApiServiceServiceSoapBinding">
<soap:binding
transport="http://schemas.xmlsoap.org/soap/http"style="document"/>
<wsdl:operation name="getLatestInvoice"> <soap:operation
style="document"soapAction=""/>
<wsdl:input
name="getLatestInvoice">
<soap:body
use="literal"/></wsdl:input>
<wsdl:output
name="getLatestInvoiceResponse">
<soap:bodyuse="literal"/></wsdl:output>
<wsdl:faultname="SessionInternalError">
<soap:fault
name="SessionInternalError"
use="literal"/>
</wsdl:fault>
</wsdl:operation>
</wsdl:binding>
</wsdl>
</xml>

HessianBurlap
TheHessianserviceURLisinthefollowingform:
http://localhost:8080/jbilling/hessian/ApiService
SimilarlyforBurlap:
http://localhost:8080/jbilling/burlap/ApiService

Copyright2013EnterprisejBillingSoftwareLtd

10

SpringHTTPInvoker
TheSpringHTTPInvokerserviceURLisinthefollowingform:
http://localhost:8080/jbilling/httpinvoker/ApiService

IntegratingjBillingtoyourApplication
Overview
This section discusses the approaches availableforintegratingjBillinginyourapplication.While
jBilling exposes a unique Web Services integration API, there areotherways ofinteractingwith
that layer too, based on the technology available to the application developer in the target
system.
Therefore, if your application is written in Java or at has away ofinterfacingwithJava,thenthe
simplest way of integrating jBilling with your application is by making use of the +jBilling Client
API+. The +jBilling client API+ is a pure Java API that another Java program can directly
call/use.
Service calls can also beperformedby means ofplainSOAPorHessian/Burlapcalls.This type
of interaction is useful for those situations in which you cannot use Java as your programming
language (either because your server does not support it or because your application has
alreadybeenwritteninanotherprogramminglanguage).
Generally, it easier to use the jBilling API than hardcoding SOAP or Hessian/Burlap calls
directly.
We'llnowexaminetheabovepossibilitiesandalsoseesomesamplecodeforeachinstance.

ThejBillingClientAPI
The jBilling Client API is a library that contains a set of Java classes that wrap the actual calls
that are made to jBilling. This simplifies the interactionwithjBillingas itcompletely hides thelow
level connection logic, which you would otherwise need to deal with either directly or viaathird
party library (suchas AxisorCXF).BeingJavaclasses,youmustbeworkinginJavaorhavea
wayofinvokingJavafunctionsfromyourprogramminglanguage.
The exactsamefunctioncalls exposedas WebServices areavailablethroughtheAPI.Itsimply
actsasawrapper.
As a subproject of jBilling, the jBilling client API has a few extra advantages. It provides a
standardized interface to jBilling so, even if in the future the SOAP interfaces change or new

Copyright2013EnterprisejBillingSoftwareLtd

11

parameters are added, your code will require little or no modification at all to adapt to those
changes. Last, but not least, its code is Open Source, so that you can get down to the
implementationdetailsifneeded.
The+jBillingclientAPI+iswellequipedtoperformservicecallstojBillinginfourdistinctways:
1.
2.
3.
4.

BymeansofstandardSOAPcalls
ThroughHessiancalls
ThroughBurlapcalls
ThroughSpringHTTPInvokercalls

,ofwhich,youmaychooseonethatbestmeetsyourprojectrequirements.
Hessian generally has the best features on offer: a fast binary protocol comparable in speedto
Java RMI (for Hessian 2), HTTP basedforaccess throughrestrictivefirewalls,thepossibility of
using HTTP authentication and SSL encryption, and library implementations in a number of
languages.
SOAPstillenjoysthebestMultiprogramminglanguagesupport.

The specific calling protocol is hidden in the library's implementation and can be
changed to use any one of the above by simply changing a parameter, and by
making the required libraries available.

TheadvantagesofusingjBillingclientAPI
As discussed earlier, the +jBilling ClientAPI+is by farthemostconvenientmeans ofintegrating
with jBilling as compared to handling SOAP/Hessian calls through custom programming. Here
arefewadditionalreasonstosupportthisargument:
First, the client implementation is cleanly separated from the underlying transport protocol
used. Your code does not change if you switch from SOAPcalls toHessiancalls.Also,ifother
protocols are added in the future, you'll be able to use them as needed without changing your
integrationcode.AnexamplewasjBilling2'sintroductionofHessian/Burlapsupport.
Secondly, the API absorbs most of the housekeeping activities you need to perform when
using a SOAP library (such as settingupthecallparameters anddatatypes).Youwilljustneed
to instantiate and populate the correct data structures that willcontaintheinputandoutputdata,
andcalltheAPItotakecareoftherest.
Third, using this API will allow you to use advance deployment features, such as clustering,
load balancing and fail over. Since the API is a layer in between the client (your application),
and the server (jBilling), it is the ideal place to abstract different layouts of the server
deployment, keeping a simplified view from the client. Using these features will simply mean a
changeoftheAPI'sconfigurationfiles,withoutchanginganycode.

Copyright2013EnterprisejBillingSoftwareLtd

12

To get anideaofhowsimpleitcanbetoperformtheintegrationcalls,takealook atthefollowing


code. The first example calls jBilling (using the jBilling client API) to perform a simplecustomer
loginsequence(moreonthislater):
importcom.sapienter.jbilling.server.util.api.JbillingAPI
importcom.sapienter.jbilling.server.util.api.JbillingAPIFactory
importcom.sapienter.jbilling.server.user.UserWS
IntegeruserId=null
JbillingAPIapi=JbillingAPIFactory.getAPI()
try{
userId=api.getUserId(username)
UserWSuserData=api.getUserWS(userId)
}catch(Exceptione){
System.out.println("Invalid username: the user does not
exist!")
}
Compare the above code with the followingexample,whichperforms exactly thesamecalls but
usingtheApacheAxislibrary:
importjavax.xml.namespace.QName
importjavax.xml.rpc.ParameterNode
importorg.apache.axis.client.Call
importorg.apache.axis.client.Service
importorg.apache.axis.encoding.ser.BeanDeserializerFactory
importorg.apache.axis.encoding.ser.BeanSerializerFactory
Serviceservice=newService()
Callcall=(Call)service.createCall()
call.setTargetEndpointAddress("http://localhost:8080/jbilling/service
s/api")
call.setUsername("myusername")
call.setPassword("mypassword")
call.setOperationName("getUserId")
call.setReturnClass(UserWS.class)
QNameqn=newQName("http://www.sapienter.com/billing","UserWS")
BeanSerializerFactoryser1=newBeanSerializerFactory(
UserWS.class,qn)
BeanDeserializerFactoryser2=newBeanDeserializerFactory(
UserWS.class,qn)
call.registerTypeMapping(UserWS.class,qn,ser1,ser2)

Copyright2013EnterprisejBillingSoftwareLtd

13

try{
IntegeruserId=call.invoke(newObject[]{username})
UserWSuserData=call.invoke(newObject[]{userId})
}catch(Exceptione){
System.out.println("Invalid username: the user does not
exist!")
}
Therefore, a good part of the latter deals with the setup of the Axis SOAP calls, i.e. more
housekeeping than the actual logic of the call. Whereas, the jBilling Client API example works
justaswellwithHessian.SimplychangeanXMLfile,nocodingrequired.
TakeadvantageoftheClientAPI.Youwillprobablywelcomeitssimplicityandconvenience.

UsingthejBillingClientAPI
The Client API classes are packaged in the jbilling_api.jarfile
that is located in your
jBillingdistribution.
The API also makes use of several thirdparty libraries, such as the Log4j and Commons
Logging for logging infrastructure, Spring for configuration and remoting, Apache CXF for
SOAP API calls, and Hessian for Hessian/Burlap support. Thus, you'll need thelog4j.jar,
commonslogging.jarand

spring.jarfiles

in your class path, if your project does not


alreadyincludethem.
These files are in the WEBINFlib@directoryofthejbillingwebappsbilling.warweb
archive,aswell.
The
API
also
requires
a
configuration file, the
jbillingconfjbillingremotebeans.xml@ file, which needs to be added to your project. This file
defines some important parameters that the API will later retrieve and use. More on this in the
nextsection.
Depending on the underlying transport protocol you choose to use (Hessian or SOAP), the
program will require other libraries. These requirements are explained in detail in the sections
below. Once you have set up yourenvironmentforusingthejBillingClientAPI,youcanusethe
library by using a factory method to retrieve an API interface, which you'll laterusetoplacethe
integrationcall.YoucanretrieveaninterfacetotheAPIinthefollowingmanner:
JbillingAPIapi=JbillingAPIFactory.getAPI()
The JbillingAPIobject

allows you to place integration calls directly. Each call performs a


specific functionality. For example: api.getUserId()retrieves

the jBilling User ID ofauser,


given the username. Obviously, each call requires different parameters and returns different
data,accordingtoitsuse.

Copyright2013EnterprisejBillingSoftwareLtd

14

The rest of the APIlibrary contains classes thatdefinetheparameters youcanuseas inputand


receive
as
output
from
the
service
calls.
For
example,
the
com.sapienter.jbilling.server.user.UserWSclass

contains a set of data regarding


the jBilling user, such as theusername,password,dateofcreation,etc.As usualinJava,most
of these properties are accessible using the getter and setter methods, such as
getUsername()or
setPassword(). Most of the integration effort goes into setting values
into these structures and passing them to the appropriate service call. For example, you'll fill a
UserWS structure and pass it to the createUser()service

call. Most of the API follows this


simplelogic.

Configuration
The jbillingconfjbillingremotebeans.xml file contains some fundamental
parameters that define the connection to the jBilling server you wish to communicate with.This
fileisrequiredbythejBillingAPIlibraryforallconnectionalternatives.
Each connection option is contained within XML bean configuration tag with id="apiClient" as
an attribute. There are four example configuration beans, one for each of the four different
remoting protocols. Only one bean should be enabled/uncommented atany giventime,whichis
the configuration the API will use. The note/comment aboveeachbeanindicates whichprotocol
it configures. Common properties to the SOAP, Hessian and Burlap protocols: username and
password. these values must correspond to a valid account in jbilling that has been granted
permission to execute webservicecalls.Properties andsetupspecific toeachremotingmethod
aredetailedinthesectionsbelow.

TheSOAP(CXF)WebServicesMethod
When using this protocolforservicecalls fromthejBillingClientAPI,youwillneedtoincludethe
CXF library (cxf.jar), which provides support for SOAP. A few support libraries are also
required: XmlSchema.jar, wsdl4j.jar, FastInfoset.jar and neethi.jar You can find all the
required .jar files in your jBilling distribution, in the WEBINFlib@directoryofthe
jbillingwebappsbilling.war@ web archive. All these libraries will need to be added to your
application'sclasspathinordertobeusablebytheAPI.
While SOAP is a solid way of communicating with remote applications, it requires theparties to
exchange XML files when the service call takes place. These files canbequitemassive,anda
great deal of time is wasted in serializing parameters into an XML, and deserializing the
response. For this reason, SOAP is relatively inefficient when it comes to implementing fast
service calls. Therefore, you're advised to use Hessian or Spring HTTP Invoker service,since
theyaremuchfaster.

Properties
address This is the URL that points to the jbilling Web Services endpoint (as

Copyright2013EnterprisejBillingSoftwareLtd

15

discussed in the Connecting to jBilling section of the Preparing jBilling for


Integration chapter of this document). As a part of this property, you may specify the
correct protocol (either http or https) and the port number, if it differs fromthestandard
port(whichis80forHTTPand443forHTTPS).
Forexample:
address="http://localhost:8080/jbilling/services/api"

TheHessian/BurlapMethod
The Hessian and Burlap versions of the Client APIprovides adifferentcommunicationprotocol.
Hessian messaging is in binary format and therefore provides faster calls, whereas Burlap
allows XML messages to be used in the cases where human readability is needed. If using
Hessian or Burlap, hessian.jar is required, and can be found in the WEBINFlib@
directoryofthejbillingwebappsbilling.war@webarchive.

Properties
serviceUrl This is the Hessian Service Url that jBilling exposes (as discussed in
ConnectingtojBillingsectionofthePreparingjBillingforIntegration
chapterofthisdocument)
<property
name="serviceUrl"
value="http://localhost:8080/jbilling/hessian/ApiService"/>
serviceInterfaceThisisthebusinessinterfacethatexposesthebusinessfunctionality
<property
name="serviceInterface"
value="com.sapienter.jbilling.server.util.IWebServicesSessionBean"/>
hessian2 This is a true/false Hessian specific property. It indicates whether Hessian
shouldusethenewerversion2protocol,whichisfasterthanversion1.
Although Hessian 2 is still a draft specification, a value of true is generally recommended for
performance

SpringHTTPInvokerMethod
Spring HTTP Invokers provide a powerfulmechanismofremotecomponentcommunication.On
the server side, services are exposed on top of Spring's infrastructure, using the Spring bean
configuration mechanism. On the client side, Spring provides proxy capabilities that allow
access to HTTP Invoker exposedservices viaabusiness interface.Sinceitis unauthenticated,
you must configure an alternate authentication filter that sets the credentials to be used when

Copyright2013EnterprisejBillingSoftwareLtd

16

makingnonauthenticatedAPIcalls.
This
business
interface
is
specified
as
a
property
of
api:org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean.
This
preconfiguredinjBillingtouseIWebServicesSessionBean

the
is

Properties
serviceUrl The service URL RMI should connect to (as definedintheConnectingto
jBillingsectionofthePreparingjBillingforIntegration
chapterofthisdocument)
Forexample:
<propertyname="serviceUrl"value="rmi://localhost:1199/RmiService"/>
serviceInterfaceThisisthebusinessinterfacethatexposesthebusinessfunctionality
<property
name="serviceInterface"
value="com.sapienter.jbilling.server.util.IWebServicesSessionBean"/>

IntegrationwithnonJavaApplications
If your current application program is not based on the Java platform/language, you can still
integrate your system with jBilling via direct SOAP calls. The beauty of SOAP is that it is
independent ofany particularlanguageorframework inordertobeusable.SOAPis availablefor
many, if not all, oftheprogramminglanguages commonly usedforWeb.Inthis document,we've
limited ourselves to provide two of the most usedprogramminglanguages forWebapplications,
besides Java i.e.C#.NETandPHP.BothprovideSOAPsupport.Ifyoursystemofchoiceis not
one of these, please refer to your language's documentation for clues on how to use SOAP
service calls effectively.Youcanhoweverusetheseexamples as aguidelineonhowtoperform
specificoperationswithjBilling.
The provided examples perform the same login sequence as seen in an earlier section of this
document, but implementing it in each of the languages andplatforms.Oncetheimplementation
in your specific language is clear, we advise you to follow the Integration Tutorial as well,
sinceitprovides usefulinsightintothepurposeofsomeofthemostusedwebservicecalls.This
information should be of interest even if your system is not built on Java, as it explains the
purposeofthecalls,ratherthantheirspecificJavaimplementation.

IntegrationwithC#.NET
C# .NET provides seamless SOAP support, which requires no extra resources to be added to
your application's execution environment. Please refer to the MSDN resources for latest

Copyright2013EnterprisejBillingSoftwareLtd

17

informationonwhatsupportoptionsyouhave.
The difficult part in implementing SOAP on C# is to map the input and output parameters ofthe
web call into appropriate data structures. Since there are many different calls, it quickly gets
difficulttocreateallthenecessaryclasses.
Therefore, a handy utility, distributed as part of the Visual Studio&reg distribution, is the
wsdl.exe. This utility takes careofconvertingaWSDLfileintoappropriatedatastructures and
creates an output file that contains a class that performs allwebservicecalls.Youcanfindthis
commandlinetoolintheVisualStudio8SDKv2.0Bindirectory ofyourVisualStudioinstallation.
Consult your Visual Studio documentation or just call wsdl.exe with no parameters to obtain
someinformationonhowtoinvokethistoolandwhatparametersareacceptable.

If you use SoapUI,anOpenSourcetoolfortestingandhandlingwebservices,youcanalsoset


this program to generate the necessary .NET files (it supports generation of Managed C++,
VisualBasic and J# code, as well as C#). Simply indicate the location of the above mentioned
wsdl.exetoolinyoursysteminthePreferences dialog,connecttothejBillingwebserviceurl(as
defined earlier) from SoapUI, and click on Tools > .NET 2.0 Artifacts inthemainmenu.You'll
be presented with a set of generation options (WSDL file to use as input, output directory, the
usernameandpasswordtopasstotheservice,etc.).

Once the class containing all the web service definitions has been generated (which will be
named WebServicesSessionLocalService.cs), it is a simple matter of using the
generatedclassinyourcode,inawaythatisakintothejBillingClientAPIforJava:
usingWebServicesSessionLocalService
//createtheinterfaceinstanceoftheclass.
WebServicesSessionLocalService
service
WebServicesSessionLocalService()
intuserId=service.getUserId(username)
if(userId>0){
UserWSuserData=service.getUserWS(userId)
}

new

IntegrationwithPHP
PHP provides SOAP support via an add on library (distributed with PHP itself). You'll need to
activate the library support in your PHP.INI file and probably need a library file (libxml) to be
present in your systeminordertousetheSOAPsupport(refertothePHPmanualfordetails on
howtoactivateSOAPsupport).
In order to automate the generation of input and output parameters for yourSOAPrequest,you
may use the PEAR library, which comes with the default PHP installation (unless you've used

Copyright2013EnterprisejBillingSoftwareLtd

18

thewithoutpearconfigurationoptionduringinstallation).
PEAR can generate the PHP code for the dataclasses oritcangeneratetheclasses onthefly
for immediate usage on the program. While the first option is the recommended procedure (this
way you can avoid parsing and generating the WSDL file each time your code executes), for
simplicity we'll demonstrate the use of the PEAR module with the second option, using the
classesonthefly:
require_once'SOAP/Client.php'
$requestParams=array('user'=>'admin','pass'=>'asdfasdf')
$wsdl
=
SOAP_WSDL('http://localhost:8080/jbilling/services/api?wsdl',
$requestParams)
$client=$wsdl>getProxy()
$userIdParams=array('in0'=>$username)
$result=$client>getUserId($userIdParams)
$userId=$result>getUserIdReturn
$userDataParams=array('in0'=>$userId)
$result=$client>getUserWS($userId)
$userData=$result>getUserWSReturn

new

This is quite straightforward, as the PEAR library has donemostofthedirty work ofparsingthe
WSDL and setting up the calls. The $requestParamsis
an associative array containing the
user name and passwordforthejBillingauthentication.Parameters forthewebservicecalls are
passedinassociativearraysaswell.
If you wish to generate the code for the web service calls foruseintheprogramwithouthaving
to parse the WSDL every time, you can explore how to generate the code and save it to a file
withthe$wsdl>generateProxyCode()functioncalloftheSOAP_WSDLobject.

AsimplePHPexampletocreatecustomerinjBilling:
<?php
require_once("../src/JbillingAPIFactory.php")
$api=jbillingAPIFactory::getAPI(
"http://localhost:8080/jbilling/services/api?wsdl",
"admin1","123qwe",JBILLINGAPI_TYPE_CXF)
$UserWS=newUserWS()
$ContactWS=newContactWS()

Copyright2013EnterprisejBillingSoftwareLtd

19

$CreditCardDTO=newCreditCardDTO()
$MetaField1=newMetaFieldValueWS()
//USERCREATIONPROCESS
//DefinejBillinguserproperties
$UserWS>setId(0)
$UserWS>setUserName("Php_Test_Customer1")
$UserWS>setPassword("secret123")
$UserWS>setLanguageId(1)//English
$UserWS>setMainRoleId(5)//Customer
$UserWS>setRole("Customer")
$UserWS>setStatusId(1)//Active
$UserWS>setSubscriberStatusId(1)//Prepaid
$UserWS>setAccountTypeId(1)//Basic
//Definecontactdatafortheusercreated
$ContactWS>setFirstName("Test")
$ContactWS>setLastName("PhpCustomer")
$ContactWS>setPhoneNumber("1234567890")
$ContactWS>setEmail("test@test.com")
$ContactWS>setAddress1("123AnywhereSt")
$ContactWS>setCity("SomeCity")
$ContactWS>setStateProvince("SomeState")
$ContactWS>setPostalCode("12345")
$ContactWS>setFieldNames(array())
//Applycontactobjecttousercontactproperty
$UserWS>setContact($ContactWS)

Copyright2013EnterprisejBillingSoftwareLtd

20

//Definecreditcarddatafortheuserbeingcreated
$CreditCardDTO>setName("PHPTesting")
$CreditCardDTO>setNumber("4012888888881881")
$CreditCardDTO>setSecurityCode(123)
$CreditCardDTO>setType(2)//Visa
//DefinedateasISO8601format
$CreditCardDTO>setExpiry(date("c",strtotime("now")))
//Addthecreditcardtotheusercreditcardproperty
$UserWS>setCreditCard($CreditCardDTO)
//Definemetafields
$MetaField1>setFieldName("contact.email")
$MetaField1>setStringValue("test@gmail.com")
$MetaField1>setGroupId(1)
$MetaField1>setDisabled(false)
$MetaField1>setMandatory(false)

//Addmetafieldstouser
$UserWS>setMetaFields(array($MetaField1))
//CREATETHEUSER
try{
print_r("Initializingcustomercreation..")
$result=$api>createUser($UserWS)
print_r($result)
print_r("Customercreated.")
}

Copyright2013EnterprisejBillingSoftwareLtd

21

catch(JbillingAPIFactory$e){
print_r("Exception:"+$e)
}
?>

AnIntegrationTutorial
Overview
This sectionprovides anintroductiontotheuseofjBillingintegrationcalls.Itbuilds onthe'Trend'
tutorial found in jBilling's Getting Started guide. As such, if you wish to follow the examples in
this section, you'll need to follow the Getting Started Guide tutorial, creating the Trend entity
and adding the Items andOrders.Theexamples inthis sectionwillmainly usethe+jBillingclient
API+. If you're unable to use this API (most probably because yoursystemdoes notmakeuse
of the Java programming language), you'll need to substitute the API calls with direct SOAP
requests. Please, refer to the Integrating jBilling to your Application chapter, which explains the
options for performing service calls to jBilling in more detail and provides examples for some
programminglanguagesandSOAPAPIsavailable.

TheTrendWebsite
In the Getting Started guide, you were introduced to jBilling's capabilities by means of a small
tutorial centered around a hypothetical 'Trend' company, which runs a website. Following the
tutorial, you were able to create the Trend entity, added an Item and created an Order and an
Invoice. We'll build on this example, examining how jBilling's integration features could be
appliedtotheTrendwebsite,whichneedstointegratewithjBilling.

Controllingaccesstothe'Paid'Areaofthewebsite
Being a paid service, the Trend website obviously needs to determine whether each user that
enters the site is a paying customer or not, in order to provide its services only to those that
have paid for it. This can be accomplished by the use of the usual user name/password pair,
which will be provided to each customer at the end of the subscription process, once the first
paymenthascleared.

Copyright2013EnterprisejBillingSoftwareLtd

22

Of course, the invoicing and paymentarehandledby jBilling,thereforethewebsiteneeds away


ofknowingwhenthegivenusernamehasbecomeapayingcustomer.
A solutioncouldbetomaintainalocalrecordofcustomers andcheck eachloginattemptagainst
it, but this actually represents a problem: how would the program know when a customer has
paid or not? Without any integration calls, someone would have to keep the data in this record
updated,amanualoperationthatcouldintroduceerrorsandtakestime.
Another important consideration is that the website charges its customers a monthly fee. This
means the status of customers could change at any time, if the user, for example,has notpaid
the fee for the current month (it would fall back to nonpaying). A local record of customers
wouldnothavethisinformation,atleastnotuntilthenextmanualupdate.
The solution is throwing in an integration call to jBilling to ensure thecustomerathandhas paid
his fee and is authorized to access the website's resources. jBilling takes care of checking its
internal data and determines if the client's payment has been processed and whether his
subscriptionisstillvalid.
The website's login form retrieves the customer's username and password, performs any local
validations andchecks theuser's status injBilling(whichwillindicatehis currentpaymentstatus
andthereforewhetherheshouldbeauthorizedtologinornot).
The first step (regarding integration calls and not local validation) is therefore to retrieve the
jBilling's +User ID+ number, and request the user's data, so that the current status can be
determined.Thesequencewouldbe:
importcom.sapienter.jbilling.server.util.api.JbillingAPI
importcom.sapienter.jbilling.server.util.api.JbillingAPIFactory
importcom.sapienter.jbilling.server.user.UserWS
/*
*WeassumetheStringvariable"username"containstheusername
*stringasenteredbytheuserintheloginform.
*/
IntegeruserId=null
//Createandinitializethe*j*BillingAPI.
JbillingAPIapi=JbillingAPIFactory.getAPI()
booleancanLogin=false
try{
userId=api.getUserId(username)
if(userId==null){
/*
* This shouldn't happen as the API should issue an
exceptionifthe
*userdoesnotexist,buttestitanyway.Inthiscase,
wesimply
*generateanexceptionthatiscatchedlaterinthis

Copyright2013EnterprisejBillingSoftwareLtd

23

block
*ofcode.
*/
}
//Withtheuseridjustretrieved,wecanquerytheuser's
data.
UserWSuserData=api.getUserWS(userId)
/*
*Theuserdatacontainsmanyinformationabouttheuser,butin
*thiscasewe'remostlyinterestedinthestatusIdfieldofthe
*UserWSclass.
*Thisfieldvaluesare:1=active,2=Overdue1,3=Overdue2,
*4=Overdue3,5=Suspended1,6=Suspended2,7=Suspended3,
*8=Deleted.StatusIdsfrom1through4indicatetheuseris
able
*tologin,allothercodescannotlogin.
*/
intstatusId=userData.getStatusId().intValue()
if(statusId>0&&statusId<=4){
/*
*Theusercanlogintothesystem,ashiscurrentstatus
isok.
*Justprintanoticeincasehe'slatewithhislast
payment.
*/
canLogin=true
System.out.println("Usercanlogin")
if(statusId!=1){
System.out.println("Theuser'spaymentisoverdue!")
}
}
}catch(Exceptione){
/*
*TheuserdoesnotexistinJbilling'srecords.Thelogin
request
*shouldbedenied,andperhapsanerrormessageissuedbackto
the
*caller.Here,wejustprintanerrormessagetostdout.
*/
canLogin=false
System.out.println("Invalid username: the user does not
exist!")
}
if(canLogin){

Copyright2013EnterprisejBillingSoftwareLtd

24

//Hereyoucangrantaccesstothereservedarea.
}else{
//Hereyoucandenyentrancetothereservedarea.
}
As you can notice from this example, using the jBilling API is very straightforward and simple.
The burden of setting input and output parameters for the call has been hidden in the
implementation of the library, and calls seem simpler. Take a look at the sample code in the
Integration with nonJava applications section to see why we strongly recommend this
approach for Java applications. And, as a bonus, you can easily switch between SOAP calls
andHessiancallswithjustachangeinanXMLfile!
Intheabovecode:
1. Weacquiretheuser'sIDwiththecalltoapi.getUserId()
2. UsethatIDtoretrievetheuser'saccountdataviacalltoapi.getUserWS()
3. With the user data at hand, we can check if the user's status in jBilling warrants his
entrancetothepaidarea.
TheflagcanLoginissetsothatwecanlaterdeterminewhatresponsetogivetotheuser.
There's even a simpler way to login into the system: the authenticate() function call
requires two Stringarguments (usernameandpassword)andreturns a0iftheuseris inastate
that allows entrance to the paid area, whereas anonzeroresponseindicates theuserdoes not
exist or is in disabled or suspended state. It however does not provide information about what
specificstatetheuserisin,orifitisoverdueornot.
Aquickexampleusingthisfunctionwouldbe:
importcom.sapienter.jbilling.server.util.api.JbillingAPI
importcom.sapienter.jbilling.server.util.api.JbillingAPIFactory
importcom.sapienter.jbilling.server.user.UserWS
//Createandinitializethe*j*BillingAPI.
JbillingAPIapi=JbillingAPIFactory.getAPI()
Integerresult=api.authenticate(username,password)
if(result.intValue()==0){
//Theuserisabletologing.
}else{
//Theusercannotlogin.Thereturnvalueindicateswhy.
}

TrialPeriodManagement
You can easily set up trial accounts so that wouldbe customers can enter your paid area for

Copyright2013EnterprisejBillingSoftwareLtd

25

free before actually being charged. Since a trial period in jBilling is managed through a normal
order, this will also give a practical demonstration of how orders can be entered via the
integrationcalls.
jBilling allows you to practice two different trial period policies: with or without preauthorization.
Preauthorized trial periods require the user to enter payment information (usually in theformof
credit card data), which will be validated before the trial period can begin. Non preauthorized
trialperiodsdonotrequirethisvalidationphase.
Trial periods are managed by simply delaying the Active Sincedateofthepurchaseorderby a
number of days equal to the Trial Period. Let's say Trend wishes to grant a free 15 day trial
period to new customers, so we'regoingtoenterorders withanActiveSincedateofTODAY+
15.
This means the login code we just saw will work correctly for trial customers as well. Theuser
appears as Active , but the invoicing will not take place until the order becomes active. In
addition, when preauthorization is required, you'll need to provide some payment information,
thatwillbevalidatedbeforetheorderinsertionendscorrectly.
When the trial period ends, the order will become active and jBilling will automatically start
invoicing the customer. If the customer changes his mindandwishes tocancelhis membership
to the site (either before the trial expires or afteractualinvoicinghas takenplace),you'llhaveto
provide a cancellation page that will take care of deleting active orders, so that no further
automaticinvoicingtakesplace.We'lltakecareofthecancellationcodeinthenextsection.
We willneedtorequestallnecessary datafromtheuser.Sincewewillbecreatinganewuserin
jBilling, we will require the user to enter the user name/password pair she intends to use to
access the site in the future. This is the minimal information we'll need to successfully call the
user creation service for a non preauthorized trial, but in production code you would probably
need to add contact information to the user record, and if you're implementing preauthorized
trials, you'll need to request some payment information as well. These can be added as
parameterstotheusercreationprocess.
Once the new user is created, we can add an order to that userwiththeActiveSincedateset
to TODAY + 15, and Active Until date set to null , which indicates the Order is permanently
active and will continue to invoice until it is canceled. We are assuming the Item has been
created as indicated in the Getting Started Guide, so that we have a 'Banners' category and a
'Front Page Banner Monthly Fee' item created under this category. In the example,weassume
the Item ID code is '1', in a more realistic situationyoucouldhaveseveralitemtypes tochoose
from, or you would otherwise need to determine what the Item ID is from the jBilling user
interface.
We also assume the periodicity code for the orderis '2',whichmaps tomonthly payments.This
however depends on the setup of the specific instance of jBilling, you can determine what
specificcodeeachperiodhasbyconsultingthejBillingUserGuideunderOrders>Periods.

Copyright2013EnterprisejBillingSoftwareLtd

26

The item we're creating an order for is, according to the Getting Started Guide, the fee for
displaying a banner in Trend's frontpage. To keep the example consistent, let's say the login
procedure illustrated above allows the customer to login to the area where he can upload and
update the banner itself, and perhaps see some statistics for his banner's exposure. The code
that performs the banner rotation would probably need to determine what banners to show
(maybe a local database, which of course needs to be kept in sync with billingdata,something
we'llcoverinanothersection).
/*
*WeassumetheStringvariables"username"and"password"contain
the
* new user's login data asenteredbytheuserinthetrial
registrationform.
*/
IntegeruserId=null
//Createandinitializethe*j*BillingAPI.
JbillingAPIapi=JbillingAPIFactory.getAPI()
try{
//Createtheuser'srecord.
UserWSnewUser=newUserWS()
//Fillinthenewuser'sdata.
newUser.setMainRoleId(newInteger(5))//Role"5"="Customer".
newUser.setStatusId(newInteger(1))//Status"1"="Active".
newUser.setUserName(username)
newUser.setPassword(password)
//RefertoAppendixAforlanguagecodes.
newUser.setLanguageId(newInteger(1))
//RefertoAppendixAforcurrencycodes.
newUser.setCurrencyId(newInteger(1))
newUser.setCreateDatetime(newjava.util.Date())//=now

//Ifyou'reenteringcreditcardinformation,you'llneedto
create

//aCreditCardDTOobjectandfillitwithdata,andassignthe
data

//tothisuserviathesetCreditCard()methodofUserWS.Same
goesfor

// Contact info,aContactDTOobjectcanbeassignedvia
setContact().
//Callthe"create"methodontheapitocreatetheuser.
IntegernewUserId=api.createUser(newUser)
//Nowlet'screateaneworderline.
OrderLineWSline=newOrderLineWS()
line.setPrice(newBigDecimal(10))//Orderprice=10.
line.setTypeId(newInteger(1))//Type1="Item".
line.setQuantity(newInteger(1))//Quantity=1

Copyright2013EnterprisejBillingSoftwareLtd

27

line.setAmount(newBigDecimal(10))//Totalamount=10
line.setDescription("BanneronFrontPage")
line.setItemId(newInteger(1))
//Nowcreateanorderthatcontainstheorderlinejustcreated.
OrderWSnewOrder=newOrderWS()
newOrder.setUserId(newUserId)
newOrder.setPeriod(newInteger(1))
//Nowaddtheorderlinecreatedabovetothisorder.
newOrder.setOrderLines(newOrderLineWS[]{line})
newOrder.setBillingTypeId(newInteger(1))//Prepaidorder.
GregorianCalendaractiveSinceDate=newGregorianCalendar()
activeSinceDate.add(Calendar.DATE,15)
newOrder.setActiveSince(activeSinceDate.getTime())
//Nowcreatetheorder.
IntegernewOrderId=api.createOrder(newOrder)
}catch(Exceptione){
/*

*Therewasanerrorduringtheuserorordercreation.Just
printan
*errormessage.
*/
System.out.println("Errorinuserorordercreation")
}
A few IMPORTANT details need to be pointed out: first, we create the user and order in two
separate steps, since we wanted toshowhowbothoperations workedontheirown,buttheAPI
provides a way of doing both operations in one step. Instead of calling
api.createUser(newUser) and api.createOrder(newOrder), you can just call
api.create(newUser,newOrder).
This call will also charge the user credit card,butnotas apreauthorization,butas afullcharge
(capture).Themethod'create'doesfoursteps:
1.
2.
3.
4.

Creationoftheuser
Creationofthepurchaseorder
Generationofaninvoicebasedonthispurchaseorder
Processingofthepaymenttogettheinvoicedpaid.

In the example, we only got the first two steps, which is consistent with the requirements of a
free trial: the invoice and payment should only happen when the trial is over and the 'active
since' of the order reached. If you do the singlestep 'create' call, be sure to set the User ID of
the new order to '1',sinceyou'recreatingtheuseratthesametimeyou'readdingtheorderand
thereforethecorrectUserIDisnotyetknown.
If you wish to do preauthorization, you'll need to fillcreditcardinformationandaddittothenew

Copyright2013EnterprisejBillingSoftwareLtd

28

userdata.Then,forthesecondstep(ordercreation)youshouldcall
api.createOrderPreAuthorize(newOrder)
, instead of calling the createOrder()method.

Note that in this case you cannot use the


create(newUser,newOrder)method

indicated above, as it does not dopreauthorization.


Therefore,you'llneedtoperformthetwoseparatesteps.ThecreateOrderPreAuthorize()
method returns a PaymentAuthorizationDTOEx structure, which provides info on the
authorization released. At this point, you're probably most interested in knowing if it was
successful, so just test the boolean result by calling getResult(). The following snippet shows
how:
PaymentAuthorizationDTOEx
payment
=
api.createOrderPreAuthorize(newOrder)
if(payment.getResult()==false){
System.out.println("Yourpaymentwasnotaccepted!Trialnot
active!")
//Sincetheuserhasbeenalreadycreated,youmightwantto
deleteit
}
Keep in mind that if you create the user and the trial order in two separate steps, and so you
could have a situationinwhichtheusergets createdbuttheOrdercouldnotbesubmitted.So,if
the code catches an exception, test if the user exists (For example, if you received a User ID
fromthefirstcallthatisnonnull)tointerceptsuchasituation.
Finally, this does not test whether the user existed previously with that user name. When
creating a user, you can first validate if the user exists, by querying its User ID, as doneinthe
login section above, and display anerrororrequestadifferentusername.Italsodoes notverify
whethertheuserhasalreadycreatedothertrialaccounts.
To intercept situations in which a user creates trial accounts just to cancel them before billing
takes place to create another trial account, ask for some contact information (such as, for
example, a valid email address or just save the IP address of the caller) and verify that this
informationisnotrepeatedinprevioustrialaccounts.

ContactInformation
The users data structure contains fields to keep Contact information along with your jBilling's
user account. Adding or updating contact data is quite simple: you just add it to the user's data
structure whenever you call createUser()or
updateUser(). There's a shortcut call that
allowsyoutoeditcontactinformationaswell:
updateUserContact()
To add contact information to an account, create the ContactWS instance and fill it as

Copyright2013EnterprisejBillingSoftwareLtd

29

necessary. Most data fields in this structure are selfexplanatory, such as postalCode or
faxNumber . For example, the following code snippet creates a ContactWSstructure

andputs
somedataintoit,andlateritpassesittotheusercreationprocess:
//CreatetheContactWSstructure
ContactWScontactInfo=newContactWS()
//Putsomedataintoit
contactInfo.setPostalCode("12345")
contactInfo.setFaxNumber("555123456")
contactInfo.setEmail("foo@bar.com")
//Passthecontactinfototheusercreationcall
//ThisassumesuserDataisanalreadyfilledUserWSstructure.
userData.setContact(contactInfo)
//Nowcreatetheuser
api.createUser(userData)
Here, we pass the contact information in the user creation process, but you couldas wellpass
this information in an updateUser()call

when updating user data, or in a separate call to


updateUserContact()if
youwishtoonly updatecontactinformationandleavetheuserdata
asitis.

CustomContactFields
The User's Contact Information is extensible for adding additional user Contact information.
Thus, two fields of the ContactWSstructure

deserve further understanding: fieldNames and


fieldValues ., which represent custom contactdata.Forexample,let's say youneedtostorethe
user's website address. A quick look at the ContactWSstructure

shows there's no website


field, so you would be left with the option of storing that info in another field not currently used,
butjBillingoffersabetteralternative:CustomContactFields(CCF).
To use CCF you will need toaddittothesystemthroughsomeconfiguration.This is coveredin
anotherdocument,butitboilsdowntotwosimplesteps:
1. addthefieldtothethecontact_field_typetable:
insertintocontact_field_type(id,entity_id,prompt_key,data_type,
customer_readonly)values(432,1,'ccf.web_site','string',1)
1. addthenameofthefieldtothefileApplicationResources.properties:
ccf.web_site=WebsiteURL
Customizing your contact infois quitestraightforward:youneedtoprovidetwoarrays ofstrings.
The first array, fieldNames, contains the IDs for each of the CCFs thatyouwishtospecify a
value for. The second array, fieldValues, holds the actual values for the fields. When
entering custom contact data, you need to initialize both arrays with data and add them to the

Copyright2013EnterprisejBillingSoftwareLtd

30

ContactWSstructure.Aquickexampleexplainshow:
//TheCCFidtosetis432,followingtheaboveexample
publicstaticfinalStringCCF_WEBSITE="432"
//NowwecreatetwostringarraysfortheIdsandvalues.
StringcustomContactIds[]=newString[1]
StringcustomContactValues[]=newString[1]
//Putthevaluesintothearrays.
//thisholdstheuniqueIDforthefield.
customContactIds[0]=CONTACT_WEBSITE
//thisholdstheactualvalue.
CustomContactValues[0]="www.fifa.com"
//SetthecustomfieldsintheContactWSstructure.
//WeassumecontactDataisanalreadycreatedandfilledContactWS
structure.
contactData.setFieldNames(customContactIds)
contactData.setFieldValues(customContactValues)
//Wenowproceedwiththecontactdatacreationprocess.
We defined a constant that holds a unique identifier for the custom contact fields. It will haveto
be equal to the IDoftherowinthecontact_field_typetablethatdefines this field.Inthis case,ID
432 will contain website information. Of course, this constant would ideally be located in a
separate class or externalized to a properties file, to keep things simple we just declared it on
the fly. We then create two String arrays (each containing just one element) and assign the ID
number and field value, respectively. We then assign these arrays to the fieldNames and
fieldValues fields in the ContactWSstructure.

When the api call is performed, the customdata


will be saved along with the rest of the contact data. A fixed length array is of course not very
intuitive, but you can easily convert these two arrays into a api:java.util.Hashtable and use the
IDvalueasanindextotheactualdata.

UpdatingandDeletingUsersandOrders
There are many situations inwhichyouwouldneedtoupdatetheuser's information,suchas for
example when the user changes passwords or address. It is also common that the user
subscribes to a service, or cancels a subscription. These type of events are reflected through
purchase orders in jBilling, you will need a way toupdateorders programmatically.This section
providessomeinsightintotheseoperations.
Updating a user or order is easy enough. You just need to +query its current data, change the
fields you need to update, and call the proper update method+. For example, let's say a user

Copyright2013EnterprisejBillingSoftwareLtd

31

changeshispassword,thesequencetoperformwouldbe:
//Gettheuserinformationfrom*j*Billing
UserWSuserData=api.getUserWS(userId)
//Changethepasswordintheuserdataandsubmititbacktothe
system.
userData.setPassword(newPassword)
api.updateUser(userData)
Here we assume you already have the User ID handy after the used logged in, perhaps as a
sessionvariable.
Therearesimilarfunctions toupdateorders (updateOrder),orderlines (updateOrderLine),
credit
card
information
(updateCreditCard)
and
contact
information
(updateUserContact). They areusedmuchinthesamemanner.Youcanofcoursepopulate
the UserWS data from scratch, instead of querying it from jBilling, ifyouhaveallthenecessary
information handy. You can also delete an userororder,ifnecessary.Themethods are,as you
have probably guessed, deleteUser and deleteOrder. You need only the UserIDorOrderIDto
performthedeletion,nottheentireUserWSorOrderWSstructures.Forexample:
api.deleteUser(oldUser)
This will delete the user. Keep in mind that jBilling does not actually delete the user from the
database, it just marks it as deleted. Of course, when a user gets deleted, so does thecontact
and credit card informationthatwas associatedtotheaccount,andorders aredeactivated(they
will be no longer invoiced). Deleting an order deletes the order lines associated with it, as well.
When you query the status for a user that has been deleted (for example, in the login page),
you'llgetthe'Deleted'statuscodeasresponse.

Theuser'smainorder
jBilling introduces theconceptofamainorderforeachuser.This simply tells jBillingwhichorder
should be the target when executing automated operations such as recurring charges. jBilling
User Guide covers this concept in greaterdetail,herewe'remainly interestedinhowtheuser's
mainordercanbespecifiedormodifiedbymeansofAPIcalls.
The mainorderofausercanbefoundontheUserWSstructure(returnedby getUserWS()),in
field mainOrderId (which contains the unique identifier of the order that acts as main order for
thisuser).So,itiseasytoaccessitwithuserAPIcalls:
//Gettheuserinformationfrom*j*Billing
UserWSuserData=api.getUserWS(userId)
//ReadthemainorderIDintoavariableandset
//anotherorder(retrievedpreviously)asmain.

Copyright2013EnterprisejBillingSoftwareLtd

32

IntegermainOrder=userData.getMainOrderId()
userData.setMainOrderId(newMainOrder)
api.updateUser(userData)
It is also possible to determine if an Order is the current main order by examining the Order's
record (there's a property named isCurrentthat

indicates whethertheorderis themainorder


or not). When creating a new order, you can also set this property to '1' to tell jBilling that the
orderbeingcreatedistobeconsideredthemainorderforitsuser:
OrderWSnewOrder=newOrderWS()
//Setorderparametershere
newOrder.setIsCurrent(Integer.valueOf(1))
//Createtheorder:
api.createOrder(newOrder)

AwordonPricing
Pricingis theprocess thatperforms calculations totheOrderdatatofindthecorrectpriceforthe
order. While possibly an Quantity Price per Item* scenario is sufficient, many companies have
a much more complicated process to calculate prices. For example, you can apply a Discount
forlargeOrders,orhavepreferentialratesforselectCustomersand/orItems.
jBilling solves this problem by providing a business rulebased mechanism for price formation.
While the inner workings of the Business Rules Engine lies outside the scope ofthis document
(please refer to the 3. Extension Guide for details on how to integrate Droolsbased rules into
jBilling), let's briefly describe how to interact with this component, and use it in your integration
calls.
Pricing is usually based on the characteristics of the item (For Example,'Apply a15%discount
on Item A if quantity of Item is above 15') ororder('Apply a10%discounttoany orders entered
by User B'). There are situations, however, when the Order or Item data is not sufficient to
describetheformationofprice.
For example, consider a situation in which we have created a 'click on a banner' Item (as
exemplified in the Trend example of the Getting Started guide) with ItemID = 2. We need to
apply different prices depending on the country of origin of the customers who clicks on the
banner. Without a rulebased pricing system, the only solution is to create as many items as
there are countries, and charge therightitemwhentheserverhas decodedthecountry oforigin
of the visitor, which is certainly not a good solution. Therefore, by using rulebased pricing, we
can create one single Item and tailor the price this Item will have according to external

Copyright2013EnterprisejBillingSoftwareLtd

33

conditions.
To address these situations, jBilling introduces theconceptof'pricingfields'.APricingFieldis
simply a value that is passed verbatim to the pricing engine, to be used if required during the
priceformationphase.
The pricing fields are useful in our example because the country of origin is known only by the
server that is creatingtheorderonjBilling,andonly aftertheeventhas takenplace.So,theonly
way we can specify variable data that alters the way rules behave at runtime is passing these
valuestotheruleengineforevaluation.
Now, lets code the rules that set different prices for our 'click on a banner' Item according to
the country of origin. To keep things simple, we're assuming herethattheserverthatoriginates
thecalltojBillingpassesthecountryasastringcontainingtheISOcodeofthecountryoforigin.
rule'pricingrulefortheUS'
when
exists(PricingField(name=="countryFrom",strValue=="US"))
$line:OrderLineDTO(itemId==2)#the'clickonabanner'
item
then
$line.setPrice(10.0F)#priceforUScustomersis10$.
end
rule'pricingruleforCanada'
when
exists(PricingField(name=="countryFrom",strValue=="CA"))
$line:OrderLineDTO(itemId=2)
then
$line.setPrice(9.0F)#priceforcanadiancustomersis9$.
end
The above rule can be read as: "apply a price of 10$ to order lines with Item 2 for users
connecting from the US, and 9$ for order lines with Item 2 for users connecting from Canada".
We can now code the API client that passes customer country in a new PricingField variable
withname"countryFrom":
JbillingAPIapi=JbillingAPIFactory.getAPI()
Stringcountry="US"//yourapplicationcodedeterminestheorigin
PricingFieldpf=newPricingField("countryFrom",country)
PricingField[]pfields=newPricingField[]{pf}
OrderWSorder=newOrderWS()
//Initializeorderparametershere
order.setPricingFields(PricingField.setPricingFieldsValue(pfields))

Copyright2013EnterprisejBillingSoftwareLtd

34

//now,let'sratetheorder
OrderWSresult=api.rateOrder(order)
This sample code creates a pricing field containing "countryFrom" = "US", so, if run, all order
linescontainingItem2areassignedapriceof10$intheoutputOrderWSstructure.

A PricingField can hold one of a String, Date, Integer orDoublevalue,anamethatidentifies the


PricingField (and can be used as demonstrated above). For more details, see the PricingField
structuredefinitionbelow.

If you examine the structureoftheOrderWSclass,

you'llseethatits pricingfields arecontained


in a String, for serializationpurposes.Tosimplify access tothis data,thePricingFieldclass

offers utility methods to decodetheserializedstringintoanarray ofPricingFieldvalues

and
encode an array of PricingFieldclasses

into a string. This of course can only be done if


you'reusingtheAPI,SOAPclientsshouldencodethestringbyhand.
Encoding is actually very simple, pricing fields are separated by commas, and each elementof
the pricing field is separated from the others by colons, in the following order:
"name:position:type:value" (name is a string value corresponding to the name of the pricing
field, positionis anintegerindicatingtheorderingofpricingrules,typeis oneof"string","integer",
"double" or "date", and value has the string formatted value for the field). Correct examples of
encoded
strings
are:
"countryFrom:1:string:US"
or
"newPrice:1:double:5.5,oldPrice:1:double:6.0" (the second example has two pricing fields
encoded,noticethecommaseparatingeachelement).
In this manner, it is possible to quickly add pricing rules that do not apply to specific Items or
Orders, but are rather applied based on external events (that translate to appropriate
PricingFieldvalues)

or otherconstraints notdirectly determinedfromtheOrderorItemdata


structures.

KeepingjBillinginsyncwithyourdata
While you can place many servicecalls tojBillingandexpectittoupdateits informationdirectly,
there are times in which asynchronous events take placeineitheryoursystemorinjBillingthat
change the data in one way or the other. For example, a scheduled payment could have been
rejected by the processor, or new invoices have been generated in a specific date, or users
couldchangetheirstatusduetopaymentevents(theybecomeoverdueorsuspended,etc.).
When it is your data that changes, it could be a simple matter of calling the appropriate update
methods in the Client API to sync jBilling to your changes. When it is jBilling that changes its
data,you'llneedtoresorttospecificAPIcallsorsetupcallbackfunctions.
The Client API provides several query functions that can be used to update your data. Most of
these functions have the get prefix. For example, if you keep a listofallusers andtheircurrent

Copyright2013EnterprisejBillingSoftwareLtd

35

status in your system, you could simply fire up an update job every night or so and call the
getUserWS() method for each user in the list to update their data. This, however, is both time
andresourceconsuming.Itwillworkforsmallvolumesofdata,butitwillnotscaleup.
Some API query methods return sets of results and not just the data that corresponds to one
element. The getUsersInStatus()function

returns alistoftheUserIDs ofallusers thatare


in a specific status, for example, getUserInStatus(newInteger(1))returns

all users
that are currently active. As another example, getOrderByPeriod() returns a list of all
orders that have the same periodicity (in our previous example, getOrderByPeriod(new
Integer(2))returnsallordersthatrecurmonthly).

SubscriptionStatus
The UserWS structure maintains a field named subscriberStatusId which contains the status
code for subscribers. This status field is kept updated internally by jBilling to reflect the overall
status of a user as a subscriber. Event such as a failed payment, or a successful payment,
produce changes to this status. It is easy to retrieve the current user's status by calling
getUserWS(). Another important query method is getUserTransitions(). This method
returns a list of all users that underwent a transition in their Subscription Status in a given time
period. You can call this method periodically (daily, for example), to keep your application
updated with who is subscribed and who is not to your services. Themethodreceives apairof
date values as arguments, indicating thestartingandendingdateoftheperiodwheretransitions
occurred. You can assign a null value to either or both of these parameters. The query
remembers the last time you called it, so if you specify a null starting date, it will extract all
transitionsmadefromthemomentyoulastcalledthisfunction.
If the ending date is null, there's no upper limit to the transition dates (i.e., the upper limit is the
current date). The query returns a set of UserTransitionResponseWS structures that contains
alltransitionsofsubscriptionstatusregisteredinthegivenperiodoftime.

SettingupCallBacks
As seen, the API provides a rich set of queries that allow your program todeterminethestatus
and information about most of the events your program needs to be informed about. You can
therefore use these calls to updateyourprogram's datafromjBilling,by creatingrecurringtasks
thatperiodicallyqueryyourjBillinginstallationandupdateyourdataaccordingly.
Some situations, however, warrant a finer degree of control. User status changes are themost
hard tomanagewithAPIcalls,sincethey occurinaratherasynchronous manner,andchecking
the status forallyourusers couldprovearesourcehog.Also,youwouldideally needtoknowof
thechangequickly,sothatyoucansuspendservicestoauserthathasnotpaidyourinvoices.
Note that, although related, the 'ageing status' is not the same as the 'subscription status'. The
first one is related to the ageing process, while the secondis not,itis only affectedby recurring

Copyright2013EnterprisejBillingSoftwareLtd

36

ordersandpayments.Callbacksareonlydoneforchangesinthe'ageingstatus'.
Ideally, you would need a way to receive anotificationwhenauserstatus changes,sothatyou
proceed to update only the user that has been affected by the change. This is wheretheHTTP
CallBack(HCB)interfacecomestotherescue.
The HBC feature of jBilling is capable of performing a web call to your application whenever a
user status changes. HBC will notify your application what user incurred in the change, the old
and new status, the user's login name, and whether the new status allows the user to login or
not.Thisinformationcancomehandytoupdateyourdataonthefly.
HBC performs a normal web request, passing the information about the status change to your
application via POST parameters. So, your application needs to publish a web page that takes
careofreceivingthenotification,gettheparametersfromtherequestformandactaccordingly.
The drawback of this method is that, if the page that listens to the call backs is notresponding,
thecallwillfailandyourapplicationwillbeoutofsync.
Setting up HBC requires you to enter jBilling's User Interface as an administrator, and set the
callback URL in theAgeingscreen.WhenavalidURLis placedinthis field,jBillingwillPOSTa
request to that URL whenever a user changes status. This callback canberedirectedtoatask
inyourprogramthatregistersthestatuschangeinyourdatastructures.
The POST callback performed by jBilling provides the called routine with the following
informationpertainingtheeventthathasoccurred:
cmd
A string that identifies jBilling's call. It is always set to 'ageing_update'by

jBilling,andallowsyoutouniquelyidentifya
jBillingcall(incasethecallback'surlisusedforotherpurposes)
user_id
The User ID of the user that is undergoing a status change in jBilling. You
canusethisIDtoidentifytheuserdirectly,
or otherwise query jBilling via the API to obtain the data for the user, should you need further
information
login_nameTheusernameoftheuserthatisundergoingastatuschange
from_status
The status the user is transitioning from. This is the status the user
hadbeforethetransitiontookplace
to_status
The status the user is transitioning to. This is the status the user has
oncethetransitiontookplace.Subsequentcalls
togetUser()intheAPIwillreturnthisstatuscode

Copyright2013EnterprisejBillingSoftwareLtd

37

can_login
Indicates whethertheuser's newstatus allows himtohaveaccess tothe
website'smember'sareaornot.

A value of 1 indicates the user can login to yoursystem,a0means hecannot.This information


can be safely ignored, if you check the user's status during the login phase, as explained in a
previouschapter
A quick example of a callback routine handler is givenbelow.This routinesimply prints astatus
change notice to the console, but ideally your application would use this data in a more useful
manner. This code constitutes the doPost()method

of a Java servlet class that services the


callbackinsideyourapplication:

public void doPost(HttpServletRequest request, HttpServletResponse


resp)
throwsServletException,IOException{

//ThedoPost()methodoftheservletclass.Thisservicesall
callbacks
//from*j*Billingintoyourapp.
StringuserName
IntegeruserId
IntegerfromStatus
IntegertoStatus
booleanupdate=false

//Testwhetherthisisa*j*Billingcallbycheckingthe"cmd"
parameter.
if(request.getParameter("cmd").equals("ageing_update")){
userName=request.getParameter("login_name")
try{
userId=newInteger(request.getParameter("user_id"))

fromStatus = new
Integer(request.getParameter("from_status")
toStatus=newInteger(request.getParameter("to_status")
}catch(NumberFormatExceptione){
//Ifthevaluespassedwerenotnumbersdonot
//performtheupdate.
update=false
}
if(update){
//Herewejustprintoutanotice.Yourappshould

//dosomethingmoresensible,suchasupdatingyour
data.

System.out.println("User"+userName+"haschanged

Copyright2013EnterprisejBillingSoftwareLtd

38

status!")
}
}
else{

//Thiswasnota*j*Billingcall.Youcanprocessit
normally
//orreturnanerror,asneeded.
}
}

Conclusion
4This document provided a hands on guide to using jBilling's integration services. While the
ClientAPIprovides muchmoreservicecalls andfeatures thanwhatwas coveredhere,wehope
this tutorial has provided some useful insight into how to put the integration API to good use in
your programs. The sections that follow cover all service calls and data structures providedby
the ClientAPIinmoredepth,andexplainwhatparameters they requireandwhatinformationyou
get in return, where applicable. Please refer to these sections for further details. The jBilling
integration layer provides a rich set of features that allow your application to seamlessly
integrate the billing process into your business logic. The Client API provides a flexible and
intuitive layer of abstraction that further simplifies the integration process and makes your
application independent of the specific technology that takes care of communicating with the
jBilling server. The Client API is easily available to any Java application. The SOAP layer
provides further support for nonJava applications that nevertheless need to integrate with
jBilling. Most modern web programming frameworks provide support for SOAP services,which
greatly expands thesetofprogramminglanguages andproductionenvironments thatjBillingcan
integratewith.

ClientAPIReference
DataStructuresObjectClasses

UserManagement
UserWS
Property

Type

Description

id

Integer

Uniqueidentifierforthisrecord.

ach

AchDTO

ACHPaymentdetailssavedforthe
User.Ifavailable,theACHinfocan
beusedduringAutomaticPayment

Copyright2013EnterprisejBillingSoftwareLtd

39

processing.
autoRecharge

api:java.lang.String

Amountbywhichthecustomer's
accountwillbeautorecharged
whendepleted(theamountcanbe
handledasa
api:java.math.BigDecimalJavatype
viathe
setAutoRechargeAsDecimal()
and
getAutoRechargeAsDecimal()
methods.Thesystemshouldbe
configuredtouseAutoRecharge
feature.

automaticPaymentType

api:java.lang.Integer

Integervaluetodeterminewhichof
thethreepaymentmethodsdoesthe
customerwanttoapplyforautomatic
paymentprocessing.Referto
AppendixAforacceptablevalues.

balanceType

api:java.lang.Integer

Thetypeofdynamicbalanceforthis
user.RefertoAppendixAfor
acceptablevalues.

blacklistMatches

String

Listsanyblacklistmatchesforthis
user.SeethejBillingUserGuidefor
moreinformationonblacklists.

childIds

Integer

Theidentifiersofanysubaccounts
forthisuser.

companyName

api:java.lang.String

User'scompanyname.

contact

ContactWS

Theprimarycontactinformationfor
thisuser.

createDatetime

api:java.util.Date

Creationdateofthisdatarecord.

creditCard

CreditCardDTO

Creditcardinformationforthisuser.
Notrequiredfortheusercreation
process.

creditLimit

Double

Thecreditlimit.Onlyvalidif
balanceTypeisofcreditlimittype.

currencyId

api:java.lang.Integer

Containsthecurrencycodeforthis
user.RefertoAppendixAfor
acceptablevalues.

customerId

api:java.lang.Integer

ReferencetotheCustomer
informationforthisuser.

deleted

api:java.lang.Integer

Iftherecordhasbeendeleted,this
fieldcontains'1',otherwiseit
contains'0'.Notethatdeletion
cannotbecarriedoutbysimply
settinga'1'inthisfield.

Copyright2013EnterprisejBillingSoftwareLtd

40

dueDateUnitId

api:java.lang.Integer

PeriodUnitofthisCustomer's
Invoiceduedate.RefertoAppendix
AforPeriodUnitacceptablevalues.

dueDateValue

api:java.lang.Integer

CustomerspecificInvoiceDuedate
value

dynamicBalance

api:java.lang.String

Stringrepresentationofthis
Customer'sdynamicbalance.The
dynamicbalance.IfbalanceTypeis
creditlimit,thisrepresentsthe
amountofcreditusedonthe
account.IfbalanceTypeisprepaid,
thisrepresentstheprepaidbalance
remaining.

excludeAgeing

Boolean

Booleanvaluetoindicateexcluding
thisUser/CustomerfromtheAgeing
process

failedAttempts

api:java.lang.Integer

Numberofloginattemptsthathave
beenfailedbythisuser(i.e.,theuser
hasenteredthewrongpassword).

invoiceChild

Boolean

trueifthisisasubaccount(childof
aparentaccount),butthisuserwill
stillreceiveinvoices.

invoiceDeliveryMethodId

api:java.lang.Integer

ReferenceIDforoneoftheInvoice
DeliveryMethods.Seeappendixfor
acceptablevalues.

isParent

Boolean

trueifthisrecordisa"parent"user.
Aparentusercanhave
subaccounts(children).

language

api:java.lang.String

Nameofthelanguage(i.e.
"English").

languageId

api:java.lang.Integer

Containsthepreferredlanguage
codeforthisuser.RefertoAppendix
Aforacceptablevalues.

lastLogin

api:java.util.Date

Dateofthelastloginperformedby
thisuser.

lastStatusChange

api:java.util.Date

Dateofthelaststatuschange
incurredbythisuser.

mainRoleId

api:java.lang.Integer

Thelevelofprivilegegrantedtothe
userwhenloggedintothesystem.
SeeAppendixAforacceptable
values.

nextInvoiceDate

api:java.util.Date

Theearliestnextbillabledateforthis
user'sOrders.

notes

api:java.lang.String

CRMnotesforthisuser.

Copyright2013EnterprisejBillingSoftwareLtd

41

owingBalance

api:java.math.BigDecimal

Arealtimecalculatedowing
balance.(AllInvoicesAll
Payments)

parentId

api:java.lang.Integer

Iftheuserbelongstoaparent
record,thisfieldcontainsthe
identifieroftheparentrecord.

partnerId

api:java.lang.Integer

Identifierofthepartnerthisuser
belongsto.

password

api:java.lang.String

Authenticatestheuser'sidentity
duringlogin.Thiscouldbe
meaninglessifthepasswordis
encrypted.

role

api:java.lang.String

ThenameoftheUser'srole(i.e.
"Clerk"or"Customer").

status

api:java.lang.String

NameoftheUser'scurrentstatus
(i.e."Suspended"or"Active").

statusId

api:java.lang.Integer

Currentstatusidentifieroftheuser.
SeeAppendixAforacceptable
values.

subscriberStatusId

api:java.lang.Integer

Subscriberstatusforthisuser.See
AppendixAforacceptablevalues.

userIdBlacklisted

Boolean

trueiftheuseridisblacklisted.See
thejBillingUserGuideformore
informationonblacklists.

userName

api:java.lang.String

Identifiestheuserduringlogin.

useParentPricing

Boolean

Selectingthisfieldwillindicatetothe
systemthatyouwantthechild
accounttotakeonthesamerates
thattheparentcarriesforparticular
products.

metaFields

MetaFieldValueWS

Userdefinefields.

mainSubscription

MainSubscriptionWS

TheMainSubscriptionfieldallowsa
billingadministratortoselectany
billingperiodrequiredforaspecific
customer.

Property

Type

Description

deleted

api:java.lang.Integer

Iftherecordhasbeendeleted,this
fieldcontains'1',otherwiseit
contains'0'.Notethatdeletion
cannotbecarriedoutbysimply
settinga'1'inthisfield.

expiry

api:java.util.Date

Expirationdateofthecreditcard.

CreditCardDTO

Copyright2013EnterprisejBillingSoftwareLtd

42

Usually,cardexpirationdatesare
expressedinmonth/yearform,such
as"05/11"or"May2011".Thisfield
containsthelastdaythecardis
valid,inthisexample,"05/31/2011".
id

api:java.lang.Integer

Uniqueidentifierforthisrecord.

name

api:java.lang.String

Creditcardowner'sname.Thisis
thenamethatappearsphysicallyon
thecreditcard.

number

api:java.lang.String

Creditcardnumber.Usually,a16
digitnumber.

securityCode

api:java.lang.Integer

CCV(CreditCardVerification)code
ofthecreditcard.

type

api:java.lang.Integer

CreditCardtype.SeeAppendixA
foracceptablevalues.

Property

Type

Description

address1

api:java.lang.String

Firstlinefortheaddress.

address2

api:java.lang.String

Secondlinefortheaddress.

city

api:java.lang.String

Cityofthiscontact.

contactTypeDescr

api:java.lang.String

Descriptionofthecontacttypeofthis
contactnamely'Primary'

contactTypeId

api:java.lang.Integer

Identifierforthetypeidofthe
Contacti.e.idofcontact_typetable.
Acontacthasatleastone'Primary'
contacttypeandmayhavemore
ContactTypes.

countryCode

api:java.lang.String

Countrycodeforthiscontact
(AppendixAcontainsalistof
acceptablecountrycodes).

createDate

api:java.util.Date

Datethiscontactrecordwasfirst
created.

deleted

api:java.lang.Integer

Iftherecordhasbeendeleted,this
fieldcontains'1',otherwiseit
contains'0'.Notethatdeletion
cannotbecarriedoutbysimply
settinga'1'inthisfield.

email

api:java.lang.String

Emailaddressofthiscontact.

faxAreaCode

api:java.lang.Integer

AreaCodeforthefaxnumber,ifany.

ContactWS

Copyright2013EnterprisejBillingSoftwareLtd

43

faxCountryCode

api:java.lang.Integer

CountryCodeforthefaxnumber,if
any.

faxNumber

api:java.lang.String

Faxnumber.

firstName

api:java.lang.String

Firstnameofthiscontact.

id

api:java.lang.Integer

Uniqueidentifierofthiscontact.

include

api:java.lang.Integer

1ifthiscontactismarkedas
includedinnotifications.

initial

api:java.lang.String

Middlenameinitials,ifany.

lastName

api:java.lang.String

LastnameofthisContact.

organizationName

api:java.lang.String

Nameoftheorganizationthecontact
belongsto.

phoneAreaCode

api:java.lang.Integer

PhonenumberAreaCode.

phoneCountryCode

api:java.lang.Integer

PhonenumberCountryCode.

phoneNumber

api:java.lang.String

Phonenumber.

postalCode

api:java.lang.String

ZIPCodeforthecontact'saddress.

stateProvince

api:java.lang.String

StateorProvinceofthecontact's
address.

title

api:java.lang.String

Titleforthecontact,suchas"Mr."or
"Dr.".

type

Integer

Userdefinecontacttypeex.primary
contact,secondarycontact.

UserTransitionResponseWS
Property

Type

Description

fromStatusId

api:java.lang.Integer

Statusofthesubscriptionbeforethe
transitiontookplace.SeeAppendix
Aforacceptablevalues.

id

api:java.lang.Integer

Uniqueidentifierforthetransition
record.

toStatusId

api:java.lang.Integer

Statusofthesubscriptionafterthe
transitiontookplace.

transitionDate

api:java.util.Date

Dateandtimethetransitiontook
place.

userId

api:java.lang.Integer

Identifiestheuseraccountthat
sufferedthesubscriptionstatus
change.

Copyright2013EnterprisejBillingSoftwareLtd

44

OrderManagementCalls
UsefulforenteringOrdersandqueryinginformationaboutOrders.

OrderWS
Property

Type

Description

activeSince

api:java.util.Date

Thepointintimewhenthisorderwill
startbeingactive,reflectingwhen
thecustomerwillbeinvoicedforthe
itemsincluded.Anullvalue
indicatesthattheorderwasactiveat
creationtime(seefieldcreateDate).

activeUntil

api:java.util.Date

Thepointintimewhenthisorder
stopsbeingactive.Afterthisdate,
theorderwillstopgeneratingnew
invoices,indicatingthattheservices
includedinthisordershouldstop
beingdeliveredtothecustomer.A
nullvaluewouldspecifyan
openendedorder.Suchordernever
expiresitisconsideredongoing
andwillrequireexplicitcancellation
forittostopgeneratinginvoices.

anticipatePeriods

api:java.lang.Integer

Howmanyperiodsinadvancethe
ordershouldinvoicefor.Leavewith
a'0'unlessyouhaveconfiguredthe
systemtoworkwithanticipated
periods.

billingTypeId

api:java.lang.Integer

Indicatesifthisorderistobepaidfor
beforeoraftertheserviceis
provided.Prepaidordersare
invoicedinadvancetothecustomer,
whilepostpaidareonlyinvoiced
oncethegoodsorservicesincluded
intheorderhavebeendelivered.'1'
meansprepaid,while'2'means
postpaid.

billingTypeStr

api:java.lang.String

(Readonly).Thewordthat
representsthebillingtype.Itis
ignoredwhenyousubmittheobject.

createDate

api:java.util.Date

(Readonly).Atimestampwiththe
dateandtimewhenthisorderwas
originallycreated.

Copyright2013EnterprisejBillingSoftwareLtd

45

createdBy

api:java.lang.Integer

Theidoftheuserthathascreated
thisorder.

currencyId

api:java.lang.Integer

Currencycode.RefertoAppendixA
foralistofacceptablevalues.

deleted

api:java.lang.Integer

Aflagthatindicatesifthisrecordis
logicallydeletedinthedatabase.
Thisallowsfor'undo'ofdeletions.
Validvaluesare0therecordis
notdeleted1therecordis
considereddeleted.

dfFm

api:java.lang.Integer

OnlyusedforspecificItalian
businessrules.

dueDateUnitId

api:java.lang.Integer

Ifthisorderhasaspecifiedduedate,
thiswillthetheunits(days,months,
years).SeeAppendixAforvalid
values.

dueDateValue

api:java.lang.Integer

Howmanyunitswillbeusedforthe
duedate.

generatedInvoices

InvoiceWS

AnarrayofInvoiceWSobjectsforall
theinvoicesgeneratedtillthetime
forthisOrder.

id

api:java.lang.Integer

Auniquenumberthatidentifiesthis
record.

lastNotified

api:java.util.Date

Whentheorderhasexpiration
notification,thisfieldtellswhenthe
lastonewassent.

nextBillableDay

api:java.util.Date

Thedatewhenthisordershould
generateanewinvoice.Meaning
thatuntilthatdate(andexcluding
thatdate),thecustomerhasbeen
invoicedfortheserviceincludedin
thisorder.

notes

api:java.lang.String

Afreetextfieldforanynotesforthis
Order.

notesInInvoice

api:java.lang.Integer

'1'ifthisorder'snoteswillbe
includedintheinvoice,or'0'ifnot.

notificationStep

api:java.lang.Integer

Whatstephasbeencompletedin
theordernotifications.

notify

api:java.lang.Integer

Aflagtoindicateifthisorderwill
generatenotificationasthe'active
since'dateapproaches.

orderLines

OrderLineWS

Theorderlinesbelongingtothis
order.Theseobjectswillspecifythe
itemsincludedinthisorderwiththeir
pricesandquantities.Seethe

Copyright2013EnterprisejBillingSoftwareLtd

46

OrderLineWSspecificationformore
information.
ownInvoice

api:java.lang.Integer

Aflagtoindicateifthisordershould
generateaninvoiceonitsown.The
defaultbehavioristhatmanyorders
cangenerateoneinvoice.

period

api:java.lang.Integer

Indicatestheperiodicityofthisorder.
Inotherwords,howoftenthisorder
willgenerateaninvoice.Examples
ofperiodsare:onetime,monthly,
weekly,etc.Periodcodescanbe
seeninjBilling'sUserInterface
under"Orders>Periods".

periodStr

api:java.lang.String

(readonly).Thedescriptionofthe
orderperiod.

pricingFields

api:java.lang.String

Anarrayofpricingfieldsencodedas
aString.Toencode,usethe
PricingField.setPricingFieldsValue()
staticmethod,whichtakesas
parameteranarrayofPricingField
structuresandreturnstheencoded
string.Todecode,usethe
PricingField.getPricingFieldsValue()
staticmethod,whichtakesas
parameteranencodedstringand
returnsanarrayofPricingField
structures.Pricingfieldsare
descriptorsthatprovidefurther
informationtothepricingengineand
aidinformingthepricefortheorder
itself.Seesection"Awordon
pricing"foramoredetailed
explanationoftheuseofpricing
fields.

statusId

api:java.lang.Integer

Anorderhastobeonstatus'Active'
inordertogenerateinvoices.An
orderusuallystartsinactivestatus,
andonlygoestosuspendedor
finishedwhenthecustomerfailsto
maketherequiredpayments.The
stepsandactionstakenduetolate
paymentsarepartoftheageing
process.SeeAppendixAforalistof
acceptableorderstatuscodes.

statusStr

api:java.lang.String

(Readonly)Thedescriptionofthe
currentorderstatus.

timeUnitStr

api:java.lang.String

(Readonly)Thedescriptionofthe
timeunitusedforbillableperiods.

Copyright2013EnterprisejBillingSoftwareLtd

47

total

api:java.lang.String

(Readonly)Astringrepresentation
oftheapi:java.math.BigDecimal
valueofsumtotalofalltheorder
linesofthisorder,inotherwords,
totalorderamount.

userId

api:java.lang.Integer

AnidentifierfortheUsertowhome
thiisorderbelongs.

metaFields

MetaFieldValueWS

Userdefinedfields.

versionNum

Integer

Keepstrackofnumberoftimesthis
objecthasbeenupdated.

Property

Type

Description

amount

String

Thetotalamountofthisline.Usually,
thisfieldshouldequaltotheproduct
ofpriceandquantity.Thisamount
willbetheoneaddedtocalculate
thepurchaseordertotal.The
currencyofthisfieldistheone
specifiedinitsparentorder.The
amountcanbealsosetand
obtainedasa
api:java.math.BigDecimal,usingthe
getAmountAsDecimal()and
setAmountAsDecimal()methods.

createDatetime

api:java.util.Date

Atimestampappliedwhenthis
recordiscreated.

deleted

api:java.lang.Integer

Aflagthatindicatesifthisrecordis
logicallydeletedinthedatabase.
Thisallowsfor'undo'ofdeletions.
Validvaluesare0therecordis
notdeleted1therecordis
considereddeleted.

description

api:java.lang.String

Adescriptivetextfortheservices
beingincluded.Thisusuallycopies
thedescriptionoftheitemrelatedto
thisline.

editable

api:java.lang.Boolean

Indicateswhetherthisorderlineis
editableornot(i.e.,itcannotbe
submittedforupdate).

id

api:java.lang.Integer

Auniquenumberthatidentifiesthis
record.

itemDto

ItemDTOEx

Containsinformationoftheitemthis
orderlinerefersto.

itemId

api:java.lang.Integer

Theidoftheitemassociatedwith
thisline,ornullifthislineisnot

OrderLineWS

Copyright2013EnterprisejBillingSoftwareLtd

48

directlyrelatedtoanitem.Itis
consideragoodpracticetohaveall
orderlinesrelatedtoanitem.This
allowsforbetterreporting.
orderId

api:java.lang.Integer

Identifieroftheorderthatcontains
thisorderline.

price

api:java.lang.String

Thepriceofoneitem,ornullifthere
isnorelateditem.Canalsobe
manipulatedasa
api:java.math.BigDecimalusingthe
"getPriceAsDecimal()"and
"setPriceAsDecimal()"methods.

priceStr

api:java.lang.String

Thepriceoftheitemasastring.

provisioningRequestId

api:java.lang.String

TheprovisioningrequestUUIDfor
thisorderline,ifitexists.

provisioningStatusId

api:java.lang.Integer

Theprovisioningstatusidforthis
orderline.SeeAppendixAforvalid
values.

quantity

api:java.lang.String

Thequantityoftheitemsincludedin
theline,ornull,ifaquantitydoesn't
apply.Itcanalsobehandledusing
the"getQuantityAsDecimal()"and
"setQuantityAsDecimal()"methods.

typeId

api:java.lang.Integer

Anorderlineusuallyhasitems.
However,somelinesareusedfor
additionalcharges,liketaxes.See
AppendixAforalistofacceptable
orderlinetypecodes.

useItem

api:java.lang.Boolean

Iftrue,whensubmitted,thislinewill
takethepriceanddescriptionfrom
theitem.Thismeansthatyouwould
notneedtogiveapriceand
descriptionfortheline.Instead,you
onlyprovidetheidoftheitem.See
thecreateOrdersectionfordetails.

orderLinePlanItems

OrderLinePlanItemWS

Canoverwritethequantity&priceof
theplanitemsatordercreation
level.

versionNum

Integer

Keepstrackofnumberoftimesthis
objecthasbeenupdated

Property

Type

Description

invoiceId

Integer

Identifieroftheinvoicethatwas
generated.

CreateResponseWS

Copyright2013EnterprisejBillingSoftwareLtd

49

orderId

api:java.lang.Integer

Identifieroftheorderthatwas
created.

paymentId

api:java.lang.Integer

Identifierofthepaymentthatwas
generatedtopaytheinvoice.

paymentResult

PaymentAuthorizationDTOEx

PaymentResultdatastructurewith
theoutcomedetailsofthepayment
operation.

userId

api:java.lang.Integer

Identifierofthenewusercreated
andforwhichtheorder,invoiceand
paymentwerecreated.

PricingField
This datastructuredescribes heterogeneous datathatwillbepassedtotherules engineinorder
tocalculatepricesand/orflagspecificconditionsthataffectpricing:
Property

Type

Description

name

api:java.lang.String

Identifierofthepricingfield.

position

api:java.lang.Integer

(optional)

value

api:java.lang.String

AmultipurposeStringvalueofthe
pricingfield,whichcanbeusedas
deemedfitwithintherules(for
example,usethestringvalueasa
descriptionfortheItem).

type

enum:Type

Enumerationfordatatype(String,
Integer,Decimal,Date,Boolean).

resultId

Long

IdentifieroftheMediationresultgets
stored.Onlyusedformediationof
batch.

ItemManagementCalls
Items are the building blocks of purchase orders.Items areusually managedfromtheGUIWeb
App since they don't have the level of activity of orders or payments. Use this service for
integration with other applications (for example, an inventory system) or when handling high
volumes to get better throughput as compared to the Web Application. An item can have a
simple price or apercentageprice.Items withasimplepricewillsimply addthatpricetothetotal
of a purchase order. A percentage price will impact that total by a percentage. Examples of
itemswithpercentagepricesaretaxesandinterests.

ItemDTOEx
Property

Type

Description

currencyId

api:java.lang.Integer

Identifierforthecurrencyinwhich

Copyright2013EnterprisejBillingSoftwareLtd

50

theitem'spriceisexpressed.See
AppendixAforalistofacceptable
values.
deleted

api:java.lang.Integer

Aflagthatindicatesifthisrecordis
logicallydeletedinthedatabase.
Thisallowsfor'undo'ofdeletions.
Validvaluesare:0therecordis
notdeleted1therecordis
considereddeleted.

entityId

api:java.lang.Integer

Identifierfortheentitytowhichthis
itembelongs.

hasDecimals

api:java.lang.Integer

Aninternalflagindicatingwhether
theitemacceptsdecimalquantities.
Canhavethefollowingvalues:0
Nodecimals,quantitiesare
expressedasaninteger,1
Decimalsallowedinquantityvalues.

id

api:java.lang.Integer

Auniquenumberthatidentifiesthis
Itemrecord.

orderLineTypeId

api:java.lang.Integer

Theorderlinetypethatthisitemwill
generate,sucha'taxes',or'items'.

types

Integer

Alistoftypeidentifiersthatindicates
towhichtypes(categories)thisitem
belongs.Anitemmustbelongtoat
leastonetype.

defaultPrice

PriceModelWS

AdefaultpricingmodelthisItem
follows.SeePriceModelWS

description

api:java.lang.String

Itemdescription

glCode

api:java.lang.String

GeneralLedgercodeforintegration
withOthersystemslikeAccounting
Systems.

number

api:java.lang.String

Thiscanbeusedtoidentifythisitem
followinganexternalcodingsystem.
Forexample,bookscanbe
identifiedbytheirISBNcodes.

percentage

api:java.math.BigDecimal

IfthisItemhaspercentagerate,that
rateisspecifiedusingthisfield

price

api:java.math.BigDecimal

Thepriceofthisitemornullifthisis
apercentageitem.

promoCode

api:java.lang.String

Ifthisitemisrelatedtoapromotion,
thisisthecodethatidentifiesthe
promotion.

metaFields

MetaFieldValueWS

Listofuserdefinedfields.

excludedTypes

Integer

Arrayofproductthatdoesnot

Copyright2013EnterprisejBillingSoftwareLtd

51

belongtoothercategories.
descriptions

InternationalDescriptionWS

Listofdescriptionsoftheproductin
theotherlanguages.

defaultPrices

Map<Date,PriceModelWS>

DefaultPriceoftheproductforthat
date&withspecifiedpricing
strategy.

Property

Type

Description

id

api:java.lang.Integer

Auniquenumberthatidentifiesthis
record

type

api:java.lang.String

Stringvaluerepresentingthe
PricingStrategytypename

attributes

SortedMap

AmapofPricemodelattributes.
Differentattributes(name,value
pairs)arerequiredbyindividual
PricingStrategytypesforuseinthe
calculationofprice

rate

api:java.lang.String

Adecimalvalueoftheavailablerate
instring.Thisisadefaultratethatis
usedforPricecalculate,unless
overriddenbyaPricingStrategyrate

currencyId

api:java.lang.Integer

Thecurrencyusedforthis
PriceModel

next

PriceModeWS

ThenextPriceModelfortheplanthat
referencesthisPriceModel

Property

Type

Description

description

String

Descriptionforthisitemtype.

id

api:java.lang.Integer

Identifierofthisitemtype.

orderLineTypeId

api:java.lang.Integer

Typeoforderlineforthisitem.See
"OrderLineTypeCodes"in
"AppendixA"forvalidvaluesforthis
field.

PriceModelWS

ItemTypeWS

ValidatePurchaseWS
Property

Type

Description

authorized

Boolean

trueifthevalidationhas

Copyright2013EnterprisejBillingSoftwareLtd

52

beenauthorized,false
otherwise.
message

String

Anarrayofmessages
detailingtheresultofthe
validationoperation.

quantity

api:java.lang.String

Quantityoftheitemthatcan
beappliedwithoutexceeding
theuser'sremainingcredit
limitorprepaidbalance.

success

api:java.lang.Boolean

trueifthevalidationwas
successful,falseotherwise.

InvoiceManagementCalls
The invoice management calls allow yourapplicationtoquery thesystemaboutinvoices,andto
attempt to pay an invoice through a payment gateway. Invoices in jBilling are,forthemostpart,
readonly and are created based on purchase orders. Invoices can be generated, however, for
ordersthathaveyettobeinvoiced.

InvoiceWS
Property

Type

Description

createDateTime

api:java.util.Date

Thisistheinvoicedate,whichis
assignedtoitbythebillingprocess
whenitisgenerated.

createTimeStamp

api:java.util.Date

Atimestampofwhenthisinvoice
recordwascreated.

dueDate

api:java.util.Date

Theduedateofthisinvoice.After
thisdate,theinvoiceshouldhave
beenpaid.

lastReminder

api:java.util.Date

Dateandtimeofwhenthelatest
reminderwasissuedforthisinvoice.

currencyId

api:java.lang.Integer

Identifierofthecurrencyinwhichthe
invoice'samountsarebeing
expressed.SeeAppendixAforalist
ofallacceptablevalues.

delegatedInvoiceId

api:java.lang.Integer

Ifthisinvoicehasbeenincludedin
anotherinvoice(usuallyforlackof
payment),thisfieldwillindicateto
whichinvoiceithasbeendelegated.

deleted

api:java.lang.Integer

Aflagthatindicatesifthisrecordis

Copyright2013EnterprisejBillingSoftwareLtd

53

logicallydeletedinthedatabase.
Thisallowsfor'undo'ofdeletions.
Validvaluesare:0therecordis
notdeleted1therecordis
considereddeleted.
id

api:java.lang.Integer

Auniquenumberthatidentifiesthis
record.

inProcessPayment

api:java.lang.Integer

Aflagindicatingifthisinvoicewillbe
paidusingautomatedpayment
(throughapaymentprocessor),orif
itwillbepaidexternally(for
example,withapapercheck).

isReview

api:java.lang.Integer

Thisisaninternalvaluethat
indicatesifthisinvoiceisnota'real'
invoice,butonethatbelongstoa
reviewprocess.If'1',itmeansthatit
isnotarealInvoice.

orders

Integer

Alistoftheidsofthepurchase
orderswhichhavebeenincludedin
thisinvoice.

overdueStep

api:java.lang.Integer

Thismarkswhichstepisthisinvoice
inforthepenalties(interests)
process.

paymentAttempts

api:java.lang.Integer

Howmanypaymentattemptshave
beendonebytheautomated
paymentprocesstogetthisinvoice
paid.

payments

Integer

Alistofidsofthepaymentsthat
havebeenappliedtothisinvoice.

statusId

api:java.lang.Integer

Aflagthatindicatesthestatusofthis
invoice.SeesectionInvoiceStatus
CodesonAnnexureAforvalid
valuesforthisfield.

toProcess

api:java.lang.Integer

Thisis'1'iftheinvoicewillbe
consideredbythebillingprocessas
unpaid.Otherwiseitis'0'andthe
invoicesiseitherpaidorcarried
overtoanotherinvoice.

userId

api:java.lang.Integer

Thecustomertowhomthisinvoice
belongs.

invoiceLines

InvoiceLineDTO

Alistofobjectsrepresentingeachof
thisinvoice'slines.

balance

api:java.lang.String

Theamountofthisinvoicethatisyet
tobepaid.Canalsobehandledas
aapi:java.math.BigDecimalviathe
"getBalanceAsDecimal()"and

Copyright2013EnterprisejBillingSoftwareLtd

54

"setBalanceAsDecimal()"methods.
carriedBalance

api:java.lang.String

Howmuchofthetotalbelongingto
previousunpaidinvoicesthathave
beendelegatedtothisone.Itcan
alsobehandledviathe
"getCarriedBalanceAsDecimal()"
and
"setCarriedBalanceAsDecimal()"
methods.

customerNotes

api:java.lang.String

Notesthatareenteredinapurchase
ordercanbeappliedtoaninvoice.If
thatisthecase,thisfieldwillhave
thoseusernotes.

number

api:java.lang.String

Theinvoicenumber,whichis
assignedtoitfroma'preference'
field(seetheuserguideformore
information).ThisisnottheID,which
isguaranteedtobeunique.

statusDescr

api:java.lang.String

ThestatusnameoftheInvoice
statusasdeterminedfromthefield
statusId

total

api:java.lang.String

Thetotalamountofthisinvoice.It
canalsobehandledasa
api:java.math.BigDecimalviathe
"getTotalAsDecimal()"and
"setTotalAsDecimal()"methods.

metaFields

MetaFieldValueWS

Alistofuserdefinedfields.

billingProcess

BillingProcessWS

Retrunsbillingprocesswsforwhich
invoiceshasgenerated.

InvoiceLineDTO
Thisdatastructurecontainsdatarelativetoasinglelineofaninvoice.
Property

Type

Description

amount

api:java.math.BigDecimal

Thetotalamountforthisline.
Usuallywouldfollowtheformula
price*quantity.

deleted

api:java.lang.Integer

Aflagthatindicatesifthisrecordis
logicallydeletedinthedatabase.
Thisallowsfor'undo'ofdeletions.
Validvaluesare:0therecordis
notdeleted1therecordis
considereddeleted.

description

api:java.lang.String

Thisdescriptionwillbedisplayedin
theinvoicedeliveredtothe

Copyright2013EnterprisejBillingSoftwareLtd

55

customer.
id

api:java.lang.Integer

Auniquenumberthatidentifiesthis
record.

isPercentage

api:java.lang.Integer

Indicateswhethertheitem
referencedbythisinvoicelineisa
percentageitemornot.Thisisused
toaidhowtheorderlineisdisplayed
tothecustomer.

itemId

api:java.lang.Integer

Identifieroftheitemreferencedby
thisinvoiceline.

price

api:java.math.BigDecimal

Thepricingofasingleunitofthis
item.

quantity

api:java.math.BigDecimal

Thenumberofunitsoftheitem
beinginvoiced.

sourceUserId

api:java.lang.Integer

Thisfieldisusefulonlywhenmany
subaccountsisinvoicedtogether.
ThisfieldwouldhavetheIDofthe
userthatoriginallypurchasean
item.

PaymentManagementCalls
Payments play a crucial role in determiningthestatus ofacustomer.Forthesystemtoproperly
trace payments, they have to be linked to the invoices they arepaying.Payments notrelatedto
an invoice should be avoided they are intended for initial imports from legacy billing systems
and exceptional circumstances. Arbitrary credit card payment processing not linked to any
invoice is possible, however. There are three basic payment methods: Cheques, ACH and
Credit Cards. Differentobjects areusedas fields ofPaymentWSforeachforthesetypes.There
are two different actions related to payments. One is to apply a payment. This means that the
payment has already been processed and accepted by thecompany.Applyingthepaymentwill
let the system know that a new payment has to be registered. A common example is whenthe
company has received and successfully deposited a cheque. In this case,thesystemonly has
to apply the payment to the customer's account. A more comprehensive action is to process a
payment. Processing a payment means the company will submitthepaymentinformationtothe
system, then the system will submit the payment to a payment process for its authorization in
realtime, storing the result of this operation. The caller will get the results of this authorization.
The most common example for this operation is acreditcardpayment.Insummary,thesystem
can both request authorization of a payment and apply the payment to the customer's account,
or it can do only this last step. The payment management calls willletyouquery thesystemfor
payments,andalsoapplyandsubmitapaymenttogetaninvoicepayed.

Copyright2013EnterprisejBillingSoftwareLtd

56

PaymentWS
Property

Type

Description

ach

AchDTO

Ifthisisapaymentdonewith
AutomaticClearingHouse(ACH),
thispropertycontainsthebanking
informationneeded.

amount

api:java.lang.String

Theamountofthepayment
operation.Canalsobehandledasa
api:java.math.BigDecimalviathe
"getAmountAsDecimal()"and
"setAmountAsDecimal()"methods.

authorization

PaymentAuthorizationDTO

Refundspecificfield.Containsthe
identifieroftheauthorizationdetails
fortherefund.

balance

api:java.lang.String

Balanceofthispayment.Ifgreater
than0,thispaymentcouldpaypart
ofanotherinvoice.If0,thispayment
hasalreadybeenappliedtoan
invoice,loweringtheinvoice's
balance.Itcanalsobehandledasa
api:java.math.BigDecimalviathe
"getBalanceAsDecimal()"and
"setBalanceAsDecimal()"methods.

cheque

PaymentInfoChequeDTO

Ifthispaymentisdoneviacheck,
thispropertycontainsinformation
aboutthecheque,otherwiseit
contains"null".

createDatetime

api:java.util.Date

Dateinwhichthispaymentrecord
wascreated.

creditCard

CreditCardDTO

Ifthisisacreditcardpayment,this
propertycontainsinformationabout
thecreditcard,otherwiseitcontains
"null".

currencyId

api:java.lang.Integer

Identifierofthecurrencyinwhichthe
paymentisbeingmade.See
AppendixAforalistofacceptable
values.

deleted

api:java.lang.Integer

Deleteflag.'1'ifthisrecordhasbeen
deleted,'0'otherwise.

attempt

api:java.lang.Integer

Numberoftheattempttoprocess
thispayment.

id

api:java.lang.Integer

Uniqueidentifierofthepayment
record.

invoiceIds

Integer

Containsthelistofinvoicesthis

Copyright2013EnterprisejBillingSoftwareLtd

57

paymentispaying.
isPreauth

api:java.lang.Integer

'1'ifthispaymentisa
preauthorization,'0'otherwise.

isRefund

api:java.lang.Integer

'1'ifthispaymentconstitutesa
refundoperation,'0'otherwise.

method

api:java.lang.String

Nameofthepaymentmethodused.

paymentDate

api:java.util.Date

Dateofthepayment.

paymentId

api:java.lang.Integer

Refundspecificfield.Whenarefund
istobeissued,thisfieldholdsthe
identifierofthepaymentthatistobe
refunded.

paymentMethodId

api:java.lang.Integer

Identifierofthepaymentmethod.
RefertoAppendixAforalistof
acceptablevalues.

paymentNotes

api:java.lang.String

Anynotesrelatedtothispaymentfor
e.g.relevantinvoiceIdcanbeadded
tonotesoranyrelevantinformation.

paymentPeriod

api:java.lang.Integer

OptionalPaymentperiodidentifier

resultId

api:java.lang.Integer

Identifieroftheresultofthepayment
attempt.RefertoAppendixAfora
listofacceptablevalues.

updateDatetime

api:java.util.Date

Dateinwhichthispaymentrecord
waslastupdated.

userId

api:java.lang.Integer

Identifieroftheuserthispayment
recordbelongsto.

metaFields

MetaFieldValueWS

Alistofuserdefinedfields.

PaymentInfoChequeDTO
Property

Type

Description

id

api:java.lang.Integer

Theuniqueidentifierofthisrecord.

bank

api:java.lang.String

Thenameofthebankthischeque's
accountbelongsto.

number

api:java.lang.String

Thecheque'snumber.

date

api:java.util.Date

Thecheque'sdate.

idHasBeenSet

Boolean

AValueObjecthasanidentityifthe
attributesmakingitsPrimaryKey
haveallbeenset.Anobjectwithout
identityisneverequaltoanyother
object.Returnstrueifthisinstance
hasanidentity.

bankHasBeenSet

Boolean

Trueifbankissetotherwisefalse.

Copyright2013EnterprisejBillingSoftwareLtd

58

numberHasBeenSet

Boolean

Trueifnumberissetotherwisefalse.

dateHasBeenSet

Boolean

Trueifdateissetotherwisefalse.

pk

Integer

Returnsprimarykey.

Property

Type

Description

abaRouting

api:java.lang.String

ABAroutingnumber.

accountName

api:java.lang.String

Theaccountname.

accountType

api:java.lang.Integer

Ifthisischequingsorasavings
account.

bankAccount

api:java.lang.String

Theaccountnumber.

bankName

api:java.lang.String

Thebankname.

id

api:java.lang.Integer

Theuniqueidentifierofthisrecord.

idHasBeenSet

Boolean

Trueifidissetotherwisefalse.

abaRoutingHasBeenSet

Boolean

TrueifABAroutingnumberisset
otherwisefalse.

bankAccountHasBeenSet

Boolean

Trueifbankaccountissetotherwise
false.

accountTypeHasBeenSet

Boolean

Trueifaccounttypeissetotherwise
false.

bankNameHasBeenSet

Boolean

Trueifbanknameissetotherwise
false.

accountNameHasBeenSet

Boolean

Trueifaccountnameisset
otherwisefalse.

gatewayKey

String

Thepaymentgatewaykey.

gatewayKeyHasBeenSet

Boolean

Trueifgatewaykeyissetotherwise
false.

pk

Integer

Idvalueissetinit.

AchDTO

PaymentAuthorizationDTO
Property

Type

Description

id

api:java.lang.Integer

Uniqueidentifierofthepayment
authorization.

processor

api:java.lang.String

Nameofthepaymentprocessor.

code1

api:java.lang.String

Requestcodenumber1.

code2

api:java.lang.String

Requestcodenumber2.

code3

api:java.lang.String

Requestcodenumber3.

Copyright2013EnterprisejBillingSoftwareLtd

59

approvalCode

api:java.lang.String

Approvalcodeprovidedbythe
processor.

AVS

api:java.lang.String

Acodewiththeresultsofaddress
verification.

transactionId

api:java.lang.String

Identifieroftheprocessor
transaction.

MD5

api:java.lang.String

Hashforthetransaction.

cardCode

String

Paymentcardcode.

createDate

Date

Thecreationdateforthispayment
authorizationrecord.

responseMessage

String

Theresponseprovidedbythe
processor.

idHasBeenSet

Boolean

Trueifidissetotherwisefalse.

paymentId

Integer

Identifierofthepayment.

processorHasBeenSet

Boolean

Trueifprocessorissetotherwise
false.

code1HasBeenSet

Boolean

Trueifcode1issetotherwisefalse.

code2HasBeenSet

Boolean

Trueifcode2issetotherwisefalse.

code3HasBeenSet

Boolean

Trueifcode3issetotherwisefalse.

approvalCodeHasBeenSet

Boolean

Trueifapprovalcodeisset
otherwisefalse.

AVSHasBeenSet

Boolean

TrueifAVSissetotherwisefalse.

transactionIdHasBeenSet

Boolean

TrueiftransactionIdissetotherwise
false.

MD5HasBeenSet

Boolean

TrueifMD5issetotherwisefalse.

cardCodeHasBeenSet

Boolean

Trueifcardcodeissetotherwise
false.

createDateHasBeenSet

Boolean

Trueifcarddateissetotherwise
false.

responseMessageHasBeenSet

Boolean

Trueifresponsemessageisset
otherwisefalse.

pk

Integer

PaymentAuthorizationDTOEx
This data structure contains data about a payment authorization process. It extends the
PaymentAuthorizationDTO structure (see above). Thus, it shares all the same fields plus the
following:
Property

Type

Description

Copyright2013EnterprisejBillingSoftwareLtd

60

result

api:java.lang.Boolean

trueiftheauthorizationsucceeded,
falseotherwise.

APIServiceCalls
The Service APIs/Calls are grouped according to functional area or data entities in jBilling, for
example: User Management APIs, Orders, Items, etc. All data contained in the Client API data
structures can be accessed by means of the getter and setter methods of each property (i.e.,
getFaxNumber()and

setFaxNumber()provide

access to the faxNumber property). When


describing data structures, this guide always provides the property name. This reference is
equally useful for those planning to use the web services directly, or for thosethatwillbeusing
the jBilling Client API. For nonJava languages, the data structures will look slightly different:
they are described in the WSDL descriptor and how that is translated to each language varies.
For those using the jBilling Client API from a Java application, the data structures can be used
directlyasclasses.
For a finer coverage of the SOAP support, refer to the WSDL file or use a SOAP introspection
tool (such as SoapUI). All theSOAPmethods,however,sharethesamename,parameters and
functionalityastheirAPIcounterparts.
AllservicecallsprovidedbytheAPIarecoveredintheWebServicesAPIReferencedocs.
Pleaserefertotheclient/WebServicesAPIfromhere:APIReference.

WebServices APIReference
InvoiceAPIMethods
APIMethod

Arguments

Returns

Description

getInvoiceWS(Integer
invoiceId)

InvoiceID

InvoiceWS

Returns the invoice for the given ID. Will


returnnullifinvoiceisareviewinvoice.

createInvoice(Integer userId, User ID, Orders to Integer


booleanonlyRecurring)
include

Creates an invoice for the given user,


includingallordersoronlyrecurringorders.
Returns the an array of generated invoice
IDs.

Copyright2013EnterprisejBillingSoftwareLtd

61

createInvoiceFromOrder(Inte Order ID, Invoice Integer


gerorderId,IntegerinvoiceId) ID

Creates an invoice for thegivenorder.Ifan


invoice ID is given, the order will beadded
to the selected invoice Otherwise a new
invoicewillbecreated.

deleteInvoice(Integer
invoiceId)

Deletesthegiveninvoice.

getAllInvoicesForUser(Intege UserID
ruserId)

InvoiceWS

Returns an array of invoices for the given


user.

getAllInvoices(IntegeruserId) UserID

Integer

ReturnsanarrayofinvoiceIDsforthegiven
user.

getLatestInvoice(Integer
userId)

UserID

InvoiceWS

Returns the most recent invoice for the


givenuser.

getLastInvoices(Integer
userId,Integernumber)

UserID,numberof Integer
invoices

Returns the last N invoice IDs for thegiven


user.

getInvoicesByDate(String
since,Stringuntil)

Date range in the Integer


format
"yyyymmdd"

Returns an array of invoice IDs created


betweenthegivendates.

getUserInvoicesByDate(Integ User ID, Date Integer


er userId, String since, String rangeintheformat
until)
"yyyymmdd"

Returns an array of invoice IDs created


betweenthegivendatesforthegivenuser.

getUserInvoicesPage(Integer UserID,
userId, Integer limit, Integer Offset
offset)

Returns an array ofinvoicews betweenthe


givenrangeforthegivenuser.

getUnpaidInvoices(Integer
userId)

InvoiceID

UserID

Limit, InvoiceWS

Integer

Returns an array of unpaid invoice IDs for


thegivenuser.

notifyInvoiceByEmail(Integer InvoiceID
invoiceId)

Boolean
success

Sends a notification to the user regarding


thegiveninvoiceID.

getPaperInvoicePDF(Integer InvoiceID
invoiceId)

Byte

Returns the generated PDF invoice as a


Base64encodedstring.

Copyright2013EnterprisejBillingSoftwareLtd

62

notifyPaymentByEmail(Intege PaymentID
rpaymentId)

createInvoiceWithDate(Integ
er userId, Date billingDate,
Integer
dueDatePeriodId,
Integer dueDatePeriodValue,
booleanonlyRecurring)

Boolean

User ID, Billing Integer


Date, Due Date
Period ID, Due
Date
Period
Value, Boolean
OnlyRecurring

applyOrderToInvoice(Integer Order
orderId,
InvoiceWS InvoiceWS
invoiceWs)

ID, Integer

SendsanemailwiththePayment
informationtothecustomer.

Generatesaninvoiceforacustomerusing
anexplicitbillingdate&duedateperiod.If
thebillingdateisleftblank,theinvoicewill
begeneratedfortoday.
Iftheduedateperiodunitorvalueisleft
blank,thentheduedatewillbecalculated
fromthe
orderperiod,orfromthecustomerduedate
periodifset.
Returnsanarrayofgeneratedinvoiceids.

GenerateaninvoiceusinggivenorderID.
Createsaninvoicetemplatethatcontains
themetafieldvaluesusingInvoiceWS&
returnsinvoiceId.

OrderAPIMethods
APIMethod

Arguments

Returns

Description

getOrder(IntegerorderId)

OrderID

OrderWS

ReturnstheorderforthegivenID.

createOrder(OrderWSorder)

OrderWS

Integer

Savesthegivenorderandreturnsthenew
ID.

updateOrder(OrderWSorder) OrderWS

Updatesthestoredorderdetailstomatch
thegivenorder.Givenordermusthavean
ID.

createUpdateOrder(OrderWS OrderWS
order)

Integer

Savestheorderifitdoesnotalreadyexist,
orupdatesthestoreddetailsifitdoes.

deleteOrder(Integerid)

OrderID

Deletesthegivenorder.

createOrderAndInvoice(Order
WSorder)

OrderWS

Integer

Savesthegivenorderandimmediately
generatesaninvoicefortheneworder.
ReturnstheIDofthenewinvoice.

getCurrentOrder(Integer
userId,Datedate)

UserID,Date

OrderWS

Returnsthecurrentorder(ordercollecting
currentonetimecharges)fortheperiodof
givendate.

OrderWS

Returnsanarrayofrecurringorderlines
forthegivenuser.

getUserSubscriptions(Integer UserID
userId)

Copyright2013EnterprisejBillingSoftwareLtd

63

getOrderLine(Integer
orderLineId)

OrderLineID

updateOrderLine(OrderLineW OrderLineWS
Sline)
getOrderByPeriod(Integer
userId,IntegerperiodId)

OrderLineWS

ReturnstheorderlineforthegivenID.

Updatesthestoredorderlinedetailsto
matchthegivenorderline.Givenorder
linemusthaveanID.

UserID,PeriodID Integer

ReturnsanarrayoforderIDsforthegiven
userandperiodid(Onetimeperiod,
Monthlyperiodetc.).

getLatestOrder(IntegeruserId) UserID

OrderWS

Returnsthemostrecentorderforthegiven
user.

getLastOrders(IntegeruserId, UserID,Integer
Integernumber)
number

Integer

ReturnsthelastNorderIDsforthegiven
user.

rateOrder(OrderWSorder)

OrderWS

OrderWS

Processesthegivenorder,calculating
pricesandrunningallitemmanagement
plugins.Returnstheorderasitwould
havebeencreated.

rateOrders(OrderWSorders)

OrderWS

OrderWS

Ratesalistofordersandreturnstheresult.

updateOrderPeriods(OrderPer OrderPeriods
iodWSorderPeriods)

boolean
success

Updatesallorderperiodstomatchthe
givenlistofperiods.

deleteOrderPeriod(Integer
periodId)

OrderPeriodID

boolean
success

Deletesthegivenorderperiod.

createOrderPreAuthorize(Ord
erWSorder)

OrderWS

PaymentAuthori Createsthegivenorder,andattemptsto
zationDTOEx
preauthorizeapaymentforthetotalorder
amount.

updateCurrentOrder(Integer
userId,OrderLineWS[]lines,
PricingField[]fields,Datedate,
StringeventDescription)

UserId,
OrderWS
OrderLineWS,

PricingField,Date,
EventDescription

Updatestheuesr'scurrentonetimeorder
forthegivendate.Returnstheupdated
currentorder.Throwsanexceptionfor
userswithnomainsubscriptionorder.

updateOrCreateOrderPeriod(
OrderPeriodWSorderPeriod)

OrderPeriodWS

Boolean

Updateorderperiodifalreadyexists
orthewisecreateneworderperiod&save
it.

getOrderPeriods()

OrderPeriodWS ReturnsanarrayoforderPeriodWS.

Copyright2013EnterprisejBillingSoftwareLtd

64

ItemAPIMethods
APIMethod

Arguments

Returns

Description

getItem(Integer itemId, Integer Item ID, User ID, ItemDTOEx


userId,Stringpricing)
Pricingstring

ReturnstheitemforthegivenID.

getAllItems()

ItemDTOEx

Returnsanarrayofallitemsinthesystem.

createItem(ItemDTOExitem)

ItemDTOEx

Integer

Save the given item and returns the new


ID.

updateItem(ItemDTOExitem)

ItemDTOEx

Updates the stored item details to match


the given item. Given item must have an
ID.

deleteItem(IntegeritemId)

ItemID

Deletesthegivenitem.

getItemByCategory(Integer
itemTypeId)

ItemTypeID

ItemDTOEx

Returns an array of itemsbelongingtothe


givenitemtype.

getUserItemsByCategory(Inte User ID, Item Type Integer


geruserId,IntegercategoryId) ID

Returns all items for the given category


that can be found on an active order for
thegivenuser.

getAllItemCategories()

ItemTypeWS

Returns an array of all item types in the


system.

createItemCategory(ItemType
WSitemType)

ItemTypeWS

Integer

Saves the given item type and returns the


newlycreatedobject.

updateItemCategory(ItemType ItemTypeWS
WSitemType)

Updates the stored item type and returns


the updated object. Given item type must
haveanID.

deleteItemCategory(Integer
itemCategoryId)

Deletesthegivenitemtype.

ItemTypeID

Copyright2013EnterprisejBillingSoftwareLtd

65

isUserSubscribedTo(Integer
userId,IntegeritemId)

UserID,ItemID

String

Returns the total quantity of an itemfound


onausersactiverecurringorders.

getLatestInvoiceByItemType(I User ID, Item Type InvoiceWS


nteger
userId,
Integer ID
itemTypeId)

Returns the latest invoice for a user


containinganitemofthegiventype.

getLastInvoicesByItemType(In User ID, Item Type Integer


teger
userId,
Integer ID,Integernumber
itemTypeId,Integernumber)

Returns the last N invoice IDs containing


anitemofthegiventypeforauser.

getLatestOrderByItemType(Int User Id, Item Type OrderWS


eger
userId,
Integer ID
itemTypeId)

Returns the latest order for a user


containinganitemofthegiventype.

getLastOrdersByItemType(Inte User ID, Item Type Integer


geruserId,IntegeritemTypeId, ID,Integernumber
Integernumber)

Returns the last N orderIDscontainingan


itemofthegiventypeforauser.

getUserOrdersPage(Integer
User,Limit,Offset OrderWS
user, Integer limit, Integer
offset)

Returns an array of orderws between the


givenrangeforthegivenuser.

validatePurchase(Integer
User ID, Item ID, ValidatePurcha
userId, Integer itemId, String Pricingstring
seWS
fields)

Runs pricing and item management


plugins in a mock purchase for the given
useranditemID.

validateMultiPurchase(Integer User ID, Array of ValidatePurcha


userId, Integer itemId, String ItemID
seWS
fields)

Runsmultiplemockpurchases.

PaymentAPIMethods
APIMethod

Arguments

Returns

Description

getPayment(Integer
paymentId)

PaymentID

PaymentWS

ReturnsthepaymentforthegivenID.

Copyright2013EnterprisejBillingSoftwareLtd

66

getLatestPayment(Integer
userId)

UserID

PaymentWS

getLastPayments(Integer
userId,Integernumber)

User ID, number of Integer


payments

Returns the most recent payment for the


givenuser.

Returns the last N payment IDs for the


givenuser.

getTotalRevenueByUser(Integ UserID
eruserId)

BigDecimal

Returns the total revenue (payments


recieved)forthegivenuser.

getUserPaymentInstrument(Int UserID
egeruserId)

PaymentWS

Returns the selected "automatic payment"


detailsforthegivenuser.

Limit, PaymentWS

Returns an array of paymentWS between


thegivenrangeforthegivenuserid.

getUserPaymentsPage(Intege User ID,


r userId, Integer limit, Integer Offset
offset)

createPayment(PaymentWS
payment)

PaymentWS

Integer

Saves the given payment and appliesitto


the user's account (as per configured
entity preferences). Does not process the
payment,onlycreatesitas'Entered'.

updatePayment(PaymentWS
payment)

PaymentWS

Updates the stored payment to match the


details in the given payment. Given
paymentmusthaveanID.

deletePayment(Integer
paymentId)

PaymentID

Deletesthegivenpayment.

removePaymentLink(Integer
invoiceId,IntegerpaymentId)

Invoice
PaymentID

ID,

Remove the link between a payment and


invoice(unpaytheinvoice).

removeAllPaymentLinks(Integ PaymentID
erpaymentId)

Removes allthelinksbetweenapayment
andinvoice.

ID,

Link the payment to an invoice (pay the


invoice).

createPaymentLink(Integer
invoiceId,IntegerpaymentId)

Invoice
PaymentID

payInvoice(IntegerinvoiceId)

InvoiceID

PaymentAuthori Pays thegiveninvoiceusingthefirstcredit


zationDTOEx
cardavailablefortheinvoiceduser.

Copyright2013EnterprisejBillingSoftwareLtd

67

applyPayment(PaymentWS
payment,IntegerinvoiceId)

PaymentWS,
InvoiceID

processPayment(PaymentWS PaymentWS,
payment,IntegerinvoiceId)
InvoiceID

Integer

Saves the given payment and appliesitto


the given invoice. Does not process the
payment,onlycreatesitas'Entered'.

PaymentAuthori Saves and processes the payment,


zationDTOEx
applying it to the given invoice. If no
payment is given, the payment will be
created using the users "automatic
payment" instrument.Ifnoinvoiceisgiven,
the payment will be applied to the user's
account according to the configured entity
preferences.

validateCreditCard(com.sapie CreditCardDTO,
CardValidation
nter.jbilling.server.entity.Credit ContactWS, Level WS
CardDTO
creditCard, innumber(1/2/3)
ContactWScontact,intlevel)

Level 1 Simple checks on Credit Card


Number,name,andmod10.
Level 2 Address and Security Code
validation.
Level3Checknumberagainsta
paymentgatewayusingpreauth
transaction.

ReturnsobjectofCardValidationWS.

UserAPIMethods
APIMethod

Arguments

Returns

Description

getUserWS(IntegeruserId)

UserID

UserWS

ReturnstheuserforthegivenID.

createUser(UserWSnewUser) UserWS

Integer

Creates a new user from given UserWS


object & returns User ID of the created
user.

updateUser(UserWSuser)

UserWS

Updates the stored user details to match


the given user object. Given user must
haveanID.

deleteUser(IntegeruserId)

UserID

Deletesthegivenuser.

Copyright2013EnterprisejBillingSoftwareLtd

68

getUserContactsWS(Integer
userId)

UserID

ContactWS

Returns all contact details for the given


user.

updateUserContact(Integer
User ID, Contact
userId,
Integer
typeId, Type
ID,
ContactWScontact)
ContactWS

Updates the contact details of the given


user.

getContactTypeWS(Integer
contactTypeId)

ContactTypeW
S

ReturnsthecontacttypeforthegivenID.

Integer

Saves the given contact type and returns


thenewID.

ContactTypeID

createContactTypeWS(Contac ContactTypeWS
tTypeWScontactType)

updateCreditCard(Integer
User ID, Credit
userId,
CreditCardDTO Card
creditCard)

Updatesthegivenuserscreditcarddata.

updateAch(Integer
AchDTOach)

Updates the given users ACH (automatic


clearinghouse)data.

setAuthPaymentType(Integer User ID, Payment


userId,
Integer Type,usetype?
autoPaymentType, boolean
use)

Marks the users Credit Card or ACH


details as being usable for automatic
payments.

getAuthPaymentType(Integer UserID
userId)

Integer

Returns the users preferred automatic


paymenttype.

getUsersByStatus(Integer
statusId,booleanin)

Status ID, in/ not in Integer


status

If "in" true,returnsalistofuserswhoarein
the givens status, if false, a list of users
whoareNOTinthegivenstatus.

getUsersInStatus(Integer
statusId)

StatusID

Integer

Array of user IDs who are in the given


status.

getUsersNotInStatus(Integer
statusId)

StatusID

Integer

Array of user IDs who are not in thegiven


status.

getUsersByCustomField(Integ Type ID, Value to Integer


ertypeId,Stringvalue)
match

Array of user IDs who have a custom


contactfieldwiththegivenvalue.

userId, UserID,ACH

Copyright2013EnterprisejBillingSoftwareLtd

69

getUsersByCreditCard(String Credit
number)
number

Card Integer

Array of user IDs who have the given


creditcardID.

Integer

Returns the user id for the given user


name.

saveCustomContactFields(Co ContactFieldType
ntactFieldTypeWSfields)
WS

Updates the available custom contact


fieldsforthesystem.

processPartnerPayouts(Date
runDate)

RunDate

Runs the parter payout process for the


givendate.

getPartner(IntegerpartnerId)

PatnerID

PartnerWS

ReturnsthepartnerforthegivenID.

getUserTransitions(Date from, Daterange


Dateto)

UserTransition
ResponseWS

Returns an arrayofusertransitions(status
changes)forthegivenddaterange.

getUserTransitionsAfterId(Inte
gerid)

UserTransition
ResponseWS

Returns an arrayofusertransitions(status
changes)forthegivenuserID.

getUserId(Stringusername)

create(UserWS
OrderWSorder)

Username

UserID

user, UserWS,OrderWS CreateRespons Saves a new user and order and


eWS
immediately generates a new invoice for
the created user and order. Returns the
ID'softhecreatedobjects.

saveCustomerNotes(Integer
userId,Stringnotes)

UserID,Notes

Updatesthegivenusersnotes.

userExistsWithName(String
userName)

UserName

Boolean

Returns true if a user exists withthegiven


username,falseifnot.

userExistsWithId(Integer
userId)

UserID

Boolean

Returns true if a user with the given ID


exists,falseifnot.

getUserIdByEmail(String
email)

EmailID

Integer

Retrieves user by the user's email. This is


only valid if Jbilling is configured to force
unique emails per user/customers in the
company. If unique emails are not forced
then an exception is thrown and in such
case this method should not be used.

Copyright2013EnterprisejBillingSoftwareLtd

70

Returns user ID of the user with given


email.

triggerPartnerPayoutProcess(
DaterunDate)

RunDate

Processes partner payouts for all partners


that have a payout due before the given
rundate.

processPartnerPayout(Integer PartnerID
partnerId)

Process partner payout for a single given


partnerID.

createPartner(UserWS
UserWS,
newUser,PartnerWSpartner) PartnerWS

Integer

Creates new Partner using PartnerWS,


sets meta fields values from UserWS &
returnsUserId.

updatePartner(UserWS
UserWS,
newUser,PartnerWSpartner) PartnerWS

Update user & set meta fields using


UserWS.UpdatepartnerusingPartnerWS.

deletePartner(Integer
partnerId)

PartnerID

Deletes the composed Partnerobjectfrom


the system by first deleting the associated
userandthendeletingthePartnerrecord.

deleteCreditCard(Integer
userId)

UserID

Deletes a users stored credit card using


User ID. Payments that were made using
thedeletedcreditcardwillnotbeaffected.

deleteAch(IntegeruserId)

UserID

Deletes a users stored ACH details using


User ID. Payments that were made using
the deleted ACH details will not be
affected.

Integer

Returns Auto Payment Type using User


ID.

getAutoPaymentType(Integer UserID
userId)

setAutoPaymentType(Integer User ID, Auto


userId,
Integer Payment
Type,
autoPaymentType, boolean Use
use)

Set Auto Payment Type using User ID,


AutoPaymentType,Use.

Copyright2013EnterprisejBillingSoftwareLtd

71

PlansandSpecialPricingAPIMethods
APIMethod

Arguments

Returns

Description

getPlanWS(IntegerplanId)

PlanID

PlanWS

ReturnstheplanforthegivenID.

createPlan(PlanWSplan)

PlanWS

Integer

SavethegivenplanandreturnthenewID.

updatePlan(PlanWSplan)

PlanWS

Update the stored plan details to match


the given plan object. Given plan must
haveanID.

deletePlan(IntegerplanId)

PlanID

Deletesthegivenplan.

addPlanPrice(Integer planId, Plan


PlanItemWSprice)
PlanItemWS

ID,

Addsanewpricetothegivenplan.

isCustomerSubscribed(Intege
rplanId,IntegeruserId)

PlanID,UserID

boolean

Returnstrueifthegivenuserissubscribed
totheplan,falseifnot.

getSubscribedCustomers(Inte
gerplanId)

PlanID

Integer

Returns an array of user IDs of userswho


havesubscribedtothegivenplan.

getPlansBySubscriptionItem(I
ntegeritemId)

ItemID

Integer

Returns a list of plan IDs that modify


customer pricing when the given item is
addedtoanorder.

getPlansByAffectedItem(Integ
eritemId)

ItemID

Integer

Returns a list of plan IDs that affect the


priceofthegivenitem.

createCustomerPrice(Integer User
userId,PlanItemWSplanItem) PlanItemWS

ID, PlanItemWS

Creates a new customerspecific price for


the given user. This new price will only
affectthegivenuser.

updateCustomerPrice(Integer User
userId,PlanItemWSplanItem) PlanItemWS

ID,

Updates a stored customerspecific price


with the details of the given price. Price
objectmusthaveanID.

Copyright2013EnterprisejBillingSoftwareLtd

72

deleteCustomerPrice(Integer
userId,IntegerplanItemId)

User ID, Plan Item


ID

Deletesacustomerspecificprice.

getCustomerPrices(Integer
userId)

UserID

PlanItemWS

Returns a list of applied pricing (both


customerspecific and plan prices) for the
givenuser.

getCustomerPrice(Integer
userId,IntegeritemId)

UserID,ItemID

PlanItemWS

Returns a list of applied pricing (both


customerspecific and plan prices) for the
givenuseranditem.

getCustomerPriceByAttributes User ID, Item ID, PlanItemWS


(Integer userId, Integer itemId, Mapofattributes
Map<String,String>attrs)

Returns a list of applied pricing (both


customerspecific and plan prices) that
matchesthegivenattributes.

getCustomerPriceByWildcard User ID, Item ID, PlanItemWS@ Returns a list of applied pricing (both
Attributes(Integer
userId, Mapofattributes
customerspecific and plan prices) that
Integer itemId, Map<String,
matches the given attributes. Handles
String>attrs)
wildcards forattributevalues,where'*'can
mean"anyvalue".

getCallerId()

Integer

Returns the user ID of the authenticated


useraccount.

getCallerCompanyId()

Integer

Returns the company ID


authenticateduseraccount.

of

the

getCallerLanguageId()

Integer

Returns the language ID


authenticateduseraccount.

of

the

getCallerCurrencyId()

Integer

Returns the currency ID


authenticateduseraccount.

of

the

PlanWS

Returns list of plans as WS objects, or


anemptylistifsourcelistisempty.

getAllPlans()

Copyright2013EnterprisejBillingSoftwareLtd

73

BillingProcessAPIMethods
APIMethod

Arguments

Returns

Description

isBillingRunning()

boolean

Returns true if the billing process is


currentlyrunning.

triggerBillingAsync(Date
runDate)

Rundate

Triggers the billing process for the given


dateinanewthread(nonblocking).

triggerBilling(DaterunDate)

Rundate

boolean

Triggers the billing process for the given


date in the current thread (blocking).
Returns true if the billing process was
triggeredsuccessfully,falseifnot.

triggerAgeing(DaterunDate)

Rundate

Triggerstheuserageingprocess.

getBillingProcessConfiguratio
n()

BillingProcessC Returnsthebillingprocessconfiguration.
onfigurationWS

createUpdateBillingProcessC BillingProcessConf Integer


onfiguration(BillingProcessCo igurationWS
nfigurationWSws)

Updatesthecurrentbillingconfiguration.

getBillingProcess(Integer
processId)

ProcessID

BillingProcess
WS

Returns the outcome of the given billing


process.

getLastBillingProcess()

Integer

Returns the billing process ID of the last


runbillingprocess.

getOrderProcesses(Integer
orderId)

OrderID

List<OrderProc
essWS>

Returns a list of processes that have


addedthegivenorderintoaninvoice.

getOrderProcessesByInvoice(I InvoiceID
ntegerinvoiceId)

List<OrderProc
essWS>

Returns a list of processes that have


createdorupdatedthegiveninvoice.

getReviewBillingProcess()

BillingProcess
WS

Returns the outcome of the latest review


billingprocess.

Copyright2013EnterprisejBillingSoftwareLtd

74

setReviewApproval(Boolean
flag)

boolean is review BillingProcessC Approves or disapproves the latestreview


approved
onfigurationWS process. Returns the billing configuration
thatgeneratedthereview.

getBillingProcessGeneratedIn ProcessID
voices(IntegerprocessId)

List<Integer>

Returns a list of invoice IDs generated by


thegivenbillingprocess.

getAgeingConfiguration(Integ
erlanguageId)

AgeingWS

Returns a list of ageing steps and ageing


messagesforthegivenlanguage.

LanguageID

saveAgeingConfiguration(Age AgeingWS , Grace


ingWS
steps,
Integer Period, Language
gracePeriod,
Integer ID
languageId)

Updates the current ageing configuration


with the given ageing steps and grace
period. Ageing notification messages will
besavedforthegivenlanguageID.

isAgeingProcessRunning()

Boolean

Returns true if the ageing process is


currently running for the caller's entity,
falseifnot.

ProcessStatus
WS

Returns the status of the last run (or


currently running) ageing process. That
the ageing process currently does not
report a start date,enddate,orprocessid.
The status returned by this method will
only
report
the
RUNNING/FINISHED/FAILED state of the
process.

isBillingRunning(Integer
entityId)

EntityID

Boolean

Returns true if the Billing Process is


runningforthegivenentityId.

getBillingProcessStatus()

ProcessStatus
WS

Returns the status of the last run (or


currentlyrunning)billingprocess.

getAgeingProcessStatus()

MediationProcessAPIMethods
APIMethod

Arguments

Returns

Description

Copyright2013EnterprisejBillingSoftwareLtd

75

triggerMediation()

Triggersthemediationprocess.

isMediationProcessing()

boolean

Returns true if the mediation process is


currentlyrunning.

getAllMediationProcesses()

List<Mediation
ProcessWS>

Returns a list of all mediation process


outcomes.

getMediationEventsForOrder(I OrderID
ntegerorderId)

List<Mediation
RecordLineWS
>

Returns alistofmediationevents(external
datareadin)forthegivenorder.

getMediationEventsForInvoice InvoiceID
(IntegerinvoiceId)

List<Mediation
RecordLineWS
>

Returns alistofmediationevents(external
datareadin)forthegiveninvoice.

getMediationRecordsByMedia Mediation Process List<Mediation


tionProcess(Integer
ID
RecordWS>
mediationProcessId)

Returns a list of mediation records for the


givenprocess.

getNumberOfMediationRecor
dsByStatuses()

Returns a breakdown of the mediation


processbyrecordstatus.

List<RecordCo
untWS>

getAllMediationConfigurations
()

List<Mediation Returns all mediation configurations for


ConfigurationW thesystem.
S>

createMediationConfiguration
(MediationConfigurationWS
cfg)

MediationConfigur
ationWS

Savesanewmediationconfiguration.

updateAllMediationConfigurat List<MediationCon List<Integer>


ions(List<MediationConfigurat figurationWS>
ionWS>configurations)

Updates
all
given
mediation
configurations. Given configs must have
anID.

deleteMediationConfiguration
(IntegercfgId)

Deletesthegivenmediationconfiguration.

Integer

Triggers the mediation process for a


specific configuration and returns the

ConfigurationID

triggerMediationByConfigurati Mediation
on(IntegercfgId)
ConfigurationID

Copyright2013EnterprisejBillingSoftwareLtd

76

mediation process id of the running


process.

isMediationProcessRunning()

Boolean

Returns true if a running Mediation


Process exists for the given entity id. A
process is considered to be running if it
doesnothaveanendtime,falseifnot.

ProcessStatus
WS

Returns the status of the last run (or


currentlyrunning)mediationprocess.

getMediationProcessStatus()

getMediationProcess(Integer
mediationProcessId)

Mediation Process MediationProce Returns the mediation process for the


ID
ssWS
givenprocessidornullifnotfound.

ProvisioningProcessAPIMethods
APIMethod

Arguments

Returns

Description

triggerProvisioning()

Triggerstheprovisioningprocess.

updateOrderAndLineProvisio Order ID, Order


ningStatus(Integer inOrderId, LineID,Result
IntegerinLineId,Stringresult)

Updates the order or line provisioning


status to the set result (either "fail",
"unavailable"or"success").

updateLineProvisioningStatus Order Line


(Integer orderLineId, Integer StatusID
provisioningStatus)

Updatestheorderlineprovisioningstatus.

ID,

PreferenceAPIMethods
APIMethod

Arguments

Returns

Description

updatePreferences(Preferenc
eWSprefList)

PreferenceWS

Storesallthegivenpreferencevalues.

Copyright2013EnterprisejBillingSoftwareLtd

77

updatePreference(Preference
WSpreference)

PreferenceWS

Storedthegivenpreferencevalue.

getPreference(Integer
preferenceTypeId)

PreferenceTypeID PreferenceWS

Returns the preference for the given


preferencetypeid.

getCurrencies()

CurrencyWS

Returnsalistofconfiguredcurrencies.

updateCurrencies(CurrencyW CurrencyWS
Scurrencies)

Storesallthegivencurrencyvalues.

updateCurrency(CurrencyWS CurrencyWS
currency)

Updates the given currency. Storing the


exchange rate, system rate, and currency
availability.

createCurrency(CurrencyWS
currency)

CurrencyWS

Integer

Savesanewcurrencytypeandreturnsthe
newID.

getCompany()

CompanyWS

Returns the company contact details for


theAPIuserscompany.

updateCompany(CompanyW
ScompanyWS)

CompanyWS

Updates the company contact details for


theAPIuserscompany.

createUpdateNotification(Inte Mesage
ID
,
ger messageId, MessageDTO MessageDTO@
dto)

Saves or updates an existing notification


message.

PluginAPIMethods

APIMethod

Arguments

Returns

Description

Copyright2013EnterprisejBillingSoftwareLtd

78

getPluginWS(IntegerpluginId) PluginID

PluggableTask
WS

Returns the configured plugin for the


givenID.

createPlugin(PluggableTask
WSplugin)

PluggableTaskWS Integer

Saves the given plugin and returns the


newID.

updatePlugin(PluggableTask
WSplugin)

PluggableTaskWS

Updates the stored plugin. Given plugin


musthaveanID.

deletePlugin(Integerplugin)

Integer

Deletesthegivenplugin

Returns

Description

This method reschedules an existing


scheduled task that got changed. If not
existing, the new plugin may need to be
scheduled only if it is an instance of
IscheduledTask.

QuartzJobAPIMethods

APIMethod

Arguments

rescheduleScheduledPlugin(I PluginID
ntegerpluginId)

AppendixA
ConstantsReference
LanguageCodes
Code

Name

English

Portuguese

CurrencyCodes
Code

CurrencyName ISOCode

Symbol

Country

Copyright2013EnterprisejBillingSoftwareLtd

79

UnitedStatesDollar USD

US$

USA

CanadianDollar

CAD

C$

Canada

Euro

EUR

<pre>&euro</pre>

Europe

Yen

JPY

Japan

PoundSterling

GBP

UnitedKingdom

SouthKoreanWon

KRW

SouthKorea

SwissFranc

CHF

Sf

Switzerland

SwedishKrona

SEK

SeK

Sweden

SingaporeDollar

SGD

S$

Singapore

10

Ringgit

MYR

M$

Malaysia

11

AustralianDollar

AUD

Australia

RoleCodes
Code

Meaning

Internal

SuperUser

Clerk

Partner

Customer

UserStatusCodes
Code

Meaning

Active

Overdue

Overdue2

Overdue3

Suspended

Suspended2

Suspended3

Deleted

SubscriberStatusCodes
Code

Meaning

Active

Copyright2013EnterprisejBillingSoftwareLtd

80

PendingSubscription

Unsubscribed

PendingExpiration

Expired

Nonsubscriber

Discontinued

PaymentMethodCodes
Code

Meaning

Cheque

Visa

MasterCard

AMEX

ACH/CCA

Discovery

Diners

PayPal

OrderStatusCodes
Code

Meaning

Active

Finished

Suspended

Suspended(auto)

OrderBillingTypeCodes
Code

Meaning

Prepaid

Postpaid

OrderLineTypeCodes
Code

Meaning

Item

Copyright2013EnterprisejBillingSoftwareLtd

81

Tax

Penalty

InvoiceStatusCodes
Code

Meaning

Paid

Unpaid

Unpaid,balancecarriedtoanewinvoice.

Periodunits(unitsoftime)
Unit

Meaning

Month

Week

Day

Year

Paymentresults
Code

Meaning

Successful

Failed

Paymentgatewaynotavailable

Manuallyentered(paymentgatewaynotinvolved,such
asacheque).

DynamicBalanceCodes
Code

Meaning

Nodynamicbalance

Prepaid

Creditlimit

ProvisioningStatusCodes

Copyright2013EnterprisejBillingSoftwareLtd

82

Code

Meaning

Active

Inactive

PendingActive

PendingInactive

Failed

Unavailable

AutomaticPaymentType
Code

Meaning

CreditCard

ACH

Cheque

InvoiceDeliveryMethod
Code

Meaning

Email

Paper

BothEmail&Paper

AppendixB
HowtousethejBilling3Logsforintegration
The jBilling 3 logs are located at logsjbilling.log. The logs will contain debugstatements
at the entry and exit of certain API method calls. These debug statements at entry and exit of
API method calls, specifically, from the Web Services API calls can be quite useful for
developerswhocanusethisadditionalinformationforintegrationofothersystemswithjBilling3.
For example, take alook atthebelowsnapshotfromjbilling.loglogs.

Thebelowsnapshot
isanoutputaftersubmittingonthe'CreateOrder'pageofjBilling3.
2011072017:02:08,660DEBUG
[com.sapienter.jbilling.server.util.api.APILogger]DonecalltocreateOrder
returning:107900
2011072017:02:09,280DEBUG
[com.sapienter.jbilling.server.util.api.APILogger]CalltogetOrder
parameters:[107900]

Copyright2013EnterprisejBillingSoftwareLtd

83

2011072017:02:12,103DEBUG
[com.sapienter.jbilling.server.invoice.InvoiceBL]converstion0
2011072017:02:12,103DEBUG
[com.sapienter.jbilling.server.util.api.APILogger]DonecalltogetOrder
returning:OrderWS{id=107900,userId=10790,currencyId=1,activeUntil=null,
activeSince=2011072000:00:00.0,isCurrent=1,statusStr='Active',
periodStr='Monthly',periodId=2,billingTypeStr='prepaid',
lines=[OrderLineWS{id=208100,amount='10.0000000000',quantity='1.0000000000',
price='10.0000000000',deleted=0,description='LongdistancecallGeneric',
useItem=false,itemId=2900,typeId=1}]}
2011072017:02:12,163DEBUG
[com.sapienter.jbilling.server.util.api.APILogger]CalltogetUserWS
parameters:[10790]
2011072017:02:12,227DEBUG
[com.sapienter.jbilling.server.util.PreferenceBL]Lookingforpreference43,
forentity1andtable'entity'
2011072017:02:12,265DEBUG
[com.sapienter.jbilling.server.util.PreferenceBL]Lookingforpreference43,
forentity1andtable'entity'

The Web Services APIthatis exposedforintegrationofjBillingwithexternalsystems is usedas


an inline Java API for making the same transactions that are supported via API, which has
becomeextensiveandfullyfunctionalinjBilling3.
Let us takeanotherexampleofusingthelogs tounderstandingtheintegrationAPIcalls thatmay
berequiredforexample,tomakeaPayment.
ThestepsrequiredontheGUIformakingaPaymentareasfollows:
1. ListInvoicesbyclickingon'Invoices'linkinthemainmenu
2. Select anInvoicefromthelistofInvoices (TheselectedInvoicedetails aredisplayedon
therighthandside)
3. Clickon'PayInvoice'
4. ChooseaPaymentoption
5. ConfirmandSubmit
Suppose we have performed above actions on the GUI, there are certain parts in the log trace
thatI'dliketohighlightforeachoftheabovesteps.
2011072017:21:37,406DEBUG
[com.sapienter.jbilling.server.util.api.APILogger]CalltogetInvoiceWS
parameters:[70]
2011072017:21:37,415DEBUG
[com.sapienter.jbilling.server.util.api.APILogger]DonecalltogetInvoiceWS
returning:InvoiceWS[balance=20.0000000000,carriedBalance=0E10,
createDateTime=2007072600:00:00.0,createTimeStamp=2007072618:17:19.113,
currencyId=1,customerNotes=null,delegatedInvoiceId=null,deleted=0,

Copyright2013EnterprisejBillingSoftwareLtd

84

dueDate=2007082600:00:00.0,id=70,inProcessPayment=1,invoiceLines=[{id=67
description=Lemonadeallyoucandrinkmonthlyamount=20.0000000000
price=20.0000000000quantity=1.0000000000deleted=0itemId=2
sourceUserId=10743isPercentage=0}],isReview=0,lastReminder=null,number=11,
orders=[],overdueStep=null,paymentAttempts=0,payments=[],
statusDescr=Unpaid,statusId=2,toProcess=1,total=20.0000000000,
userId=10743]
2011072017:21:37,420DEBUG
[com.sapienter.jbilling.server.util.api.APILogger]CalltogetUserWS
parameters:[10743]

SelectaparticularInvoice(70),APICallgetInvoiceWS()
2011072017:21:37,572DEBUG
[com.sapienter.jbilling.server.util.api.APILogger]DonecalltogetUserWS
returning:UserWS[ach=null,autoRecharge=0E10,automaticPaymentType=1,
balanceType=1,blacklistMatches=[],childIds=[],companyName=PrancingPony,
contact=ContactWS{id=112603,type=null,title='null',lastName='Baggins',
firstName='Frodo',initial='null',organization='null',address1='null',
address2='null',city='null',stateProvince='null',postalCode='null',
countryCode='null',phone='',fax='',email='frodo@shire.com',type='null',
include='1'},createDatetime=2009103000:00:00.0,creditCard=null,
creditLimit=0E10,currencyId=1,customerId=1067,deleted=0,
dueDateUnitId=null,dueDateValue=null,dynamicBalance=0E10,
excludeAgeing=false,failedAttempts=0,id=10743,invoiceChild=false,
invoiceDeliveryMethodId=null,isParent=false,language=English,languageId=1,
lastLogin=null,lastStatusChange=null,mainOrderId=null,mainRoleId=5,
nextInvoiceDate=null,notes=null,owingBalance=20.0000000000,parentId=null,
partnerId=null,password=46f94c8de14fb36680850768ff1b7f2a,role=Customer,
status=Active,statusId=1,subscriberStatusId=6,userIdBlacklisted=false,
userName=carryovertest1]
2011072017:21:37,576DEBUG
[com.sapienter.jbilling.server.util.api.APILogger]Callto
getTotalRevenueByUserparameters:[10743]
2011072017:21:37,587DEBUG
[com.sapienter.jbilling.server.util.api.APILogger]Donecallto
getTotalRevenueByUserreturning:0
2011072017:21:37,827DEBUG
[com.sapienter.jbilling.server.util.PreferenceBL]Lookingforpreference20,
forentity1andtable'entity'
2011072017:22:27,422DEBUG
[com.sapienter.jbilling.server.util.api.APILogger]CalltogetUserWS
parameters:[10743]
2011072017:22:27,512DEBUG[com.sapienter.jbilling.server.user.ContactBL]
ContactDTO:gettingcustomfields
2011072017:22:27,516DEBUG[com.sapienter.jbilling.server.user.ContactBL]
Returningdtowith3fields
2011072017:22:27,516DEBUG

Copyright2013EnterprisejBillingSoftwareLtd

85

[com.sapienter.jbilling.server.util.api.APILogger]DonecalltogetUserWS
returning:UserWS[ach=null,autoRecharge=0E10,automaticPaymentType=1,
balanceType=1,blacklistMatches=[],childIds=[],companyName=PrancingPony,
contact=ContactWS{id=112603,type=null,title='null',lastName='Baggins',
firstName='Frodo',initial='null',organization='null',address1='null',
address2='null',city='null',stateProvince='null',postalCode='null',
countryCode='null',phone='',fax='',email='frodo@shire.com',type='null',
include='1'},createDatetime=2009103000:00:00.0,creditCard=null,
creditLimit=0E10,currencyId=1,customerId=1067,deleted=0,
dueDateUnitId=null,dueDateValue=null,dynamicBalance=0E10,
excludeAgeing=false,failedAttempts=0,id=10743,invoiceChild=false,
invoiceDeliveryMethodId=null,isParent=false,language=English,languageId=1,
lastLogin=null,lastStatusChange=null,mainOrderId=null,mainRoleId=5,
nextInvoiceDate=null,notes=null,owingBalance=20.0000000000,parentId=null,
partnerId=null,password=46f94c8de14fb36680850768ff1b7f2a,role=Customer,
status=Active,statusId=1,subscriberStatusId=6,userIdBlacklisted=false,
userName=carryovertest1]
2011072017:22:27,521DEBUG
[com.sapienter.jbilling.server.util.api.APILogger]CalltogetUnpaidInvoices
parameters:[10743]
2011072017:22:27,714DEBUG
[com.sapienter.jbilling.server.util.api.APILogger]Donecallto
getUnpaidInvoicesreturning:[70]
2011072017:22:27,717DEBUG
[com.sapienter.jbilling.server.util.api.APILogger]CalltogetInvoiceWS
parameters:[70]
2011072017:22:27,726DEBUG
[com.sapienter.jbilling.server.util.api.APILogger]DonecalltogetInvoiceWS
returning:InvoiceWS[balance=20.0000000000,carriedBalance=0E10,
createDateTime=2007072600:00:00.0,createTimeStamp=2007072618:17:19.113,
currencyId=1,customerNotes=null,delegatedInvoiceId=null,deleted=0,
dueDate=2007082600:00:00.0,id=70,inProcessPayment=1,invoiceLines=[{id=67
description=Lemonadeallyoucandrinkmonthlyamount=20.0000000000
price=20.0000000000quantity=1.0000000000deleted=0itemId=2
sourceUserId=10743isPercentage=0}],isReview=0,lastReminder=null,number=11,
orders=[],overdueStep=null,paymentAttempts=0,payments=[],
statusDescr=Unpaid,statusId=2,toProcess=1,total=20.0000000000,
userId=10743]

Click 'Pay Invoice', behind the scenes API Calls like getUserPaymentInstrument(),
getUnpaidInvoices()etc.
2011072017:22:27,731DEBUG
[com.sapienter.jbilling.server.util.api.APILogger]Callto
getUserPaymentInstrumentparameters:[10743]
2011072017:22:27,819DEBUG
[com.sapienter.jbilling.server.pluggableTask.admin.PluggableTaskManager]total
classes=1

Copyright2013EnterprisejBillingSoftwareLtd

86

2011072017:22:27,819DEBUG
[com.sapienter.jbilling.server.pluggableTask.admin.PluggableTaskManager]
Applyingtaskcom.sapienter.jbilling.server.pluggableTask.BasicPaymentInfoTask
2011072017:22:27,951DEBUG
[com.sapienter.jbilling.server.pluggableTask.BasicPaymentInfoTask]Couldnot
findpaymentinstrumentforuser10743
2011072017:22:27,951DEBUG
[com.sapienter.jbilling.server.util.api.APILogger]Donecallto
getUserPaymentInstrumentreturning:null
2011072017:23:09,081DEBUG
[com.sapienter.jbilling.server.util.api.APILogger]CalltogetUserWS
parameters:[10743]
2011072017:23:09,112DEBUG
[com.sapienter.jbilling.server.util.PreferenceBL]Lookingforpreference43,
forentity1andtable'entity'
2011072017:23:09,119DEBUG
[com.sapienter.jbilling.server.util.PreferenceBL]Lookingforpreference43,
forentity1andtable'entity'
2011072017:23:09,170DEBUG
[com.sapienter.jbilling.server.payment.tasks.PaymentFilterTask]UserIdFilter
enabled
2011072017:23:09,170DEBUG
[com.sapienter.jbilling.server.payment.tasks.PaymentFilterTask]NameFilter
enabled
2011072017:23:09,170DEBUG
[com.sapienter.jbilling.server.payment.tasks.PaymentFilterTask]
CreditCardFilterenabled
2011072017:23:09,170DEBUG
[com.sapienter.jbilling.server.payment.tasks.PaymentFilterTask]AddressFilter
enabled
2011072017:23:09,170DEBUG
[com.sapienter.jbilling.server.payment.tasks.PaymentFilterTask]
IpAddressFilterenabled
2011072017:23:09,170DEBUG
[com.sapienter.jbilling.server.payment.tasks.PaymentFilterTask]PhoneFilter
enabled
2011072017:23:09,226DEBUG[com.sapienter.jbilling.server.user.ContactBL]
ContactDTO:gettingcustomfields
2011072017:23:09,232DEBUG[com.sapienter.jbilling.server.user.ContactBL]
Returningdtowith3fields
2011072017:23:09,232DEBUG
[com.sapienter.jbilling.server.util.api.APILogger]DonecalltogetUserWS
returning:UserWS[ach=null,autoRecharge=0E10,automaticPaymentType=1,
balanceType=1,blacklistMatches=[],childIds=[],companyName=PrancingPony,
contact=ContactWS{id=112603,type=null,title='null',lastName='Baggins',
firstName='Frodo',initial='null',organization='null',address1='null',
address2='null',city='null',stateProvince='null',postalCode='null',
countryCode='null',phone='',fax='',email='frodo@shire.com',type='null',

Copyright2013EnterprisejBillingSoftwareLtd

87

include='1'},createDatetime=2009103000:00:00.0,creditCard=null,
creditLimit=0E10,currencyId=1,customerId=1067,deleted=0,
dueDateUnitId=null,dueDateValue=null,dynamicBalance=0E10,
excludeAgeing=false,failedAttempts=0,id=10743,invoiceChild=false,
invoiceDeliveryMethodId=null,isParent=false,language=English,languageId=1,
lastLogin=null,lastStatusChange=null,mainOrderId=null,mainRoleId=5,
nextInvoiceDate=null,notes=null,owingBalance=20.0000000000,parentId=null,
partnerId=null,password=46f94c8de14fb36680850768ff1b7f2a,role=Customer,
status=Active,statusId=1,subscriberStatusId=6,userIdBlacklisted=false,
userName=carryovertest1]
2011072017:23:09,235DEBUG
[com.sapienter.jbilling.server.util.api.APILogger]CalltogetUnpaidInvoices
parameters:[10743]
2011072017:23:09,246DEBUG
[com.sapienter.jbilling.server.util.api.APILogger]Donecallto
getUnpaidInvoicesreturning:[70]
2011072017:23:09,249DEBUG
[com.sapienter.jbilling.server.util.api.APILogger]CalltogetInvoiceWS
parameters:[70]
2011072017:23:09,273DEBUG
[com.sapienter.jbilling.server.util.api.APILogger]DonecalltogetInvoiceWS
returning:InvoiceWS[balance=20.0000000000,carriedBalance=0E10,
createDateTime=2007072600:00:00.0,createTimeStamp=2007072618:17:19.113,
currencyId=1,customerNotes=null,delegatedInvoiceId=null,deleted=0,
dueDate=2007082600:00:00.0,id=70,inProcessPayment=1,invoiceLines=[{id=67
description=Lemonadeallyoucandrinkmonthlyamount=20.0000000000
price=20.0000000000quantity=1.0000000000deleted=0itemId=2
sourceUserId=10743isPercentage=0}],isReview=0,lastReminder=null,number=11,
orders=[],overdueStep=null,paymentAttempts=0,payments=[],
statusDescr=Unpaid,statusId=2,toProcess=1,total=20.0000000000,
userId=10743]

Makeapayment,APICallapplyPayment()
2011072017:23:14,077DEBUG
[grails.app.controller.jbilling.PaymentController]creatingpayment
PaymentWS{id=0,baseUserId=null,paymentMethodId=1,method='null',
amount='20.00',balance='null',isRefund=0,isPreauth=null,paymentDate=Wed
Jul2000:00:00IST2011,deleted=0}forinvoice70
2011072017:23:14,077DEBUG
[grails.app.controller.jbilling.PaymentController]creatingpayment
PaymentWS{id=0,baseUserId=null,paymentMethodId=1,method='null',
amount='20.00',balance='null',isRefund=0,isPreauth=null,paymentDate=Wed
Jul2000:00:00IST2011,deleted=0}forinvoice70
2011072017:23:14,077DEBUG
[grails.app.controller.jbilling.PaymentController]enteringpayment
2011072017:23:14,077DEBUG
[grails.app.controller.jbilling.PaymentController]enteringpayment

Copyright2013EnterprisejBillingSoftwareLtd

88

2011072017:23:14,078DEBUG
[com.sapienter.jbilling.server.util.api.APILogger]CalltoapplyPayment
parameters:[PaymentWS{id=0,baseUserId=null,paymentMethodId=1,
method='null',amount='20.00',balance='null',isRefund=0,isPreauth=null,
paymentDate=WedJul2000:00:00IST2011,deleted=0},70]
2011072017:23:14,147DEBUG
[com.sapienter.jbilling.server.util.db.JbillingTableDAS]Lookingfortable+
payment
2011072017:23:14,151DEBUG
[com.sapienter.jbilling.server.payment.PaymentSessionBean]applyingpaymentto
invoice70
2011072017:23:14,152DEBUG
[com.sapienter.jbilling.server.payment.PaymentSessionBean]Setinvoicebalance
to:0
2011072017:23:14,216DEBUG
[com.sapienter.jbilling.server.pluggableTask.admin.PluggableTaskManager]total
classes=1
2011072017:23:14,216DEBUG
[com.sapienter.jbilling.server.pluggableTask.admin.PluggableTaskManager]
Applyingtaskcom.sapienter.jbilling.server.process.task.BasicAgeingTask
2011072017:23:14,320DEBUG
[com.sapienter.jbilling.server.invoice.InvoiceBL]userwithinvoice:70
2011072017:23:14,320DEBUG
[com.sapienter.jbilling.server.invoice.InvoiceBL]userwithoverdue:true
2011072017:23:14,320DEBUG
[com.sapienter.jbilling.server.process.task.BasicAgeingTask]User10743still
hasoverdueinvoices,cannotremovefromageing.
2011072017:23:14,323DEBUG
[com.sapienter.jbilling.server.system.event.EventManager]processingevent
PaymentSuccessfulEvent{paymentId=1900,amount=20.00}
2011072017:23:14,323DEBUG
[com.sapienter.jbilling.server.system.event.InternalEventProcessor]In
InternalEventProcessor::process()
2011072017:23:14,346DEBUG
[com.sapienter.jbilling.server.pluggableTask.admin.PluggableTaskManager]total
classes=8
2011072017:23:14,346DEBUG
[com.sapienter.jbilling.server.system.event.InternalEventProcessor]Processing
PaymentSuccessfulEvent{paymentId=1900,amount=20.00}with
com.sapienter.jbilling.server.user.balance.DynamicBalanceManagerTask@7fa58648
2011072017:23:14,346DEBUG
[com.sapienter.jbilling.server.user.balance.DynamicBalanceManagerTask]Nothing
toupdate
2011072017:23:14,347DEBUG
[com.sapienter.jbilling.server.system.event.EventManager]Nowprocessingwith
com.sapienter.jbilling.server.user.event.SubscriptionStatusEventProcessor
2011072017:23:14,355DEBUG
[com.sapienter.jbilling.server.pluggableTask.admin.PluggableTaskManager]total

Copyright2013EnterprisejBillingSoftwareLtd

89

classes=1
2011072017:23:14,355DEBUG
[com.sapienter.jbilling.server.pluggableTask.admin.PluggableTaskManager]
Applyingtask
com.sapienter.jbilling.server.user.tasks.BasicSubscriptionStatusManagerTask
2011072017:23:14,370DEBUG
[com.sapienter.jbilling.server.system.event.EventManager]Nowprocessingwith
com.sapienter.jbilling.server.payment.event.GatewayAlarmEventProcessor
2011072017:23:14,370DEBUG
[com.sapienter.jbilling.server.util.api.APILogger]DonecalltoapplyPayment
returning:1900

Finally, check theentry 'DonecalltoapplyPaymentreturning:1900',wheredatabase1900is


theIDofthePaymentcreatedinthesystem.
These behind the scenes API calls and their sequence of invocations show the API calls that
may have to be performed for performing similar actions from a third party system like a CRM
systemforasimilaractiononjBilling.
Similarly, logs can be used to check the API calls required for other actions that can be
mimickedbyperformingsimilaractionsontheGUI.

RevisionHistory
Date

Author

Version Description

07/26/2013

MaheshShivarkar

1.0

ReceiveddocumentforupdationofnewAPImethods.

07/30/2013

MaheshShivarkar

1.1

CopiedexistingAPIreferencefromthedocumenttothe
integrationguideunderWebServicesAPIreference
section..

07/31/2013

MaheshShivarkar

1.2

AddedmissingAPIreferencesfromrelease3.2inthe
IntegrationGuide.

08/02/2013

MaheshShivarkar

1.3

Validatedallconstantsavailableinthedocument,
foundallarecorrect.Addedmissingconstant.

08/07/2013

MaheshShivarkar

1.4

Validatedobjectreferences.Addedmissingfieldsofthe
objects&theirbehaviours,correctedsomeobjects
properties&theirdescriptions.Removedunused
properties.

08/29/2013

MaheshShivarkar

1.5

Completedpendingfieldsdescriptionsoftheobjects.
AddedRevisionHistorytable.

Copyright2013EnterprisejBillingSoftwareLtd

90

You might also like