Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
mikejpeters committed Jan 9, 2020
0 parents commit 3b504bf
Show file tree
Hide file tree
Showing 12 changed files with 583 additions and 0 deletions.
33 changes: 33 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# CRAFT ENVIRONMENT
.env.php
.env.sh
.env

# COMPOSER
/vendor
/composer.lock

# BUILD FILES
/bower_components/*
/node_modules/*
/build/*
/yarn-error.log

# MISC FILES
.cache
.DS_Store
.idea
.project
.settings
*.esproj
*.sublime-workspace
*.sublime-project
*.tmproj
*.tmproject
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
config.codekit3
prepros-6.config
9 changes: 9 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
The MIT License (MIT)

Copyright (c) 2020 Bound State Software

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
88 changes: 88 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# Mailchimp plugin for Craft CMS 3.x

Subscribe users to Mailchimp lists in Craft CMS

## Installation

To install the plugin, follow these instructions.

1. Open your terminal and go to your Craft project:

cd /path/to/project

2. Then tell Composer to load the plugin:

composer require boundstate/craft-mailchimp

3. In the Control Panel, go to Settings → Plugins and click the “Install” button for Mailchimp.

4. In the Control Panel, go to Settings → Plugins → Mailchimp and configure the plugin.

## Usage

Your subscribe form template can look something like this:

```twig
<form method="post" action="" accept-charset="UTF-8">
{{ csrfInput() }}
<input type="hidden" name="action" value="mailchimp/subscribe">
{{ redirectInput('subscribe/thanks') }}
<h3><label for="name">Your Name</label></h3>
<input id="name" type="text" name="mergeFields[NAME]" value="{{ subscription.mergeFields.NAME ?? '' }}" required>
<h3><label for="email">Your Email</label></h3>
<input id="email" type="email" name="email" value="{{ subscription.email ?? '' }}" required>
{{ subscription.getErrors('email')|join() }}
<input type="hidden" name="tags[]" value="Tag 1">
<input type="hidden" name="tags[]" value="Tag 2">
<input type="submit" value="Subscribe">
</form>
```

The only required field is `email`. Everything else is optional.

### Redirecting after submit

If you have a `redirect` hidden input, the user will get redirected to it upon successfully subscribing. The following variables can be used within the URL/path you set:

- `{email}`
- `{mergeFields}`
- `{tags}`

For example, if you wanted to redirect to a `subscribe/thanks` page and pass the user’s name to it, you could set the input like this:

```twig
{{ redirectInput('subscribe/thanks?name={mergeFields.NAME}') }}
```

In your `subscribe/thanks` template, you can access URL parameters using `craft.app.request.getQueryParam()`:

```twig
<p>Thanks for subscribing, {{ craft.app.request.getQueryParam('name') }}!</p>
```

Note that if you don’t include a `redirect` input, the current page will get reloaded.

### Flash messages & API errors

When a subscribe form is submitted, the plugin will set a `notice` or `success` flash message on the user session. You can display it in your template like this:

```twig
{% if craft.app.session.hasFlash('notice') %}
<p class="message notice">{{ craft.app.session.getFlash('notice') }}</p>
{% elseif craft.app.session.hasFlash('error') %}
<p class="message error">{{ craft.app.session.getFlash('error') }}</p>
{% endif %}
```

If the Mailchimp API returns an error, the plugin also sets the `subscription.apiError` variable. You can display it in your template like this:

```twig
{% if subscription is defined and subscription.apiError %}
<h3>{{ subscription.apiError.title }}</h3>
<p>{{ subscription.apiError.detail }}</p>
{% endif %}
```
38 changes: 38 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"name": "boundstate/craft-mailchimp",
"description": "Subscribe users to Mailchimp lists in Craft CMS",
"type": "craft-plugin",
"version": "1.0.0",
"keywords": [
"craft",
"cms",
"craftcms",
"craft-plugin",
"mailchimp"
],
"license": "MIT",
"authors": [
{
"name": "Bound State Software",
"homepage": "https://boundstatesoftware.com"
}
],
"support": {
"docs": "https://github.com/boundstate/craft-mailchimp/blob/master/README.md",
"issues": "https://github.com/boundstate/craft-mailchimp/issues"
},
"require": {
"craftcms/cms": "^3.0.0",
"drewm/mailchimp-api": "^2.5"
},
"autoload": {
"psr-4": {
"boundstate\\mailchimp\\": "src/"
}
},
"extra": {
"handle": "mailchimp",
"name": "Mailchimp",
"description": "Subscrube users to Mailchimp lists"
}
}
43 changes: 43 additions & 0 deletions src/Plugin.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php
namespace boundstate\mailchimp;

use Craft;

class Plugin extends \craft\base\Plugin
{
/**
* @inheritdoc
*/
public $hasCpSettings = true;

