This example demonstrates how to integrate server side SDK.

Configuring and running the server side SDK

  1. Register an account or login to the Mobile Connect Developer Portal and create an application to obtain your sandbox credentials.
  2. Download the Mobile Connect server side project.

    git clone
  3. Copy php-server-side-library and mobile-connect-library folders into \xampp\htdocs.
    And then run next commands from both folder (php-server-side-library and mobile-connect-library):
    install npm
    composer install
  4. Before application running you need to create 3 tables in database: discovery, nonce, discovery_cache. Discovery and nonce values will be written into these tables. The structure these tables:
    Discovery: Table for temporary DiscoveryResponse storage, Discovery Response written to database after successful Discovery request and deleted after receiving any auth response (both success and error)
    id varchar(64)
    value varchar(4096)
    Nonce fields: Table for temporary nonce storage, nonce written to database after auth request generation and deleted after receiving any token requeset response (both success and error)
    id varchar(64)
    value varchar(64)
    discovery_cache fields: Table implements discovery caching feature
    msisdn varchar(64)
    mcc varchar(4)
    mnc varchar(4)
  5. Open the configuration file: \php-server-side-library\app\data\data.json.
  6. Note: if you operate in the EU then you should use EU Discovery Service domain in discovery url:

    Here are 10 parameters:

      “msisdn”: your msisdn
      "clientID": your client Id,
      "clientSecret": your client Secret,
      "discoveryURL": your Discovery endpoint,
      "redirectURL": "http://your redirect url",
      "xRedirect": "True",
      "includeRequestIP": "False",
      "apiVersion": api version: "mc_v1.1" or "mc_v1.2",
      "scopes": scopes,
      "clientName":  your client name
  7. Move to the root of the project and call.
     php artisan key:generate
  8. Open the configuration file .env at the root of the project
    Set correct values for variables DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME and DB_PASSWORD
  9. You can configure your application (clientID, clientSecret, discoveryURL, redirectURL). You can also configure your parameters for auth request (xRedirect, . includeRequestIP, apiVersion, scope, acrValues).
  10. Download and install any missing dependencies.
  11. Build the project.
  12. Run the MobileConnect demo.
  13. Prepare client side application (IOS or Android application) or Demo App for Server Side application.

Using the server side application

The server side 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.


Discovery is the process of determining an end-user's Mobile Connect Identity Provider, i.e. the Operator ID Gateway. The discovery response will provide with a number of endpoints and the operator specific credentials which will need to use with this ID Gateway.
The server side SDK has a method that accepts user's data as parameters and needs MobileConnectConfig object initialized as part of the MobileConnectWebInterface object - that's enough to make a successful call to the Mobile Connect Discovery endpoint, and the methods AttemptDiscovery, AttemptDiscoveryAfterOperatorSelection, and HandleUrlRedirect do just that, building and making the call, and then handling the response. The server side library also takes care of caching the response for re-use in a subsequent call – subject to the configured timeout.

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 server side library 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 server side library 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.

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”


Version Compatibility

Although the MNOs may support differing versions of the Mobile Connect APIs, the server side 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.

Application Short Name

The application you register with the Mobile Connect Developer Portal includes an Application Short Name, which is stored in the API Exchange and returned in responses from the Discovery service. The server side SDK captures the returned applicationShortName and includes it when constructing calls to the Mobile Connect Authorisation and Identity endpoints.

Mobile Connect Constants

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


The above example calls the scope "openid mc_identity_phonenumber". You can pass multiple scopes as a space-separated string; the server side library 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* MOBILECONNECTIDENTITYSIGNUPPLUS "openid mc_identity_signupplus"
Identity: National ID MOBILECONNECTIDENTITYNATIONALID "openid mc_identity_nationalid"

*This constant is available to support possible future products.

Login Hint Support

You have the option to provide the login hint to the Identity Gateway using 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 server side 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 server side Library offers a further three functions to build it for you:

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

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 server side 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 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:

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

