This guide details how to integrate Mobile Connect into your PHP-based server applications using the Mobile Connect SDK for PHP. It is strongly recommended that you read through this guide and familiarise yourself with the functions the SDK provides before downloading a demo app and starting to code.

The guide describes the processes for:

Prerequisites

Before you can make calls to Mobile Connect, you must have registered for a Mobile Connect user account and registered an application. This will provide you with your developer credentials, which you will need to specify in a configuration object, and your Application Short Name, which is a required parameter when calling the Authorisation or Identity endpoints.

Configuring your Project

  1. Download and install WampServer, which provides you with a PHP interpreter and Apache webserver.

    Note: you can use any web server in production; WampServer is recommended as the easiest way to get the demo application running.

  2. Download and install the CodeIgniter web framework. This framework is used both in the examples in this guide and in the demo application.

  3. Download the Mobile Connect SDK. From a command line, run the following:

    git clone https://github.com/Mobile-Connect/php_sdk_v2.git

    to get the code from Github.

  4. Install the SDK. From a command line, navigate into the directory mobile-connect-sdk and run the following:

    php composer.phar install

    This will install all of the necessary dependencies, allowing you to access the Mobile Connect SDK libraries from within your project. It also installs the demo application.

  5. Run unit tests to ensure that the SDK has been installed correctly. Navigate to the root of the SDK package and run the following:

    phpunit -c tests

    Following a successful test, you’re ready to access the SDK in your projects.

Back to top

Using the SDK with Mobile Connect

The Mobile Connect SDK for PHP automates much of the basic housekeeping and configuration tasks of your application’s integration with Mobile Connect. Many of these functions activate in the Discovery phase, independently of the Identity Gateway endpoint your application will ultimately call, and so are described here for your reference.

Provider Metadata

A successful call to the Mobile Connect Discovery endpoint returns the end user’s Mobile Network Operator (MNO) and describes the Mobile Connect services that MNO supports, via a URI to the MNO’s Provider Metadata. The metadata describes the Identity Gateway endpoints (Mobile Connect services) your application or service can use and how those endpoints are configured – for example, the response types an endpoint can return, the subject identifier types supported, or the Identity Services encryption algorithms in use.

Although Provider Metadata is the primary source of information detailing the Identity Gateway configuration, it does not change often, so a cached version can be used without risk of expired data causing errors. The Mobile Connect SDK handles both the querying of the Provider Metadata and the caching.

  • If the Provider Metadata URI returns no data, the cached metadata is used.
  • Where the cached data is out of date (defaulting to 15-minute intervals) a subsequent query of the URI is attempted, and in the event of a second failed response, expired cached data is used.
  • Should neither the cached data nor the Provider Metadata URI return data (such as an error upon first user login) default values are used.

Regardless of the source, the SDK parses the Provider Metadata into a discrete list of properties. See the OpenID Provider Metadata definition for a list of the metadata available, although you should note that Mobile Connect's implementation may not be exhaustive.

The providerMetadata object is available on discoveryResponse.providerMetadata.

Back to top

Supported Services

Before your application or service can call an Identity Gateway endpoint (scope), you need to know if the MNO supports the scope you are calling. The Mobile Connect SDK provides the method isMobileConnectServiceSupported($scope) in the discoveryReponse, which can be accessed as follows:

$supported = $discoveryResponse->IsMobileConnectServiceSupported(“mc_authz mc_identity_signup”)

The method accepts a comma- or space-separated list of scopes, which it then checks against the list of supported scopes in the Provider Metadata.

  • If all of the scopes passed as arguments are present in the Provider Metadata, the function returns true.
  • If any of the passed scopes are not present in the metadata, the function returns false.
  • If the Provider Metadata is not available, or the scopes attribute is missing, null, or an empty string, the function returns an exception: “Provider Metadata scopes unavailable”.

Back to top

Version Compatibility

