Is there a way to extend the API?

Ernesto

Member
I'm associating my main site users with MW customers via their uid, and to call API endpoints like the list/view for example, I need the customer's keys.
So I'd need to add an API endpoint that lets me get the customer keys. I know this may pose a security threat, but the API is restricted to 127.0.0.1 so only my application will have access to it.
I could just add an action to the API's CustomersController, but it would be cleaner to add it as an extension, I think.
 
@Ernesto - Why not simply add your own controllers in the apps/api/controllers ?
Prefix them to avoid collision and go from there ;)
Yeah, you're right, I'll go that way.
I was thinking how to build something that we easy to maintain even through Mailwizz updates, I think I could do it as a Yii module or something, but for now I'll just hack it in.
 
@twisted1919 - Ok so I added an action to the Customers controller of the API, (I know, not a different controller as you suggested, just an action for now) but there's no logged-in user, but when I call the Lists endpoint, using the same customer keys, there is.
What could be wrong?

I added this to the API's CustomerController. The Yii user object is a Guest, so no id is returned with getId()
PHP:
public function actionView()
{
    $customer = Customer::model()->findByPk( (int)Yii::app()->user->getId());
    if( $customer ) {
        return $this->renderJson([
            'status'    => 'success',
            'data'      => $customer
        ], 200);
    }
    else {
        return $this->renderJson([
            'status'    => 'error',
            'debug'     => Yii::app()->user,
            'error'     => Yii::t('api', 'The customer does not exist.')
        ], 404);
    }
}

I added the rule to the urlManager for the API:
PHP:
array('customers/view',   'pattern' => 'customers', 'verb' => 'GET'),
 
Last edited:
@Ernesto - if you look in /apps/api/config/main.php at the end of the file you will see:
Code:
// application-level parameters that can be accessed
// using Yii::app()->params['paramName']
'params' => array(
    'unprotectedControllers' => array(
        'site', 'customers',
    )
),
Which means the customers controller is freely available, thus no user is loaded there automatically for you.
If you want to load a customer in such scenario, then you'd do something like:
PHP:
// simplified example, make sure you check if keys are set, records exists, and so on.
$publicKey =  $_SERVER['HTTP_X_MW_PUBLIC_KEY'];
$key = CustomerApiKey::model()->findByAttributes(array(
    'public' => $publicKey
));
$customer = Customer::model()->findByPk((int)$key->customer_id);
Beware that the api keys have to be passed in the api call.
 
Back
Top