How to Create Text Message Alerts for PayPal Payments using Twilio, PHP, and YII 2

April 18, 2019
Written by
Andre Piper
Contributor
Opinions expressed by Twilio contributors are their own

How to Add Text Message Alerts for PayPal Payments using Twilio, PHP, and YII 2.png

I was recently completing a payments integration for a recruiting firm that wanted to quickly deploy text message alerts for when buyers complete a PayPal payment flow. The business wanted the ability to instantly text payment info to the payee’s cell number. This tutorial is an introduction to integrating Twilio SDK into a Yii2 web application.

Preview of Text Alert

Technical Requirements

For this tutorial we’ll assume the following:

YII2 framework is defined as a high performance, component-based PHP framework for rapidly developing modern web applications. Personally, I love that it allows me to just focus on code instead of design patterns. I can scaffold views, data models and other trivial tasks that would normally take a great deal of time.

Cloning the sample project

The first thing we will need is a working installation of git. Open your favorite console/terminal and navigate to your local web server instance. My version is XAMPP so my server is located at ~/xamp/htdocs. Run the following commands below.

$ git clone https://github.com/andrepiper/twilio_yii2_tutorial.git

Installing dependencies

Navigate to the folder twilio_yii2_tutorial and open a new terminal window if you haven’t closed the previous one used for cloning the repository. We will need Composer installed at this point. If you haven't, you can follow this documentation.

$ composer install

Grab a cup of coffee if your Internet is slow and let it install.

cup of coffee

At last! The screenshot of the successful installation of project dependencies.

screenshot of successful install

Assuming that you, cloned the project in your local PHP web server, navigate to the URL below http://localhost/twilio_yii2_tutorial/web/

The index page should load a demo product page that shows a single product and price, along with a submit button. See screenshot below.

demo of sample yii2 checkout page

At this point you have a working YII2 web application with the Twilio and PayPal SDK installed. 

Wrapping Twilio and PayPal SDKs for usage in application

Open your favorite note editor and navigate to the common folder of the application hierarchy. See screenshot below. I am using Sublime editor.

screenshot of sublime ide with yii2 app

The following PHP files AppResponse.php and AppServices.php are classes used to conduct payments and SMS disbursement.

  • AppResponse.php is a response class that holds $success, $payload and $message properties for when we get a response from PayPal and Twilio servers.
  • AppServices.phpcontains the methods that actually conduct the payment and sending of text messages. Such methods include :
    • function generatePaymentUrl(params, callbackUrl), accepts a callback URLan array of product info, ex. price, description and other relevant product information. It also returns an AppResponse object with payload property being a redirect url to the PayPal payment gateway for the user to login and complete purchase. After payment is complete, a callback is made to a designated URL and then the method makePayment($payload) is executed.
    • function makePayment($payload) accepts the redirect query string data and conducts the final step in the payment chain. Returns payment payload from PayPal SDK.
    • function sendAlert(from, to, message) accepts a Twilio verified phone number for the $from parameter, destination number and $message body. Returns a true or false for message sending procedure.

Retrieving PayPal Client ID and Secret

A requirement of this tutorial is a PayPal restful application on the developer portal. Please follow this documentation if you haven’t done so already. Store this value in a text file for now until we ready for it.

screenshot of PayPal app dashboard
screenshot of Twilio account dashboard

After creating a Twilio account you are given a SID and Token for your account on the dashboard page. Store this value in a text file for now until we ready for it.

Configuring Twilio managed and verified numbers

Purchase a Twilio managed phone number with SMS capabilities. If you haven’t done so, please see this complete tutorial on how to purchase one.

Twilio number dashboard

Navigate here https://www.twilio.com/console/phone-numbers/verified and enter a phone number that you want to test as a recipient.

Twilio verified numbers

Updating parameters file in application route

Open the params.php file in the config folder of the tutorial folder currently running on localhost. Open your text editor/IDE and enter the Twilio and PayPal credentials previously retrieved. See code snippet below.

Sublime yii2 app parameters
<?php 
return [
    'adminEmail' => '',
    'paypalKey' => '',
    'paypalSecret' => '',
    'twilioSID' => '',
    'twilioToken' => '',
    'twilioFromNumber' => '',
    'twilioToNumber' => '',
];

The preceding array will be used to store Twilio and PayPal credentials used by the application. See key value explanation below :

  • adminEmail : Enter your email or a test email it doesn't matter
  • paypalKey : Enter the PayPal client id
  • paypalSecret : Enter the PayPal secret
  • twilioSID : Enter the Twilio SID
  • twilioToken : Enter the Twilio Token
  • twilioFromNumber : Enter the verified number bought from Twilio
  • twilioToNumber : Enter the verified caller id you want to send test SMS.