Although the MNOs may support differing versions of the Mobile Connect APIs, the SDK automatically detects the version in use at an Identity Gateway from the Provider Metadata, and ensures that the correct Mobile Connect Profile is used when making calls to the Mobile Connect APIs.

Back to top

Mobile Connect Constants

The SDK provides a number of constants for referencing the Mobile Connect services by scope. They are available in the MCSDK\MobileConnectConstants class, and can be called using the following syntax:

MCSDK\MobileConnectConstants::MOBILECONNECTIDENTITYPHONE

The above example calls the scope "openid mc_identity_phonenumber". You can pass multiple scopes as a space-separated string; the SDK will remove any duplicates before making the call to the Identity Gateway.

The following constants are available:

Mobile Connect Product Constant Identifier Literal Value
Authentication (v1.0) MOBILECONNECT "openid"
Authentication (v1.1) MOBILECONNECTAUTHENTICATION "openid mc_authn"
Authorisation MOBILECONNECTAUTHORIZATION "openid mc_authz"
Identity: Phone Number MOBILECONNECTIDENTITYPHONE "openid mc_identity_phonenumber"
Identity: Signup MOBILECONNECTIDENTITYSIGNUP "openid mc_identity_signup"
Identity: Signup Plus* MOBILECONNECTR3IDENTITYSIGNUPPLUS "openid mc_identity_signupplus"
Identity: National ID MOBILECONNECTIDENTITYNATIONALID "openid mc_identity_nationalid"

*This constant is available to support possible future products.

Back to top

Login Hint Support

You have the option to provide the login hint to the Identity Gateway in one of three formats: MSISDN, encrypted MSISDN, and PCR. Your decision on how to provide the login hint is governed by two factors:

  • The login hint formats supported by the Identity Gateway.
  • Whether you are a “Trusted Service Provider”; an unencrypted MSISDN is only accepted from a trusted provider – attempting to send one if you are not trusted returns an error.

The Mobile Connect SDK provides functions to test for login hint support in the Identity Gateway, namely:

  • LoginHint::IsSupportedForMSISDN()
  • LoginHint::IsSupportedForEncryptedMSISDN()
  • LoginHint::IsSupportedForPCR()

Each function checks the login_hint_methods_supported attribute in the Provider Metadata returned from the Discovery endpoint. Should the attribute be missing, the function checks the Mobile Connect Profile version supported; only version 1.2 supports passing the PCR as the login hint.

Once you have decided how to provide the login hint, the SDK offers a further three functions to build it for you:

  • LoginHint::GenerateForMSISDN($MSISDN)
  • LoginHint::GenerateForEncryptedMSISDN($encryptedMSISDN)
  • LoginHint::GenerateForPCR ($PCR)

Back to top

id_token Validation

A successful response from the Identity Gateway includes an id_token – a JSON Web Token, which validates against a JSON Web Keyset (JWKS), available at a URL specified in the Provider Metadata attribute jwks_uri.

The SDK performs a number of automatic validation actions to ensure the integrity of the response source, such as checking whether the token has expired. It also fetches the data from the jwks_uri location and stores it alongside the associated Discovery response, where it is cached. The following functions are then available to you to support id_token validation:

  • checkIDTokenSignature(id_token, $keyset) verifies the signature of the id_token based on the jwks_uri data. A successful validation returns true; a failed validation returns false; a missing JWKS certificate returns an error.
  • JWKeysetService::RetrieveJWKS($url) allows you to fetch all of the keys from the JWKS data.
  • returnMatchingJWKSEntries allows you to fetch specific keys matching the following parameters:

    All keys match the following parameters:

    • kty – key type (e.g. RSA)
    • alg – algorithm (e.g. RS256)
    • use – sig (signature) or enc (encryption)
    • kid – key identifier

Back to top

Using Mobile Connect Authentication