Using Mobile Connect Authentication

The server side 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 methods AttemptDiscovery and HandleUrlRedirect do just that, building and making the call, and then handling the response. The server side library 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 server side library 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.

Server side application

With your configuration specified in the configuration file you have everything you need to make a successful call to the server side application.p/>

Client side application allows to sends a request to server side application in three modes: msisdn, mcc_mnc, none

Example request:
If you are using only msisdn the request to your server side part will be: http://localhost:8080/server_side_api/start_discovery?msisdn=447700900907
When you are using mcc and mnc it will be: http://localhost:8080/server_side_api/start_discovery?mcc=907&mnc=07
If you choose None mode: http://localhost:8080/server_side_api/start_discovery
Also sourceIp can be included to request: http://localhost:8080/server_side_api/start_discovery?sourceIp=

Client side application sends a GET request with client data to server side application.
Then server side application makes StartDiscovery method call with your data from configuration file. This method calls AttemptDiscoveryWrapper method with your parameters from config file. And then StartAuthentication method perfoms for getting authentication URL.

        public function StartDiscovery(Request $request) {
        $msisdn = Input::get("msisdn");
        $mcc = Input::get("mcc");
        $mnc = Input::get("mnc");
        $sourceIp = $request->header("X-Source-IP");
        return $this->AttemptDiscoveryWrapper($request, $msisdn, $mcc, $mnc, $sourceIp);

Note:If discovery request with msisdn, mcc_mnc or source ip fails - method perform Discovery UI flow to discover operator.

1) If you selected the msisdn mode: method generates auth URL and respond with 302 redirect to this URL. After you follow the redirect, and pass consent confirmation screen, redirect will be proceed by server side HandleRedirect method.
2) mcc_mnc mode.
3) none mode.
If you selected the mcc_mnc mode or none mode:
you will be redirected to the operator selection page. Here you can type your msisdn and process page. Then the scenario should be the same as on first mode.


