Cold Fusion MX Creating Web Service

  • Upload
    play05

  • View
    227

  • Download
    0

Embed Size (px)

Citation preview

  • 8/14/2019 Cold Fusion MX Creating Web Service

    1/15

    Creating a Web S ervice in ColdFusion M X

    by Stacy Young

    Apri l 20 0 2

  • 8/14/2019 Cold Fusion MX Creating Web Service

    2/15

    Copyright 200 2 M acromedia, Inc. All rights reserved.

    The information contained in this document represents the current view of Macromedia on the issue discussed as of the date of publication. BecauseMacromedia must respond to changing market conditions, it should not be interpreted to be a commitment on the part of M acromedia, and Macromediacannot guarantee the accuracy of any information presented after the date of publication.

    This white paper is for information purposes only. MACROMED IA MAK ES N O W ARRANTIES, EXPRESS OR IMPL IED, IN TH IS DOCUM ENT.

    Macromedia may have patents, patent applications, trademark, copyright or other intellectual property rights covering the subject matter of this document.Except as expressly provided in any written license agreement from Macromed ia, the furnishing of this document d oes not g ive you any license to thesepatents, trademarks, copyrights or o ther intellectual property.

    The Macromedia logo, Flash, ColdFusion, and M acromedia Flash are either trademarks or registered trademarks of M acromedia, Inc. in the United Statesand/or o ther countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.

    Macromedia, Inc.60 0 Townsend StreetSan Francisco, CA 94 103415252 20 00

  • 8/14/2019 Cold Fusion MX Creating Web Service

    3/15

    Creating a Web Service in ColdFusion MX

    Contents

    The Next B ig Th ing ............................................................................................................ 1B uildin g the B ack End ...................................................................................................... 2 Dissec tin g the Com po nen t ............................................................................................... 3 ColdFusion Com po nen t B row ser ..................................................................................... 4 Creating a W SDL Fi le....................................................................................................... 5 Pu bli shin g a W eb Serv ice ................................................................................................ 6 Const ruc tin g a Client ........................................................................................................ 8 About the Author .............................................................................................................10

    April 2002 Page iii

  • 8/14/2019 Cold Fusion MX Creating Web Service

    4/15

  • 8/14/2019 Cold Fusion MX Creating Web Service

    5/15

    Creating a Web Service in ColdFusion MXThe Next Big Thing

    Maybe youve heard that web services will revolutionize the wayyou do business and develop applications on the web. Youveheard theyll simplify corporate infrastructures and unitebusiness partners all over the world and even make your coffee

    in the morning. Web services promise a lot, but is it fact orfiction?

    The Next B ig ThingAs a developer, Im constantly presented with the supposed next big thing.After enough disappointments, I stopped paying attention. When I first heard of

    web services I thought they were no exception. That was well over a year ago.Since that time, the momentum has only gotten stronger. This prompted me to

    stop and take a closer look. Happily, the release of Macromedia ColdFusion MXmeans getting your hands dirty with web services couldnt be easier.

    As a developer at SureFire Commerce, I put together a simple example of how toprocess payments though a web service. The web service comes from SureFireCommerce, which enables any business to process electronic payments, such ascharging a customers credit card, e-mailing an invoice that can be paid online,or depositing money into the bank account of a supplier or employee. Included

    with its payment processing applications, SureFire offers merchant accounts,risk management, financial reconciliation and online reporting.

    At SureFire, one of the biggest issues that I encounter as a developer iscustomer integration. As a payment processor serving customers who have

    specific and individual needs, it is cost-prohibitive for me to develop customizedsolutions for every platform, not to mention having to re-deploy all thosesolutions every time I want to make an enhancement. Additionally, traditionalInternet communication using HTTP POST/GET is not fully compatible whenimplementing more complex service offerings. If youve ever had to use CFHTTPto parse data from another web page, this problem is clear to you.

    Enter web services, a communication platform for applications. By using acombination of standardized protocols, it allows applications to communicate

    with each other regardless of their platform or programming language. Byoffering payment processing as a web service, I only need to define a singlestandard interface for everyone.

    In this article, Ill explain how to create a web service using ColdFusion MX.Then Ill explore how you can invoke the new service over the Internet to processa credit card transaction.

    April 2002 Page 1

  • 8/14/2019 Cold Fusion MX Creating Web Service

    6/15

    Creating a Web Service in ColdFusion MXBuilding the Back End

    B uild ing the B ack EndThe first thing you need to do is learn how to construct a credit cardauthorization service and encapsulate that in a ColdFusion Component (CFC).

    Typically, a credit card transaction requires certain parameters to be processed,such as customer information, card number and expiration date. This CFCverifies that the correct parameters were supplied, queries your database for theavailable credit for the card requested and compares the requested authorizationamount and the available credit. Lastly, it decides whether to authorize ordecline the transaction, and returns the appropriate response.

    The following is an example ColdFusion Component that performs a basic creditcard authorization:

    Page 2 April 2002

  • 8/14/2019 Cold Fusion MX Creating Web Service

    7/15

    Creating a Web Service in ColdFusion MXDissecting the Component

    Dissecting the Com ponentThe cfcomponent tag is a wrapper that defines the functions within it. Typically acomponent packages a set of related functions or methods. For instance, a

    component dedicated to user management would likely contain functions thatcould perform the following:

    add a user

    update a user

    delete a user

    list users

    You define each method with the cffunction tag. This article focuses on theauthorize function, or method. The code for the authorize function is asfollows:

    To create a function that is a web service, specify the access value as remote.This determines the level of exposure for the function. Specifying

    access=remote means that you can access the function from abroad, whereas

    access=private means that you can only access the function from within thecomponent.

    Next, consider what type of response youll send back to the calling application(such as string, numeric value, structure, array, query object and so forth). Thereturntype attribute specifies the data type of the response, in this case, youll

    return a CFMLstructure (also called a struct). If youre unsure of the data type,perhaps due to conditional logic within your function, you can always specify a

    returntype of any and ColdFusion will adjust accordingly. However, formaximum compatibility with other web service clients, specifying a data type forthe returntype attribute ensures a safer transaction.

    Use the cfargument tag to specify the required parameters for the function. Thedefault attribute is optional, while the type and required attributes are

    mandatory.

    To reference the arguments within your function, access them through thearguments scope (for example, #arguments.myVariable#):

    SELECT availableCredit

    FROM credit_cardsWHERE cardnumber = #arguments.cardnumber#

    Our database query expects the cardnumber argument and returns a single field

    called availableCredit. (To keep the code simple, this example includes the

    database query with the cfinclude tag rather than putting all of the code in theCFC.)

    April 2002 Page 3

  • 8/14/2019 Cold Fusion MX Creating Web Service

    8/15

    Creating a Web Service in ColdFusion MXColdFusion Component Browser

    Compare the amount of the purchase to the available credit and determine thetransaction status: AUTHORIZED or DECLINED.

    Next, insert a record of the transaction into your database. If the status isAUTHORIZED, make an adjustment on the available credit for the requestingcardholder to indicate that the funds have been spent. In either case, thedatabase insert returns a reference number to pass back to the callingapplication for reconciliation:

    Specifying a returntype of struct enables you to return the response structureback to the calling application that carries all pertinent information. Here, use

    the cfreturn tag to return the entire structure response back to the callingapplication.

    ColdFusion Com ponent B row serUpon typing the URL for your component, ColdFusion MX forwards you to abuilt-in server utility called the ColdFusion Component Browser, which auto-documents your components and benefits development teams.

    Figure 1 shows the documentation for the authorizecomponent built above.

    Page 4 April 2002

  • 8/14/2019 Cold Fusion MX Creating Web Service

    9/15

    Creating a Web Service in ColdFusion MXCreating a WSDL File

    ColdFusion Component Browserigur e 1:

    Creat ing a W SD L Fi leWhen publishing a web service, make a description of it available to potentialclients. This description enables your clients to interact with your web serviceand informs them of required arguments and data types they must pass to the

    web service. This description is called Web Services Description Language, orWSDL.

    Once you save the component in your webroot, you can view the WSDL file

    (which ColdFusion creates for you) by appending ?WSDL to the end of your

    component URL, as in the following example:

    http://www.mydomain.com/mycomponent.cfc?WSDL

    Browsing the URL above would produce the WSDL file shown in Figure 2.

    April 2002 Page 5

  • 8/14/2019 Cold Fusion MX Creating Web Service

    10/15

    Creating a Web Service in ColdFusion MXPublishing a Web Service

    Produced WSDL fileigure 2 :

    Publishing a W eb ServiceTo publish a web service with ColdFusion, make an entry in the Web Servicescontrol panel in the ColdFusion administrator (see Figure 3).

    Page 6 April 2002

  • 8/14/2019 Cold Fusion MX Creating Web Service

    11/15

    Creating a Web Service in ColdFusion MXPublishing a Web Service

    ColdFusion Web Services entry formigure 3 :

    Enter a name and the URL of your web service (see Figure 4). Then click AddWeb Service to activate it.

    Your entered web service in the ColdFusion administrator.igure 4 :

    April 2002 Page 7

  • 8/14/2019 Cold Fusion MX Creating Web Service

    12/15

    Creating a Web Service in ColdFusion MXConstructing a Client

    Construct ing a ClientNow that you have a working web service, you need to learn what to develop forthe client side. An e-commerce website typically has a checkout page where the

    consumer enters his or her payment information. The customer submits thepayment form and the form action sends the request to the payment processingservice for authorization.

    Heres an HTML form where your customer would enter payment information(step1.cfm):

    Joe's Credit Card Processing

    Name

    Address

    Zip

    State

    Country

    Card Type

    VisaMastercard

    Cardnumber

    Expiry

    Amount

    Page 8 April 2002

  • 8/14/2019 Cold Fusion MX Creating Web Service

    13/15

    Creating a Web Service in ColdFusion MXConstructing a Client

    This code displays the screen shown in Figure 5 (without the information

    entered).

    HTML entry form displayed in a browserigure 5 :

    Next, step2.cfm receives the POST from the HTML form, step1.cfm, andintroduces two new tags: cfinvoke and cfinvokeargument:

    The cfdump tag displays the structures data after the service has successfully

    processed the request (see Figure 6).

    April 2002 Page 9

  • 8/14/2019 Cold Fusion MX Creating Web Service

    14/15

    Creating a Web Service in ColdFusion MXAbout the Author

    Data displayed in a structure from the cfdump tag.igure 6 :

    Web services really work. Using the new features in ColdFusion MX to create astandardized web service for our payment processing engine enables us atSureFire to drastically reduce the time and effort required in making ourservices available to customers. First, our customers benefit from SureFiresoffering of standard protocols (converting our payment processing API to a webservice). Second, Macromedia ColdFusion MX enables both us and ourcustomers to connect to web services more easily by offering standard protocolsto connect to SureFires web service. In short, the customer benefits fromshorter development times and lower support costs.

    About the Author

    Page 10 April 2002

  • 8/14/2019 Cold Fusion MX Creating Web Service

    15/15

    Creating a Web Service in ColdFusion MXAbout the Author

    Stacy Young is a web guru and technology evangelist at SureFire Commerce,located in Montreal, Canada. (www.surefirecommerce.com). With over sevenyears of experience in the IT world, Stacy has served time as a systemsadministrator, HTML junkie, Macromedia Flash enthusiast, ColdFusion fanatic,

    usability freak, bread maker, and aspiring author. He plays an active role in theFuseBox community (www.fusebox.org) and spends most of his free timereplacing what his dog chews while hes at work. You can e-mail him directly [email protected] .

    April 2002 Page 11

    http://www.surefirecommerce.com/http://www.fusebox.org/mailto:[email protected]:[email protected]://www.fusebox.org/http://www.surefirecommerce.com/