public function init()
{
parent::init();

$this->setComponents([
'mailchimp' => \boundstate\mailchimp\services\Mailchimp::class,
]);
}

/**
* @inheritdoc
*/
protected function createSettingsModel()
{
return new \boundstate\mailchimp\models\Settings();
}

/**
* @inheritdoc
*/
protected function settingsHtml()
{
// Get and pre-validate the settings
$settings = $this->getSettings();
$settings->validate();

return Craft::$app->getView()->renderTemplate('mailchimp/settings', [
'settings' => $settings
]);
}
}
57 changes: 57 additions & 0 deletions src/controllers/SubscribeController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php
namespace boundstate\mailchimp\controllers;

use boundstate\mailchimp\models\Subscription;
use boundstate\mailchimp\Plugin;

use Craft;
use craft\web\Controller;
use yii\web\Response;

class SubscribeController extends Controller
{
/**
* @inheritdoc
*/
protected $allowAnonymous = true;

/**
* Subscribes a member to a MailChimp list.
*
* @return Response|null
*/
public function actionIndex()
{
$this->requirePostRequest();

$request = Craft::$app->getRequest();
$urlManager = Craft::$app->getUrlManager();
$plugin = Plugin::getInstance();
$settings = $plugin->getSettings();

$subscription = new Subscription();
$subscription->listId = $request->getBodyParam('listId');
$subscription->email = $request->getBodyParam('email');
$subscription->mergeFields = $request->getBodyParam('mergeFields');
$subscription->tags = $request->getBodyParam('tags');

if (!$plugin->mailchimp->subscribe($subscription)) {
if ($request->getAcceptsJson()) {
return $this->asJson(['errors' => $subscription->getErrors()]);
}

Craft::$app->getSession()->setError(Craft::t('mailchimp', 'There was a problem with your submission, please check the form and try again!'));
Craft::$app->getUrlManager()->setRouteParams([
'variables' => ['subscription' => $subscription]
]);
return null;
}

if ($request->getAcceptsJson()) {
return $this->asJson(['success' => true]);
}

Craft::$app->getSession()->setNotice($settings->successFlashMessage);
return $this->redirectToPostedUrl($subscription);
}
}
5 changes: 5 additions & 0 deletions src/icon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
53 changes: 53 additions & 0 deletions src/models/ApiError.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php
namespace boundstate\mailchimp\models;

use craft\base\Model;

class ApiError extends Model
{
/**
* @var string|null
*/
public $type;

/**
* @var string|null
*/
public $title;

/**
* @var int|null
*/
public $status;

/**
* @var string|null
*/
public $detail;

/**
* @var string|null
*/
public $instance;

/**
* @var array|null
*/
public $errors;

/**
* @param array $result
* @return ApiError
*/
static function fromApiResult($result): ApiError {
$apiError = new ApiError();
$apiError->type = $result['type'];
$apiError->title = $result['title'];
$apiError->status = $result['status'];
$apiError->detail = $result['detail'];
$apiError->instance = $result['instance'];
$apiError->errors = $result['errors'] ?? [];

return $apiError;
}
}
46 changes: 46 additions & 0 deletions src/models/Settings.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php
namespace boundstate\mailchimp\models;

use Craft;
use craft\base\Model;

class Settings extends Model
{
/**
* @var string Mailchimp API key
*/
public $apiKey;

/**
* @var string Audience ID
*/
public $audienceId;

/**
* @var string|null
*/
public $successFlashMessage;

/**
* @inheritdoc
*/
public function init()
{
parent::init();

if ($this->successFlashMessage === null) {
$this->successFlashMessage = Craft::t('mailchimp', 'Thanks for subscribing.');
}
}

/**
* @inheritdoc
*/
public function rules(): array
{
return [
[['apiKey', 'successFlashMessage'], 'required'],
[['apiKey', 'audienceId', 'successFlashMessage'], 'string'],
];
}
}
Loading

0 comments on commit 3b504bf

Please sign in to comment.