The SDK allows you to call a method that accepts a reference to a configuration file as a parameter. With your developer credentials specified in the configuration file, you have everything you need to make a successful call to the Mobile Connect Discovery endpoint, and the functions AttemptDiscovery() and HandleUrlRedirect() do just that, building and making the call, and then handling the response. The SDK also takes care of caching the response for re-use in a subsequent call – subject to the configured timeout. Once the end user has entered their MSISDN or specified their operator, and a successful Discovery response is received, the SDK builds the call to the Authentication endpoint. A successful authentication returns an id_token containing the user’s PCR, which is unpacked and available for verification against your user register.

The following procedure details the steps for creating a server application capable of calling, and handling the responses from, the Mobile Connect Authentication service. The steps don’t describe how to construct the web pages that will be needed for a client to interact with the server application beyond describing the interfaces. In order to build and test the application described, create pages using your preferred scripting language to interact with the server application.

  1. Create a Mobile Connect controller.

    Note: if you operate in the EU then you should use EU Discovery Service domain: eu.discover.mobileconnect.io

    1. Add a new controller to CodeIgniter.
    2. In the file, add a controller definition.

         public function __construct() {
              parent::__construct();
      
              session_start();
              $cache = null;
              if (!isset($_SESSION['mc_session'])) {
                  $cache = new Cache();
                  $_SESSION['mc_session'] = $cache;
              } else {
                  $cache = $_SESSION['mc_session'];
              }
      
              $discoveryService = new DiscoveryService(new RestClient(), $cache);
              $authentication = new AuthenticationService();
              $identity = new IdentityService(new RestClient());
              $jwks = new JWKeysetService(new RestClient(), $discoveryService->getCache());
              $config = new MobileConnectConfig();
              $config->setClientId("");
              $config->setClientSecret("");
              $config->setDiscoveryUrl("");
              $config->setRedirectUrl("");
      
              $this->_mobileConnect = new MobileConnectWebInterface($discoveryService, $authentication, $identity, $jwks, $config);
          }
      
          

      MobileConnectStatus is a large object, which needs to be condensed into a smaller response that can be easily JSON serialised and returned to the client. This is the role of the ResponseConverter, which returns a MobileConnectWebResponse. Each response has the action property, which contains a key specifying what the client’s next action should be, from the following list: “discovery", "operator_selection", "start_authorization", "authorization", "complete", and "error". During the Mobile Connect process, the Mobile Connect endpoints may set cookies.

    3. Add a function StartDiscovery to call the Mobile Connect Discovery service.

            public function StartDiscovery($msisdn = "", $mcc = "", $mnc = "") {
              $msisdn = $this->input->get('msisdn', true);
              $mcc = $this->input->get('mcc', true);
              $mnc = $this->input->get('mnc', true);
      
              $response = $this->_mobileConnect->AttemptDiscovery($this->input, $msisdn, $mcc, $mnc, true, new MobileConnectRequestOptions());
              return $this->CreateResponse($response);
          }

      Note: MobileConnectRequestOptions() enables optional query parameters in the API.

    4. Add a handler to capture the parameters from redirected URLs containing the results of calls to both the Discovery and Identity Gateway endpoints. The client must forward the redirected URL’s parameters, as appropriate, using a GET action (see the code comments for the URL structure).

      public function HandleRedirect($sdkSession = null, $mcc_mnc = null, $code = null, $expectedState = null, $expectedNonce = null) {
              $sdkSession = $this->input->get('sdkSession', true);
              $expectedState = $this->input->get('expectedState', true);
              $expectedNonce = $this->input->get('expectedNonce', true);
              $requestUri = $this->input->server('REQUEST_URI');
      
      // This method is called when the client makes an HTTP GET request to the relative url /api/mobileconnect
      // Expected calls:
      // After Operator Selection: http://hostname.com/api/mobileconnect?mcc_mnc=101_01&subscriber_id=1cf21232hzakxzkjxakjw....
      // After Authentication: http://hostname.com/api/mobileconnect?code=12345676424567432&sdksession=a54asdasgdasx67&expectedState=state&expectedNonce=nonce (state and nonce from start_authentication response)
              $response = $this->_mobileConnect->HandleUrlRedirect($this->input, $requestUri, $sdkSession, $expectedState, $expectedNonce);
              return $this->CreateResponse($response);
      // The response to the client will depend on the input. The following will be responses to the above expected calls
      // After Operator Selection: { "status": "success", "action": "start_authorization", "sdkSession": "a54asdasgdasx67", "subscriberId": "2g131jh2312h...." } (sdkSession should be stored and passed into subsequent requests in the process)
      // After Authentication: { "status": "success", "action": "complete", "token": { token_data } }
          
      }
    5. Add a call to the Mobile Connect Authentication endpoint, including values for state and nonce.

      Note: GenerateSecureNonce() is a method of the Security helper class provided in the SDK.

      public function StartAuthentication($sdkSession = null, $subscriberId = null, $scope = null) {
              $sdkSession = $this->input->get('sdkSession', true);
              $subscriberId = $this->input->get('subscriberId', true);
              $scope = $this->input->get('scope', true);
      
      // This method is called when the client makes an HTTP GET request to the relative url api/mobileconnect/start_authentication
                  // Expected call: http://hostname.com/api/mobileconnect/start_authentication?sdksession=a54asdasgdasx67&subscriberId=1cf21232hzakxzkjxakjw....
      
              $state = Security::GenerateSecureNonce();
              $nonce = Security::GenerateSecureNonce();
      
              $options = new MobileConnectRequestOptions();
              $options->setScope($scope);
              $options->setContext("demo");
              $options->setBindingMessage("demo auth");
              $response = $this->_mobileConnect->StartAuthentication($this->input, $sdkSession, $subscriberId, $state, $nonce, $options);
      
              return $this->CreateResponse($response);
      // This returns JSON to the client similar to the following
                  // { "status": "success", "action": "authorization", "url": "http://authenticationurl.com/auth?param=x....", "state": "state", "nonce": "nonce" }
                  // The client should access the url and store the state and nonce returned for later use
          }

    Back to top

    Using Mobile Connect Authorisation

    The SDK allows you to call the Identity Gateway with the scope parameter set to “mc_authz”, which signifies an Authorisation request for a single transaction (the id_token and access token returned from the Gateway have a timeout set to zero, so expire after a single use). You should check that the Identity Gateway supports version 1.2 of the Mobile Connect Profile (available in the Provider Metadata) before attempting a call, but note that the SDK sets the version to “mc_v1.2” automatically.

    To make a successful authorisation call, you must provide the following additional parameters:

    • client_name – specifies the name of the application/service requesting authorisation. This must match the Application Short Name returned by the Discovery service. If no client_name is specified, the SDK will handle this for you.
    • context – specifies the reason for the authorisation request, and should be built from the data describing the transaction requiring authorisation. The context is displayed on the authenticating (mobile) device only.
    • binding_message – specifies a reference string to display on the device from which the authorisation request was invoked, and on the authenticating (mobile) device, allowing the user to visually verify that the confirmation message originated from their transaction request.

    Note: the authorisation prompt displayed to the user combines all three parameters, which cannot exceed 93 bytes in total.

    The following example shows how to add the additional options to the authentication call described in Using Mobile Connect Authentication, resulting in a correctly configured call to the authorisation service.

    $authOptions = new MobileConnectRequestOptions();
    $authOptions->setScope(MobileConnectConstants::MOBILECONNECTAUTHORIZATION);
    //context of the transaction
    $authOptions->setContext("trans 123");
    //unique user recognisable message
    $authOptions->setBindingMessage("jamaica clock");
    
    $nesponse = $this->_mobileConnect->StartAuthentication($discoveryResponse, $subscriberId, $state, $nonce, $authOptions); //same as Authentication example

    The level of authentication required to authorise the transaction defaults to LoA2 (Authorisation), but you can increase it by adding the optional parameter acr_value and setting the value to "3" (for Authorisation Plus).

    Back to top

    Using Mobile Connect Identity and Attributes

    A successful call to the Authorisation endpoint returns an id_token identifying the user, and an access token that grants your application permission to request their personal information (referred to as Claims). This information contains a range of data; the exact data you can request is specified in the access token, and is limited to those Claims the end user has permitted as part of the original authorisation request.

    Note: the access token is for single use only, and expires immediately upon use.

    You request access to the Identity endpoint by specifying the appropriate scope. The SDK provides constants that you can pass when requesting specific Identity products:

    • Identity: Phone Number – MOBILECONNECTIDENTITYPHONE
    • Identity: Sign-up – MOBILECONNECTIDENTITYSIGNUP
    • Identity: National Identity – MOBILECONNECTIDENTITYNATIONALID

    Upon successful authorisation, the SDK provides an IdentityResponse with the user information JSON available as a property. The following example can be used to convert the JSON data to a class - IdentityData - which is provided with all recognised claims.

          public function RequestIdentity($sdkSession = null, $accessToken = null) {
            $sdkSession = $this->input->get('sdkSession', true);
            $accessToken = $this->input->get('accessToken', true);
    // IdentityData is a JSON serializable class containing properties for all available Identity claims
    // It can be replaced by any JSON serializable type, either to add additional supported claims
    // or to provide a lightweight class with only the required claims
    
            $response = $this->_mobileConnect->RequestIdentity($this->input, $sdkSession, $accessToken, new MobileConnectRequestOptions());
            return $this->CreateResponse($response);
        }

    The following example shows how to add the additional Authorisation and Identity options to the Authentication call described in Using Mobile Connect Authentication, resulting in a correctly configured call to the Identity: Phone Number service.

    Note: calls to Identity: Sign-up and Identity: National ID are structured in exactly the same way, but using the constant MOBILECONNECTIDENTITYSIGNUP or MOBILECONNECTIDENTITYNATIONALID as applicable.

    $authOptions = new MobileConnectRequestOptions();
    $authOptions->setScope(MobileConnectConstants:: MOBILECONNECTIDENTITYPHONE);
    //context of the transaction
    $authOptions->setContext("trans 123");
    //unique user recognisable message
    $authOptions->setBindingMessage("jamaica clock");
    
    $nesponse = $this->_mobileConnect->StartAuthentication($discoveryResponse, $subscriberId, $state, $nonce, $authOptions); //same as Authentication example

    Back to top

    Using Mobile Connect Server-to-Server (Headless) Operation

    MNOs have the option to enable headless operation in their Identity Gateway. This server-to-server configuration allows your server-side applications/services to make calls to the Mobile Connect endpoints without any user interaction via a client application or browser. Headless operation supports implementations where the user’s MSISDN is provided by a third-party system – a call centre Interactive Voice Response (IVR) system, for example.

    The Mobile Connect SDK handles the configuration needed for headless operation. Following a successful Discovery response containing the URL to the MNO’s Identity Gateway, the SDK handles the call to the requested endpoint (Authentication, Authorization, or Identity) in the following ways:

    • The prompt parameter is set to “mobile”, ensuring that all user interactions are sent via the user’s mobile device.
    • The SDK waits for a response from the endpoint (in the form of a redirect to your registered redirect URL) following either a successful user authentication or an error. If the wait time exceeds the timeout interval (defaulting to two minutes, but you can set a different duration) then a timeout error is generated and returned to your application.
    • The SDK can cancel an in-progress request when instructed by your application/service.

    The following example enables headless operation in your server application.

    $options = new MobileConnectRequestOptions();
    $options->setScope($scope);
    $options->setContext("headless");
    $options->setBindingMessage("demo headless");
    $options->setAutoRetrieveIdentityHeadless(true);
    $response = $this->_mobileConnect->RequestHeadlessAuthentication($request, $sdksession, $subscriberId, null, null, $options);
    return $this->CreateResponse($response);

    Further Reference

    Back to top