[public static function HandleUrlRedirect(DiscoveryService $discovery, $jwks, $redirectedUrl, $expectedState, $expectedNonce, MobileConnectConfig $config,
        AuthenticationService $authentication = null, DiscoveryResponse $discoveryResponse = null,
        MobileConnectRequestOptions $options = null) {

        $query = parse_url($redirectedUrl, PHP_URL_QUERY);
        parse_str($query, $queryValue);
        if (isset($queryValue['code'])) {
            return static::RequestToken($authentication, $jwks, $discoveryResponse, $redirectedUrl, $expectedState, $expectedNonce, $config, $options);
        } else if(isset($queryValue['mcc_mnc'])) {
            return static::AttemptDiscoveryAfterOperatorSelection($discovery, $redirectedUrl, $config);
        $errorCode = "invalid_request";
        if (isset($queryValue['error'])) {
            $errorCode = $queryValue['error'];
        $errorDesc = "Unable to parse next step using " . $redirectedUrl;
        if (isset($queryValue['error_description'])) {
            $errorDesc = $queryValue['error_description'];
        else {
            if (isset($queryValue['description'])) {
                $errorDesc = $queryValue['description'];
        return MobileConnectStatus::Error($errorCode, $errorDesc, null);

Discovery caching

Discovery response is cached in server side library with following rules:
1) After succeed Discovery request, Discovery response is cached with used mcc/mnc, msisdn or sourceIp.
2) Expiration time for Discovery Response cache is the same as "ttl" field in Discovery Response - if Discovery Response expired - that deleted from cache.
3) Next requests for Discovery with the same mcc/mnc, msisdn or sourceIp - Discovery request shouldn't be performed, Discovery response should be taken from cache.
4) If auth call respond with error - Discovery Response deleted from cache, and server side library redirect you to Discovery UI.

Using Mobile Connect Authorisation

The server side 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 server side library 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 value is taken from Options and must match the Application Short Name.
  • 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();
//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

StartAuthentication method generates URL for authorisation, which is sent to client side application.

public function StartAuthentication($sdkSession = null, $subscriberId = null, $scope = null, $clientName = null) {
    if(Controller::$_apiVersion != 'mc_v1.1') {
        $options = new MobileConnectRequestOptions();
        $options->setBindingMessage("demo auth");
        $response = Controller::$_mobileConnect->StartAuthentication($sdkSession, $subscriberId, null, null, $options);
        return $response;
        $options = new MobileConnectRequestOptions();
        $response = Controller::$_mobileConnect->StartAuthentication($sdkSession, $subscriberId, null, null, $options);
        return $response;

After that client side makes redirects session and gets the code. Client side sends this code to server side, which uses this code for RequestToken method performing
public static function RequestToken(IAuthenticationService $authentication, IJWKeysetService $jwks, DiscoveryResponse $discoveryResponse,
        $redirectedUrl, $expectedState, $expectedNonce, MobileConnectConfig $config, MobileConnectRequestOptions $options = null) {
        $response = null;
        $query = parse_url($redirectedUrl, PHP_URL_QUERY);
        parse_str($query, $queryValue);

        if(empty($expectedState)) {
            return MobileConnectStatus::Error("required_arg_missing", "ExpectedState argument was not supplied, this is needed to prevent Cross-Site Request Forgery", null);
        if (empty($expectedNonce)) {
            return MobileConnectStatus::Error("required_arg_missing", "expectedNonce argument was not supplied, this is needed to prevent Replay Attacks", null);
        $actualState = $queryValue['state'];
        if ($expectedState != $actualState) {
            return MobileConnectStatus::Error("invalid_state", "State values do not match, this could suggest an attempted Cross-Site Request Forgery", null);
        try {
            $code = $queryValue['code'];
            $clientId = $config->getClientId();
            if (!empty($discoveryResponse) && !empty($discoveryResponse->getResponseData()) && isset($discoveryResponse->getResponseData()['response']['client_id'])) {
                $clientId = $discoveryResponse->getResponseData()['response']['client_id'];
            $clientSecret = $config->getClientSecret();
            if (!empty($discoveryResponse) && !empty($discoveryResponse->getResponseData()) && isset($discoveryResponse->getResponseData()['response']['client_secret'])) {
                $clientSecret = $discoveryResponse->getResponseData()['response']['client_secret'];
            $requestTokenUrl = null;
            if (!empty($discoveryResponse) && !empty($discoveryResponse->getOperatorUrls()) && !empty($discoveryResponse->getOperatorUrls()->getRequestTokenUrl())) {
                $requestTokenUrl = $discoveryResponse->getOperatorUrls()->getRequestTokenUrl();
            $issuer = $discoveryResponse->getProviderMetadata()["issuer"];

            $response = $authentication->RequestToken($clientId, $clientSecret, $requestTokenUrl, $config->getRedirectUrl(), $code);
            $jwKeySet = $jwks->RetrieveJWKS($discoveryResponse->getOperatorUrls()->getJWKSUrl());
            if (isset($discoveryResponse->getProviderMetadata()['mobile_connect_version_supported'])) {
                $supportedVersions = new SupportedVersions($discoveryResponse->getProviderMetadata()['mobile_connect_version_supported']);
            } else {
                $supportedVersions = new SupportedVersions(null);
            return static::HandleTokenResponse($authentication, $response, $clientId, $issuer, $expectedNonce, $jwKeySet,
                $supportedVersions->getMaxSupportedVersion(), $options);

        } catch(Exception $ex) {
            return MobileConnectStatus::Error("unknown_error", "A failure occured while requesting a token", $ex);
        return MobileConnectStatus::Complete($response);

After RequestToken method performing server side returns the Token JSON response to client side application.

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).

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 server side library provides constants that you can pass when requesting specific Identity products:


Upon successful authorisation, the server side library 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 scopes “mc_identity_signup” and “mc_identity_nationalid” 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

Further Reference