JBilling 3.2 Integration Guide
JBilling 3.2 Integration Guide
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
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
Copyright2013EnterprisejBillingSoftwareLtd
'/httpinvoker/**':
'securityContextPersistenceFilter,staticAuthenticationProcessingFilte
r,securityContextHolderAwareRequestFilter,basicExceptionTranslationFi
lter,filterInvocationInterceptor',
'/**':
'JOINED_FILTERS,basicAuthenticationFilter,basicExceptionTranslation
Filter'
]
The staticAuthenticationProcessingFilter itself is configured in the jBilling
resources.groovyfile.
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
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
Copyright2013EnterprisejBillingSoftwareLtd
14
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
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® 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.
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("[email protected]")
$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("[email protected]")
$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
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.
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("[email protected]")
//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
CustomContactFields
The User's Contact Information is extensible for adding additional user Contact information.
Thus, two fields of the ContactWSstructure
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.
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
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.
and
encode an array of PricingFieldclasses
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
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.
//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.
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
WebServices APIReference
InvoiceAPIMethods
APIMethod
Arguments
Returns
Description
getInvoiceWS(Integer
invoiceId)
InvoiceID
InvoiceWS
Copyright2013EnterprisejBillingSoftwareLtd
61
deleteInvoice(Integer
invoiceId)
Deletesthegiveninvoice.
getAllInvoicesForUser(Intege UserID
ruserId)
InvoiceWS
getAllInvoices(IntegeruserId) UserID
Integer
ReturnsanarrayofinvoiceIDsforthegiven
user.
getLatestInvoice(Integer
userId)
UserID
InvoiceWS
getLastInvoices(Integer
userId,Integernumber)
UserID,numberof Integer
invoices
getInvoicesByDate(String
since,Stringuntil)
getUserInvoicesPage(Integer UserID,
userId, Integer limit, Integer Offset
offset)
getUnpaidInvoices(Integer
userId)
InvoiceID
UserID
Limit, InvoiceWS
Integer
notifyInvoiceByEmail(Integer InvoiceID
invoiceId)
Boolean
success
getPaperInvoicePDF(Integer InvoiceID
invoiceId)
Byte
Copyright2013EnterprisejBillingSoftwareLtd
62
notifyPaymentByEmail(Intege PaymentID
rpaymentId)
createInvoiceWithDate(Integ
er userId, Date billingDate,
Integer
dueDatePeriodId,
Integer dueDatePeriodValue,
booleanonlyRecurring)
Boolean
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
ReturnstheitemforthegivenID.
getAllItems()
ItemDTOEx
Returnsanarrayofallitemsinthesystem.
createItem(ItemDTOExitem)
ItemDTOEx
Integer
updateItem(ItemDTOExitem)
ItemDTOEx
deleteItem(IntegeritemId)
ItemID
Deletesthegivenitem.
getItemByCategory(Integer
itemTypeId)
ItemTypeID
ItemDTOEx
getAllItemCategories()
ItemTypeWS
createItemCategory(ItemType
WSitemType)
ItemTypeWS
Integer
updateItemCategory(ItemType ItemTypeWS
WSitemType)
deleteItemCategory(Integer
itemCategoryId)
Deletesthegivenitemtype.
ItemTypeID
Copyright2013EnterprisejBillingSoftwareLtd
65
isUserSubscribedTo(Integer
userId,IntegeritemId)
UserID,ItemID
String
getUserOrdersPage(Integer
User,Limit,Offset OrderWS
user, Integer limit, Integer
offset)
validatePurchase(Integer
User ID, Item ID, ValidatePurcha
userId, Integer itemId, String Pricingstring
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)
getTotalRevenueByUser(Integ UserID
eruserId)
BigDecimal
getUserPaymentInstrument(Int UserID
egeruserId)
PaymentWS
Limit, PaymentWS
createPayment(PaymentWS
payment)
PaymentWS
Integer
updatePayment(PaymentWS
payment)
PaymentWS
deletePayment(Integer
paymentId)
PaymentID
Deletesthegivenpayment.
removePaymentLink(Integer
invoiceId,IntegerpaymentId)
Invoice
PaymentID
ID,
removeAllPaymentLinks(Integ PaymentID
erpaymentId)
Removes allthelinksbetweenapayment
andinvoice.
ID,
createPaymentLink(Integer
invoiceId,IntegerpaymentId)
Invoice
PaymentID
payInvoice(IntegerinvoiceId)
InvoiceID
Copyright2013EnterprisejBillingSoftwareLtd
67
applyPayment(PaymentWS
payment,IntegerinvoiceId)
PaymentWS,
InvoiceID
processPayment(PaymentWS PaymentWS,
payment,IntegerinvoiceId)
InvoiceID
Integer
validateCreditCard(com.sapie CreditCardDTO,
CardValidation
nter.jbilling.server.entity.Credit ContactWS, Level WS
CardDTO
creditCard, innumber(1/2/3)
ContactWScontact,intlevel)
ReturnsobjectofCardValidationWS.
UserAPIMethods
APIMethod
Arguments
Returns
Description
getUserWS(IntegeruserId)
UserID
UserWS
ReturnstheuserforthegivenID.
createUser(UserWSnewUser) UserWS
Integer
updateUser(UserWSuser)
UserWS
deleteUser(IntegeruserId)
UserID
Deletesthegivenuser.
Copyright2013EnterprisejBillingSoftwareLtd
68
getUserContactsWS(Integer
userId)
UserID
ContactWS
updateUserContact(Integer
User ID, Contact
userId,
Integer
typeId, Type
ID,
ContactWScontact)
ContactWS
getContactTypeWS(Integer
contactTypeId)
ContactTypeW
S
ReturnsthecontacttypeforthegivenID.
Integer
ContactTypeID
createContactTypeWS(Contac ContactTypeWS
tTypeWScontactType)
updateCreditCard(Integer
User ID, Credit
userId,
CreditCardDTO Card
creditCard)
Updatesthegivenuserscreditcarddata.
updateAch(Integer
AchDTOach)
getAuthPaymentType(Integer UserID
userId)
Integer
getUsersByStatus(Integer
statusId,booleanin)
If "in" true,returnsalistofuserswhoarein
the givens status, if false, a list of users
whoareNOTinthegivenstatus.
getUsersInStatus(Integer
statusId)
StatusID
Integer
getUsersNotInStatus(Integer
statusId)
StatusID
Integer
userId, UserID,ACH
Copyright2013EnterprisejBillingSoftwareLtd
69
getUsersByCreditCard(String Credit
number)
number
Card Integer
Integer
saveCustomContactFields(Co ContactFieldType
ntactFieldTypeWSfields)
WS
processPartnerPayouts(Date
runDate)
RunDate
getPartner(IntegerpartnerId)
PatnerID
PartnerWS
ReturnsthepartnerforthegivenID.
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
saveCustomerNotes(Integer
userId,Stringnotes)
UserID,Notes
Updatesthegivenusersnotes.
userExistsWithName(String
userName)
UserName
Boolean
userExistsWithId(Integer
userId)
UserID
Boolean
getUserIdByEmail(String
email)
EmailID
Integer
Copyright2013EnterprisejBillingSoftwareLtd
70
triggerPartnerPayoutProcess(
DaterunDate)
RunDate
processPartnerPayout(Integer PartnerID
partnerId)
createPartner(UserWS
UserWS,
newUser,PartnerWSpartner) PartnerWS
Integer
updatePartner(UserWS
UserWS,
newUser,PartnerWSpartner) PartnerWS
deletePartner(Integer
partnerId)
PartnerID
deleteCreditCard(Integer
userId)
UserID
deleteAch(IntegeruserId)
UserID
Integer
getAutoPaymentType(Integer UserID
userId)
Copyright2013EnterprisejBillingSoftwareLtd
71
PlansandSpecialPricingAPIMethods
APIMethod
Arguments
Returns
Description
getPlanWS(IntegerplanId)
PlanID
PlanWS
ReturnstheplanforthegivenID.
createPlan(PlanWSplan)
PlanWS
Integer
SavethegivenplanandreturnthenewID.
updatePlan(PlanWSplan)
PlanWS
deletePlan(IntegerplanId)
PlanID
Deletesthegivenplan.
ID,
Addsanewpricetothegivenplan.
isCustomerSubscribed(Intege
rplanId,IntegeruserId)
PlanID,UserID
boolean
Returnstrueifthegivenuserissubscribed
totheplan,falseifnot.
getSubscribedCustomers(Inte
gerplanId)
PlanID
Integer
getPlansBySubscriptionItem(I
ntegeritemId)
ItemID
Integer
getPlansByAffectedItem(Integ
eritemId)
ItemID
Integer
createCustomerPrice(Integer User
userId,PlanItemWSplanItem) PlanItemWS
ID, PlanItemWS
updateCustomerPrice(Integer User
userId,PlanItemWSplanItem) PlanItemWS
ID,
Copyright2013EnterprisejBillingSoftwareLtd
72
deleteCustomerPrice(Integer
userId,IntegerplanItemId)
Deletesacustomerspecificprice.
getCustomerPrices(Integer
userId)
UserID
PlanItemWS
getCustomerPrice(Integer
userId,IntegeritemId)
UserID,ItemID
PlanItemWS
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
getCallerCompanyId()
Integer
of
the
getCallerLanguageId()
Integer
of
the
getCallerCurrencyId()
Integer
of
the
PlanWS
getAllPlans()
Copyright2013EnterprisejBillingSoftwareLtd
73
BillingProcessAPIMethods
APIMethod
Arguments
Returns
Description
isBillingRunning()
boolean
triggerBillingAsync(Date
runDate)
Rundate
triggerBilling(DaterunDate)
Rundate
boolean
triggerAgeing(DaterunDate)
Rundate
Triggerstheuserageingprocess.
getBillingProcessConfiguratio
n()
BillingProcessC Returnsthebillingprocessconfiguration.
onfigurationWS
Updatesthecurrentbillingconfiguration.
getBillingProcess(Integer
processId)
ProcessID
BillingProcess
WS
getLastBillingProcess()
Integer
getOrderProcesses(Integer
orderId)
OrderID
List<OrderProc
essWS>
getOrderProcessesByInvoice(I InvoiceID
ntegerinvoiceId)
List<OrderProc
essWS>
getReviewBillingProcess()
BillingProcess
WS
Copyright2013EnterprisejBillingSoftwareLtd
74
setReviewApproval(Boolean
flag)
getBillingProcessGeneratedIn ProcessID
voices(IntegerprocessId)
List<Integer>
getAgeingConfiguration(Integ
erlanguageId)
AgeingWS
LanguageID
isAgeingProcessRunning()
Boolean
ProcessStatus
WS
isBillingRunning(Integer
entityId)
EntityID
Boolean
getBillingProcessStatus()
ProcessStatus
WS
getAgeingProcessStatus()
MediationProcessAPIMethods
APIMethod
Arguments
Returns
Description
Copyright2013EnterprisejBillingSoftwareLtd
75
triggerMediation()
Triggersthemediationprocess.
isMediationProcessing()
boolean
getAllMediationProcesses()
List<Mediation
ProcessWS>
getMediationEventsForOrder(I OrderID
ntegerorderId)
List<Mediation
RecordLineWS
>
Returns alistofmediationevents(external
datareadin)forthegivenorder.
getMediationEventsForInvoice InvoiceID
(IntegerinvoiceId)
List<Mediation
RecordLineWS
>
Returns alistofmediationevents(external
datareadin)forthegiveninvoice.
getNumberOfMediationRecor
dsByStatuses()
List<RecordCo
untWS>
getAllMediationConfigurations
()
createMediationConfiguration
(MediationConfigurationWS
cfg)
MediationConfigur
ationWS
Savesanewmediationconfiguration.
Updates
all
given
mediation
configurations. Given configs must have
anID.
deleteMediationConfiguration
(IntegercfgId)
Deletesthegivenmediationconfiguration.
Integer
ConfigurationID
triggerMediationByConfigurati Mediation
on(IntegercfgId)
ConfigurationID
Copyright2013EnterprisejBillingSoftwareLtd
76
isMediationProcessRunning()
Boolean
ProcessStatus
WS
getMediationProcessStatus()
getMediationProcess(Integer
mediationProcessId)
ProvisioningProcessAPIMethods
APIMethod
Arguments
Returns
Description
triggerProvisioning()
Triggerstheprovisioningprocess.
Updatestheorderlineprovisioningstatus.
ID,
PreferenceAPIMethods
APIMethod
Arguments
Returns
Description
updatePreferences(Preferenc
eWSprefList)
PreferenceWS
Storesallthegivenpreferencevalues.
Copyright2013EnterprisejBillingSoftwareLtd
77
updatePreference(Preference
WSpreference)
PreferenceWS
Storedthegivenpreferencevalue.
getPreference(Integer
preferenceTypeId)
PreferenceTypeID PreferenceWS
getCurrencies()
CurrencyWS
Returnsalistofconfiguredcurrencies.
updateCurrencies(CurrencyW CurrencyWS
Scurrencies)
Storesallthegivencurrencyvalues.
updateCurrency(CurrencyWS CurrencyWS
currency)
createCurrency(CurrencyWS
currency)
CurrencyWS
Integer
Savesanewcurrencytypeandreturnsthe
newID.
getCompany()
CompanyWS
updateCompany(CompanyW
ScompanyWS)
CompanyWS
createUpdateNotification(Inte Mesage
ID
,
ger messageId, MessageDTO MessageDTO@
dto)
PluginAPIMethods
APIMethod
Arguments
Returns
Description
Copyright2013EnterprisejBillingSoftwareLtd
78
getPluginWS(IntegerpluginId) PluginID
PluggableTask
WS
createPlugin(PluggableTask
WSplugin)
PluggableTaskWS Integer
updatePlugin(PluggableTask
WSplugin)
PluggableTaskWS
deletePlugin(Integerplugin)
Integer
Deletesthegivenplugin
Returns
Description
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
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'
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='[email protected]',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='[email protected]',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='[email protected]',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
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