Developers

Integrate mobile payments and monetize with Mocopay

Our developer center provides all the details for a simple and smooth integration so you could easily add mobile payments with Mocopay.

Integration instructions

The main entry point into your communication with the SDK is the Payment class. This class is used to initiate the purchase and also to verify the status of a previous one.

Setup process

To begin, a Payment object needs to be instantiated. To do that, you need to have a PaymentConfig object also, which defines the basic configuration parameters of the payment process. The PaymentConfig object is constructed via a Builder pattern, and has three mandatory parameters – URL, ApiKey and ApiSecret. These parameters are all given by MoCoPay and can be found in control box inside service details (you can find more info in the developers help pages that describe the control box GUI).

PaymentConfig config = new PaymentConfig.Builder(
    "payment_manager_url", // accessible via the MoCoPay control box
    "payment_manager_api_key",
    "payment_manager_api_secret"
).build();

Now that we have the configuration object, we can instantiate a Payment object. The constructor receives a Context object and the aforementioned PaymentConfig. The next step is to start the setup process of the Payment object which will notify a listener when it’s done. After receiving the callback from the setup method, the payment process can be initiated. Alternatively, we can then also check the status of a previous purchase (more on that further down). Here is an example of the complete setup process in an hypothetical Activity which we will use throughout our examples:

public class MyActivity extends Activity {
    private Payment mPayment;
    private boolean mSetupDone;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        PaymentConfig config = new PaymentConfig.Builder(
            "payment_manager_url", // get this from your MoCoPay control box
            "payment_manager_api_key",
            "payment_manager_api_secret"
        ).build();

        mPayment = new Payment(this, config);
        mPayment.startSetup(listener);

        Button button = (Button) findViewById(R.id.buy_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                makeThePurchase();
            }
        });
    }

    private OnSetupFinishedListener listener = new OnSetupFinishedListener() {
        @Override
        public void onSetupFinished() {
            // our Payment object is now ready!
            mSetupDone = true;
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSetupDone = false;
        mPayment.dispose(); // important
    }

    private void makeThePurchase() {
        // making a purchase in the next example
    }
}

Please note, it is important to dispose of the Payment object in the onDestroy method of your implementing class to prevent resource leaks.

Buying a product

After the setup is finished, we can make a purchase. To do that, you need a PaymentRequest object. This method defines the necessary information to purchase a product. This object is constructed via the Builder pattern and has multiple configuration parameters you can provide. When you have the request object, you can make the purchase by calling the startPayment(PaymentRequest, PaymentListener) method on your Payment object. That code might look something like this:

public class MyActivity extends Activity {
    // previous code omitted for brevity

    private void makeThePurchase() {
        if (!mSetupDone) {
            // wait for the setup to finish
            return;
        }

        PaymentRequest request = new PaymentRequest.Builder("your_product_id")
        .build();

        mPayment.startPayment(request, new PaymentListener() {
            @Override
            public void onSuccess(PaymentData data) {
                // we have the sessionId – we should verify the session status!
                mSessionId = data.getSessionId();
                verifyThePurchase();
            }

            @Override
            public void onError(PaymentError error) {
                // an irrecoverable error was detected
            }
        });
    }

    private void verifyThePurchase() {
        // verifying the purchase in the next example
    }
}

When you call the startPayment method, the PaymentActivity (which we’ve declared earlier in our manifest) will be displayed to the user, guiding him through the payment process. The PaymentListener will be called once per startPayment call.

Due to differences in the payment process and regulations in different countries and/or markets, an onSuccess() callback does not necessarily mean that the whole payment process was finished successfully. What it means is that we have got a valid payment session identifier through which we can then check the actual payment session status. You should save the sessionId you get here so that you can verify the session at any time in the future in case it changes (e.g. on the next application start-up). You can, of course, hold the session status also, for example to rely on that when there is no Internet connection to verify the payment session.

Checking the status of a purchase

To actually verify the payment session status, you call the verifyPayment() method, which is available via the Payment object, just as the startPayment() method was. When you get a success callback, you can then get all of the relevant session information through the VerifyPaymentResponse object you receive.

public class MyActivity extends Activity {
    // previous code omitted for brevity

    private void verifyThePurchase() {
        mPayment.verifyPayment(mSessionId, new VerifyPaymentListener() {
            @Override
            public void onSuccess(VerifyPaymentResponse response) {
                // inspect the "response" object to find out
                // more information about the payment session
                // for example you can get the status enum like this:
                PaymentSessionStatus status = PaymentSessionStatus.from(response);
            }

            @Override
            public void onError(AsyncError error) {
                // the network call failed or there was a server
                // side error – note that this does not
                // reflect the payment session status
            }
        });
    }
}

For a complete list of potential payment session statuses, you can check our payment notification chapter.

And that’s it! You’ve successfully integrated the payment SDK in your application. If you wish, can check out the rest of this guide for the more advanced use-cases.

Additional payment parameters

When constructing a payment request object, you can, alongside the mandatory productId parameter, specify additional parameters which can affect the payment process. These additional parameters are provided via the Builder when the PaymentRequest object is constructed. All of these additional parameters are optional, only the productId is mandatory. Here is an example:

new PaymentRequest.Builder(getString(R.string.product_id_onetime))
    .withImageUrl("http://your_site.org/diamond_image.jpg")
    .withImageResource(R.drawable.ic_diamond)
    .withMcc("mcc")
    .withMnc("mnc")
    .withCountry("country_id")
    .withPhone("phone")
    .withLanguage("language")
    .withUserId("user_id") // e.g. PaymentUtils.getAvailableID(getActivity())
    .withNotifyUrl("notify_url")
    .build();

Here are the descriptions for each of these parameters:

Parameter Description

ImageUrl

The image specified by this URL will be displayed on the payment screens if “native” display is used (as opposed to the WebView display).

ImageResource

The image specified by this Android ResourceId will be displayed on the payment screens if “native” display is used (as opposed to the WebView display). If ImageUrl is also specified, this parameter is ignored.

Mcc

MCC (Mobile Country Code) parameter to help determine which payment route will be used (currency, short id, etc.). The SDK provides a convenience method through which you can find out the MCC of the SIM card. If that is acceptable, you can use PaymentUtils.getMCC(context).

Mnc

MNC (Mobile Network Code) parameter to help determine which payment route will be used (currency, short id, etc.). The SDK provides a convenience method through which you can find out the MNC of the SIM card. If that is acceptable, you can use PaymentUtils.getMCC(context).

Country

Country ISO 2 code.

Phone

End user mobile phone number (you can set this if it is available).

Language

Preferred language code (ISO 639-1).

UserId

End user identifier.

NotifyUrl

Notification URL.

Preferred display type

The method startPayment() has, as it’s last parameter, a varargs of type DisplayType. The values provided here signify the “preferred” display types that you would like to use during the payment process and are checked against the supported display types returned from the back-end. The first display type (from the varargs parameter) that was found as “supported” in the list sent from the back-end, will be used. If none of the preferred displayed types are in the supported list, we will automatically default to the “WEB” display type. For example, if you wish to display the native flow instead of the web flow (provided that’s supported), you can use something like this (the web flow will then be used as a fallback option in case the native flow is not supported):

public class MyActivity extends Activity {
    // omitted for brevity
    private void makeThePurchase() {
        mPayment.startPayment(request, new PaymentListener() {
            // implement onSuccess() and onError() as usual
        }, DisplayType.NATIVE);
    }
}