Dissecting method actionIndex() of SiteController class

If you are knowledgeable of MVC, the controller accepts input and converts it to commands for the model or view, thus this where we handle the actual payment after you press the submit button. The indexAction() method holds all the code we will need to conduct payment and SMS disbursement. So let’s dissect this method.

actionIndex() HTTP Request Methods [GET,POST]

[GET] /index - loads the demo screen showing product.

[POST] /index - This essentially generates the redirect URL to allow for PayPal user authentication and allow the user to select their preferred method of payment.

$paypalKey = \Yii::$app->params['paypalKey'];
            $paypalSecret = \Yii::$app->params['paypalSecret'];
            $twilioSID = \Yii::$app->params['twilioSID'];
            $twilioToken = \Yii::$app->params['twilioToken'];
            $from = \Yii::$app->params['twilioFromNumber'];
            $to = \Yii::$app->params['twilioToNumber'];

            $services = new AppServices($paypalKey,$paypalSecret,$twilioSID,$twilioToken);

            $paypalPayment = [
                'method'=>'paypal',
                'intent'=>'sale',
                'order'=>[
                    'description'=>'Payment description',
                    'subtotal'=>150,
                    'shippingCost'=>0,
                    'total'=>150,
                    'currency'=>'USD',
                    'items'=>[
                        [
                            'name'=>'Super Awesome Product',
                            'price'=>150,
                            'quantity'=>1,
                            'currency'=>'USD'
                        ]
                    ]

                ]
            ];
            $callbackUrl = "site/payment";
            $response = $services->generatePaymentUrl($paypalPayment, $callbackUrl);
            if($response->getSuccess())
            {
                return $this->redirect($response->getPayload()->getHeaders()->get("location"));
            }

actionPayment() HTTP Request Methods [GET,POST]

[GET] /payment  - Without params loads the index page

[GET] /payment  - This is the callback URL specified in the post request code, PayPal passes query string params :

  • Success - bool
  • PaymentId - unique payment id from PayPal/receipt id
  • Token - id passed from PayPal to invoke the makePayment method found in the AppServices class
  • PayerID -  payer id defined in dashboard

On payment processed, an SMS is sent to the test destination number specified in config/params.php file.

$paypalKey = \Yii::$app->params['paypalKey'];
            $paypalSecret = \Yii::$app->params['paypalSecret'];
            $twilioSID = \Yii::$app->params['twilioSID'];
            $twilioToken = \Yii::$app->params['twilioToken'];
            $from = \Yii::$app->params['twilioFromNumber'];
            $to = \Yii::$app->params['twilioToNumber'];

            $services = new AppServices($paypalKey,$paypalSecret,$twilioSID,$twilioToken);

            $paymentId = Yii::$app->request->get('paymentId');
            $token = Yii::$app->request->get('token');
            $payerId = Yii::$app->request->get('PayerID');

            $payload = [
                'paymentId'=>$paymentId,
                'success'=>$success,
                'token'=>$token,
                'payerId'=>$payerId,
                'order'=>[
                    'description'=>'Payment description',
                    'subtotal'=>150,
                    'shippingCost'=>0,
                    'total'=>150,
                    'currency'=>'USD',
                    'items'=>[
                        [
                            'name'=>'Super Awesome Product',
                            'price'=>150,
                            'quantity'=>1,
                            'currency'=>'USD'
                        ]
                    ]

                ]
            ];

            $response = $services->makePayment($payload);
            if($response->getSuccess())
            {
                $smsPayload = $services->sendAlert($from, $to, "PayPal order completed. Receipt #: ".$response->getPayload()->getId()." Total $:".$payload['order']['total'].' USD');
                return $this->render('payment',['payload'=>$response, 'sms'=>$smsPayload]);
            }

Conducting a payment Payment

Pressing the submit button triggers the payment flow. This action loads the PayPal hosted gateway that allows users to authenticate and pay for the item/items.

PayPal sandbox checkout
Payment confirmation from PayPal

The test recipient number that was specified in the params.php file should get a message about the payment being made. See screenshot below.

Displaying of a successful payment alert on the recipient cell phone

Conclusion

The example we have implemented above is just us getting our feet wet. There is a lot we can implement using Twilio SMS services. For example, we can implement a cancel payment via SMS where the account holder sends a cancel message using receipt id. Ex. cancel PAY-LRJIGSA56R7336023335545J and we kick off a cancel flow in the backend and execute PayPal restful endpoints to issue a refund.

Written By:

Name: Andre Piper

Twitter: twitter.com/andrepiper89
Email: andrepiper@gmail.com
Github: github.com/andrepiper