How To Implement WorldPay Payment Using PHP SDK

In this tutorial I will show you all you need to implement Worlday payment using php from scrath. Worldpay documentation is very well done but here I will guide you step by step in the implementation. First of all you need an approved account because we will need an api key which will be used to send payment requests to Worldpay. 

Now, to start the implementation we need to download all required scripts so you need to go on their github and download the PHP sdk library. It can be installed with composer too, they have all available intalation methods on their git, don't forget to add their javscript scripts in your page, because first validation will be made by javascript.

 

Create Worldpay Payment Form HTML

We will need a form where the customer will add his payment details, like card number ccv month and year date. So, our form will look something like that:

<form id="payment" class="show_item card" style="display:block;" action="your backend url" method="POST">
    <div id="paymentErrors" class="payment-errors"></div>
    <div class="row">
        <div class="left">
            <div class="item">
                <label>Name on card</label>
                <input type="text" name="name" data-worldpay="name">
            </div>
            <div class="item">
                <label>Card Number</label>
                <input type="text" name="number" data-worldpay="number" size="20">
            </div>
            <div class="item">
                <div class="row">
                    <div class="item threeItem">
                        <label>Expiry Month</label>
                        <input type="text" name="exp-month" data-worldpay="exp-month">
                    </div>
                    <div class="item threeItem">
                        <label>Expiry Year</label>
                        <input type="text" name="exp-year" data-worldpay="exp-year">
                    </div>
                    <div class="item threeItem">
                        <label>CVV/CVC</label>
                        <input type="text" name="cvc" data-worldpay="cvc" size="4">
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>

Now we have the form where the customer will fill the fields with his details, this is a basic form because you will need to add address fields too and send them in backend to the controller, but for tests purpose it is enough to have these fields.

 

Create validation for Worldpay form

To create the validation we will need to use some javascript, to let Worldpay check the details inserted by the client in our form, if a field is complete incorectly and error will come up from worldpay scripts. The javascript code will look like the following:

Worldpay.setClientKey(your api key here); 
    var form = $('#payment')[0]; 
    var _triggerWorldpayUseForm = function() {
        Worldpay.useForm(form, function (status, response) {
            if (response.error) {
                Worldpay.handleError(form, jQuery('#paymentErrors')[0], response.error);
            } else if (status != 200) {
                Worldpay.handleError(form, jQuery('#paymentErrors')[0], response);
            } else {
                var token = response.token;
                Worldpay.formBuilder(form, 'input', 'hidden', 'token', token);
                form.submit();
            }
        });
    };
    _triggerWorldpayUseForm();

If there is no input error in the form the script will trigger submit event on our form and all data will be send to the controller where we have the rest of the implementation. Don't forget to update your api key in the first line of this js function.

 

Implement Worldpay server side 

public function makeCardPayment($address, $fields, $address_id){
    $worldpay = new Worldpay('your api key');
    $billing_address = array(
        "address1"=>$address->address1,
        "address2"=> $address->address2,
        "address3"=> '',
        "postalCode"=> $address->postcode,
        "city"=> $address->city,
        "state"=> '',
        "countryCode"=> 'US',
    );
    $delivery_address = array(
          "firstName" => $firstname,
          "lastName" => $lastname,
          "address1"=> $address->address1,
          "postalCode"=> $address->postcode,
          "city"=> $address->city,
          "state"=> '',
          "countryCode"=> '',
          "telephoneNumber"=> $address->phone
      );
    $obj = array(
      'token' => $fields['token'],
            'orderDescription' => 'description',
            'amount' => 200,
            'is3DSOrder' => false,
            'environment' => 'test',
            'authorizeOnly' => false,
            'orderType' => 'ECOM',
            'currencyCode' => 'EUR',
            'name' => 'John Doe', // Customer name
            'shopperEmailAddress' => 'test@test.com', // Shopper email address
            'billingAddress' => $billing_address, // Billing address array
            'deliveryAddress' => $delivery_address, // Delivery address array// Custom indentifiers
            'customerOrderCode' => $fields['id_project'], // Order code of your choice
        	'successUrl' => 'success url', //Success redirect url for APM
        	'redirectURL' => 'redirect url', //Success redirect url for APM
            'pendingUrl' => 'pending url', //Pending redirect url for APM
            'failureUrl' => 'failure url', //Failure redirect url for APM
            'cancelUrl' =>  'cancel url'//Cancel redirect url for APM
    );
    
    $obj['directOrder'] = true;
        $obj['shopperLanguageCode'] = 'EN';
        $obj['paymentMethod'] = array(
              "name" => $fields['name'],
              "expiryMonth" => $fields['exp-month'],
              "expiryYear" => $fields['exp-year'],
              "cardNumber"=> $fields['number'],
              "cvc"=> $fields['cvc']
        );
    
    $response = $worldpay->createOrder($obj);
    if($response['paymentStatus'] == 'SUCCESS'){
      'do something'
    }
  }

The above function is all we need to create a payment using Worldpay, as you can see we need to add some address fields to the order object, here depends how your implementation is, if you have accounts you can get the address from customer account, or you can add extra fields to the payment form. Everything is pretty simple, the last part of the function is the spot where we add card details to the order object and then just send the message to Worldpay. If the paymentStatus is success that's mean the payment was processed and eveything worked well. Let me know if you any help and I will try to help you with the implementation. This is the way you can implement Worldpay using php sdk.

3 2 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x