Magento 使用 geoip2 插件做用户IP定位功能

一. 安装 geoip2 库,并检查ip

第一步:安装 geoip2 库

composer require geoip2/geoip2:~2.0

 

第二步:下载 GeoLite2 数据库
需要注册账户,注册成功后就可以直接下载 GeoLite2 数据库
第三步:调用 ip 检测方法

$reader = new Reader('/var/geoip/GeoLite2-Country.mmdb'); //替换成自己的数据库文件路径
$record = $reader->city('128.101.101.101');
print($record->country->isoCode);

 

 

二. 更新 geoip2 数据库

下载用到的 API
https://www.geodbase-update.com/api/v1/edition
需要注册账户的 License key
直接上代碼:

<?php

namespace xxxx\xxxxxx\Helper;

use DirectoryIterator;
use Exception;
use FilesystemIterator;
use PharData;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use ReflectionClass;
use ZipArchive;

/**
* Class Client
* @package tronovav\GeoIP2Update
*/
class Client
{
const ARCHIVE_GZ = 'tar.gz';
const ARCHIVE_ZIP = 'zip';

/**
* @var string Your account’s actual license key on www.maxmind.com
* @link https://support.maxmind.com/account-faq/license-keys/where-do-i-find-my-license-key/
*/
public $license_key;

/**
* @var string Your account’s actual "geodbase_update_key" on www.geodbase-update.com
* @link https://www.geodbase-update.com
*/
public $geodbase_update_key;

/**
* @var string[] Database editions list to update.
* @link https://www.maxmind.com/en/accounts/current/geoip/downloads/
*/
public $editions;

/**
* @var string Destination directory. Directory where your copies of databases are stored. Your old databases will be updated there.
*/
public $dir;

protected $_editionVersions = array();
protected $_baseUrlApi = 'https://www.geodbase-update.com/api/v1/edition';
protected $_updated = array();
protected $_errors = array();
protected $_errorUpdateEditions = array();
protected $_lastModifiedStorageFileName = 'VERSION.txt';
protected $_client = 1;
protected $_client_version = '2.3.1';

public function __construct(array $params)
{
$this->setConfParams($params);
$thisClass = new ReflectionClass($this);
foreach ($params as $key => $value)
if ($thisClass->hasProperty($key) && $thisClass->getProperty($key)->isPublic()) {
$this->$key = $value;
} else {
$this->_errors[] = "The \"{$key}\" parameter does not exist. Just remove it from the options. See https://www.geodbase-update.com";
}
}

/**
* Update info.
* @return array
*/
public function updated()
{
return $this->_updated;
}

/**
* Update errors.
* @return array
*/
public function errors()
{
return array_merge($this->_errors, array_values($this->_errorUpdateEditions));
}

/**
* Database update launcher.
* @throws Exception
*/
public function run()
{
if (!$this->validate()) {
return;
}

$this->updateEdition((string)$this->editions);

}

protected function setConfParams(&$params)
{
if (array_key_exists('geoipConfFile', $params)) {
if(is_file($params['geoipConfFile']) && is_readable($params['geoipConfFile'])) {
$confParams = array();
foreach (file($params['geoipConfFile']) as $line) {
$confString = trim($line);
if (preg_match('/^\s*(?P<name>LicenseKey|EditionIDs)\s+(?P<value>([\w-]+\s*)+)$/', $confString, $matches)) {
$confParams[$matches['name']] = $matches['name'] === 'EditionIDs'
? array_values(array_filter(explode(' ', $matches['value']), function ($val) {
return trim($val);
}))
: trim($matches['value']);
}
}
$this->license_key = !empty($confParams['LicenseKey']) ? $confParams['LicenseKey'] : $this->license_key;
$this->editions = !empty($confParams['EditionIDs']) ? $confParams['EditionIDs'] : $this->editions;
} else {
$this->_errors[] = 'The geoipConfFile parameter was specified, but the file itself is missing or unreadable. See https://www.geodbase-update.com';
}
unset($params['geoipConfFile']);
}
}

/**
* @return bool
*/
protected function validate()
{
if (!empty($this->_errors)) {
return false;
}

switch (true) {
case empty($this->dir):
$this->_errors[] = 'Destination directory not specified. See documentation at https://www.geodbase-update.com';
break;
case !is_dir($this->dir):
$this->_errors[] = "The destination directory \"{$this->dir}\" does not exist. See documentation at https://www.geodbase-update.com";
break;
case !is_writable($this->dir):
$this->_errors[] = "The destination directory \"{$this->dir}\" is not writable. See documentation at https://www.geodbase-update.com";
}

if (empty($this->license_key)) {
$this->_errors[] = 'You must specify your Maxmind "license_key". See documentation at https://www.geodbase-update.com';
}

if (empty($this->editions)) {
$this->_errors[] = "No GeoIP revision names are specified for the update. See documentation at https://www.geodbase-update.com";
}

if (!empty($this->_errors)) {
return false;
}

return true;
}

/**
* @param string $editionId
* @throws Exception
*/
protected function updateEdition(string $editionId)
{
$remoteEditionData = $this->getRemoteEditionData($editionId);

if (!empty($this->_errorUpdateEditions[$editionId])) {
return;
}

if ($remoteEditionData['ext'] === self::ARCHIVE_ZIP && !class_exists('\ZipArchive')) {
$this->_errorUpdateEditions[$editionId] = "PHP zip extension is required to update csv databases. See https://www.php.net/manual/en/zip.installation.php to install zip php extension.";
return;
}

$remoteActualVersion = date_create($remoteEditionData['version']);

$localEditionData = is_file($this->getEditionDirectory($editionId) . DIRECTORY_SEPARATOR . $this->_lastModifiedStorageFileName) ?
file_get_contents($this->getEditionDirectory($editionId) . DIRECTORY_SEPARATOR . $this->_lastModifiedStorageFileName) : '';

$currentVersion = date_create_from_format('Y-m-d\TH:i:sP',$localEditionData) ?: 0;

$this->_editionVersions[$editionId] = [
!empty($currentVersion) ? $currentVersion->format('c') : 0,
$remoteActualVersion->format('c')
];

if (empty($currentVersion) || $currentVersion != $remoteActualVersion) {

$this->download($remoteEditionData);
if (!empty($this->_errorUpdateEditions[$editionId])) {
return;
}

$this->extract($remoteEditionData);
if (!empty($this->_errorUpdateEditions[$editionId])) {
return;
}

$this->_updated[] = "$editionId has been updated.";
} else {
$this->_updated[] = "$editionId does not need to be updated.";
}
}

/**
* @param $editionId
* @return string
*/
protected function getEditionDirectory($editionId): string
{
return $this->dir . DIRECTORY_SEPARATOR . $editionId;
}

/**
* @param string $editionId
* @return array
*/
protected function getRemoteEditionData(string $editionId): array
{
$ch = curl_init(trim($this->_baseUrlApi,'/').'/'.'data'.'?'. http_build_query(array(
'id' => $editionId,
)));
curl_setopt_array(
$ch,
[
CURLOPT_HEADER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Accept: application/json',
'X-Api-Key: '.$this->geodbase_update_key
],
CURLOPT_POSTFIELDS => json_encode(
[
'maxmind_key' =>$this->license_key,
'client' => $this->_client,
'client_version' => $this->_client_version
]
)
]
);

$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if(empty($httpCode)){
$this->_errorUpdateEditions[$editionId] = "The remote server is not available.";
return [];
}

$resultArray = json_decode($result,true);

if($httpCode !== 200){
$this->_errorUpdateEditions[$editionId] = $resultArray['data']['message'] ?: $resultArray['data']['name'];
return [];
}
return $resultArray['data'];
}

/**
* @param array $remoteEditionData
*/
protected function download($remoteEditionData)
{
$ch = curl_init(
trim($this->_baseUrlApi,'/').'/'.'download'.'?'. http_build_query(
['request_id' => $remoteEditionData['request_id']]
)
);
$fh = fopen($this->getArchiveFile($remoteEditionData), 'wb');
curl_setopt_array($ch, array(
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'X-Api-Key: '.$this->geodbase_update_key,
),
CURLOPT_FILE => $fh,
));
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
fclose($fh);
if ($response === false || $httpCode !== 200){
if(is_file($this->getArchiveFile($remoteEditionData)))
unlink($this->getArchiveFile($remoteEditionData));
$this->_errorUpdateEditions[$remoteEditionData['id']] = "Download error: ($httpCode)" . curl_error($ch);
}
}

protected function getArchiveFile($remoteEditionData)
{
return $this->dir . DIRECTORY_SEPARATOR . $remoteEditionData['id'] . '.' . $remoteEditionData['ext'];
}

/**
* @param array $remoteEditionData
*/
protected function extract(array $remoteEditionData)
{
switch ($remoteEditionData['ext']) {
case self::ARCHIVE_GZ:
if (!in_array('phar', stream_get_wrappers(), true)) {
stream_wrapper_restore('phar');
}
$phar = new PharData($this->getArchiveFile($remoteEditionData));
$phar->extractTo($this->dir, null, true);
break;
case self::ARCHIVE_ZIP:
$zip = new ZipArchive;
$zip->open($this->getArchiveFile($remoteEditionData));
$zip->extractTo($this->dir);
$zip->close();
break;
}

unlink($this->getArchiveFile($remoteEditionData));

if (!is_dir($this->getEditionDirectory($remoteEditionData['id']))) {
mkdir($this->getEditionDirectory($remoteEditionData['id']));
}

$directories = new DirectoryIterator($this->dir);
foreach ($directories as $directory) {
/* @var DirectoryIterator $directory */
if ($directory->isDir() && preg_match('/^' . $remoteEditionData['id'] . '[_\d]+$/i', $directory->getBasename())) {
$newEditionDirectory = new DirectoryIterator($directory->getPathname());
foreach ($newEditionDirectory as $item)
if ($item->isFile()) {
rename($item->getPathname(), $this->getEditionDirectory($remoteEditionData['id']) . DIRECTORY_SEPARATOR . $item->getBasename());
}
file_put_contents($this->getEditionDirectory($remoteEditionData['id']) . DIRECTORY_SEPARATOR . $this->_lastModifiedStorageFileName, $remoteEditionData['version']);
$this->deleteDirectory($directory->getPathname());
break;
}
}
$this->copyFiles($remoteEditionData);
}

/**
* @param $remoteEditionData
*/
public function copyFiles($remoteEditionData)
{
$directoryPath = $this->dir . DIRECTORY_SEPARATOR . $remoteEditionData['id'];
$sourceFile = $this->dir . DIRECTORY_SEPARATOR . $remoteEditionData['id'] . DIRECTORY_SEPARATOR . $remoteEditionData['id'] . '.mmdb';
$targetFile = $this->dir . DIRECTORY_SEPARATOR . $remoteEditionData['id'] . '.mmdb';
$content = file_get_contents($sourceFile);
file_put_contents($targetFile, $content);
$this->deleteDirectory($directoryPath);
}

/**
* @param string $directoryPath
*/
protected function deleteDirectory(string $directoryPath)
{
if (is_dir($directoryPath)) {
$directory = new RecursiveDirectoryIterator($directoryPath, FilesystemIterator::SKIP_DOTS);
$children = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::CHILD_FIRST);
foreach ($children as $child)
/* @var RecursiveDirectoryIterator $child */
$child->isDir() ? rmdir($child) : unlink($child);
rmdir($directoryPath);
}
}
}


//调用数据库更新
public function execute()
{
// 获取 License key
$licenseKey = $this->helperData->getLicenseKey();
// 指定下载目录
$downloadPath = $this->directoryList->getPath('var') . $this->helperData->getDownloadPath();
if (!is_dir($downloadPath)) {
mkdir($downloadPath, 0755, true);
}
$client = new Client(
[
'license_key' => $licenseKey,
'dir' => $downloadPath,
'editions' => 'GeoLite2-Country',
]
);
$client->run();
}

 

在 Windows 系统上开发 Shopify 插件(通常称为 Shopify Apps)是完全可行的。Shopify 应用可以是独立的网络应用程序,它与 Shopify 店铺通过 Shopify API 交互。以下是开发 Shopify 应用的完整流程:

1. 环境设置

设置开发环境

首先,确保你的 Windows 机器安装有以下工具:
- 文本编辑器或IDE(如 Visual Studio Code, Sublime Text, JetBrains PhpStorm)
- Ruby(Shopify CLI 需要 Ruby 来运行)
- Node.js(用于 Shopify Node.js 或 React 应用)
- Git(代码版本控制)
- Shopify CLI(命令行工具,用于创建和管理 Shopify 应用)

你可以从 Shopify 的官方网站下载并安装 Shopify CLI。

安装 Shopify CLI

在 Windows 上安装 Shopify CLI,通常可以通过 RubyGems 安装:

gem install shopify-cli

 

2. 注册 Shopify 开发者账号

- 访问 Shopify Partners 网站并注册一个开发者账号。
- 创建一个 Partners 账户后,你可以创建开发商店,用于测试和开发应用。

3. 创建新的 Shopify 应用

- 在 Shopify Partner Dashboard 中创建一个新的应用。
- 设置应用的配置,包括应用名称、URL、回调地址等。

4. 开发应用

使用 Shopify CLI 创建应用

在命令行中运行以下命令来创建一个新的 Shopify 应用(支持 Node.js 和 Ruby on Rails):

shopify app create node

shopify app create rails

 

这些命令将生成一个应用的基础架构,包括用于与 Shopify API 交互的一些初始代码。

开发功能

根据你的应用需求,你可能需要开发以下功能:
- 认证和授权(使用 OAuth)
- 与 Shopify API 交互
- 前端界面(如果是嵌入式应用,使用 Polaris 或其他前端框架)
- Webhooks 处理
- 定期任务处理

5. 测试应用

- 使用你的开发商店测试应用功能。
- 确保所有功能在实际场景下都能正常工作。

6. 部署应用

- 将应用部署到生产环境。通常可以使用云服务平台,如 Heroku、AWS、Azure 等。
- 更新应用的配置,确保所有生产环境的 URL 和回调地址都是正确的。

7. 提交应用审核

- 如果你打算将应用发布到 Shopify App Store,则需要提交给 Shopify 进行审核。
- 遵循 Shopify 的应用审核指南和最佳实践,确保应用符合所有要求。

8. 发布应用

- 审核通过后,你的应用就可以在 Shopify App Store 上架了。
- 根据用户反馈和需求,继续维护和更新应用。

使用 Windows 开发 Shopify 应用完全可行,重要的是遵循开发和部署的最佳实践,并确保提供高质量的用户体验。

前几天逛github,无意中发现了国外大神(magenx)的一键部署命令,然后做了测试,第一次部署因为没细看,导致中途出了很多问题;后面认真理解了部署步骤命令跟着操作后很顺利,总体而言还是比较不错,推荐一下;

环境:debian11/unbuntu20.04(貌似也支持centos,但是我没有实测);

我的环境是ubuntu20.04,空白环境;

话不多说,直接上命令;

curl -Lo magenx.sh https://magenx.sh && bash magenx.sh 执行操作后,就开始跑了,会自动安装环境所需,自动更改SSH端口,请留意窗口展示,(为啥我不能上传图片) 执行命令过程中每个环境所需的每个软件安装都需要确认,包括magento版本选择等; lemp,magento,database,install,config,执行完成后根据自己的需求可以继续安装webmin和firewell; 最后执行certbot certonly --agree-tos --no-eff-email --email {EMAIL} --webroot -w /home/{USER}/public_html/pub 生成ssl;并修改相关的配置文件
  • /etc/nginx/nginx.conf
  • /etc/nginx/sites-available/{DOMAIN_NAME}.conf
  • /etc/nginx/conf_m2/varnish_proxy.conf
  • 然后就可以上线了

新人报道magento,多多关照

magento的代码高度模块化,阅读时一般分模块阅读。在阅读某个模块的代码的时候可以把代码大致分成三类:

  1. 实现/继承了其他模块的接口/类的代码

  2. 本模块对外定义的接口/类

  3. 本模块内部使用的接口/类

对于第1类代码,需要在熟悉关联模块的代码的基础之上再阅读(或者说在读之前,先要阅读关联模块的代码。)。这类代码一般处于和关联模块名同名的文件夹下。

对于第2类代码,模块可能会定义多个类和接口,这些类与接口之间的组合关系可能会用到行为型模式,比如:策略模式、状态模式、观察者模式等等。(通常都只是简单组合,行为型模式本质就是低耦合,只是组合之外符合特定行为定义而已。)

对于第3类代码,模块之所以定义这些接口/类是为第2类代码服务的,这类代码定义的接口/类与第1类代码定义的接口/类要么是继承关系,要么是组合关系。如果是组合关系,通常会用到结构型模式,比如:桥接模式、组合模式、装饰模式、代理模式等等。这类代码一般处于模块子目录文件夹里。(结构型模式本质是高内聚,涉及的类都将实现同一个接口)

看magento自带一套restapi,看了作者写的api章节要用这个restapi要先在后台建立一个用户,但是我们网站上都已经有很多用户了,怎么直接用网站上现有的用户?

本文介绍两种方式:

  1. 本地手动运行测试
  2. push到Github时利用Github Actions 自动测试

 

1. 本地手动测试(本地需安装php 8.1 运行环境)

#切换到项目根目录运行以下命令

! find . -not \( -path ./.phpstorm.meta.php -prune \) -type f -name "*.php" -exec php -d error_reporting=32767 -l {} \; 2>&1 1> /dev/null | grep "^"

效果如图:

2. Github Actions 自动测试

  1. 在项目根目录新建.github/workflows/文件夹
  2. .github/workflows/下新建php-syntax-check.yml并添加以下代码
    name: "PHP Syntax Check"
    on:
      push:
      pull_request:
    
    jobs:
      php_syntax_check:
        name: PHP Syntax ${{ matrix.php-versions }} Check
        runs-on: ${{ matrix.operating-system }}
        needs: php_syntax
        strategy:
          max-parallel: 1
          fail-fast: false
          matrix:
            operating-system: [ubuntu-latest]
            php-versions: ["8.1"]
        steps:
          - uses: actions/checkout@v1
          - name: Setup PHP
            uses: shivammathur/setup-php@master
            with:
              php-version: ${{ matrix.php-versions }}
              extension-csv: mbstring #optional, setup extensions
              ini-values-csv: post_max_size=256M, short_open_tag=On #optional, setup php.ini configuration
              coverage: none #optional, setup coverage driver
              pecl: true #optional, setup PECL
          - name: Check PHP Version
            run: php -v
          - name: Check .php files
            continue-on-error: true
            run: '! find . -not \( -path ./.phpstorm.meta.php -prune \) -type f -name "*.php" -exec php -d error_reporting=32767 -l {} \; 2>&1 1> /dev/null | grep "^"'

 

来源:https://github.com/OpenMage/magento-lts

一. vps系统:Linux CentOS 7.7.1908 64bit

二. yum -y update 更新一下centos系统

三. oneinstack自动安装,生成安装命令如下链接:https://oneinstack.com/auto/
【 备注:apache2.4, Mariadb10.4, php7.4(默认), php8.0(第二安装), 勾选php扩展(fileinfo, redis, memcached, swoole), 下面再勾选:node.js(根据以后需要打勾), .... iptables 】

四. 修改默认的php.ini的配置文件并保存
vi /usr/local/php/etc/php.ini
找到下面这些项进行修改 ( vi下面按esc, 然后: /查找的字符)
1. memory_limit = 1024M
2. max_execution_time = 18000
3. max_input_time = 1800
4. zlib.output_compression = on
5. 找到这项 disable_functions=... 删除3个禁止的函数:exec, proc_open, proc_get_status

五. 重启php-fpm, httpd
service php-fpm restart
service httpd restart

六. 安装elasticsearch (magento必装插件)
【 首先安装 JDK 环境 】
1. 本机是否已经安装,ElasticSearch 最低支持 jdk 1.7
yum list installed | grep java

2. 查看 yum 库中的 java 安装包
yum list java*

3. 安装 java-1.8.0
yum install -y java-1.8.0-openjdk

4. 安装完成后查看 java 版本
java -version (出现以下信息则安装成功)
//openjdk version "1.8.0_212"
//OpenJDK Runtime Environment (build 1.8.0_212-b04)
//OpenJDK 64-Bit Server VM (build 25.212-b04, mixed mode)
------------------------------------------------------------
【 安装 elasticsearch(当前为 7.2)】

5. 下载并安装公共签名密钥
rpm --import https://artifacts.elastic.co/GPG-KEY-elasticsearch

6. 创建 yum 源文件
vim /etc/yum.repos.d/elasticsearch.repo

把下面这段粘上去进行保存即可
[elasticsearch-7.x]
name=Elasticsearch repository for 7.x packages
baseurl=https://artifacts.elastic.co/packages/7.x/yum
gpgcheck=1
gpgkey=https://artifacts.elastic.co/GPG-KEY-elasticsearch
enabled=1
autorefresh=1
type=rpm-md

7. 安装 elasticsearch
yum install -y elasticsearch

8. 配置 elasticsearch

8.1 配置文件都在 /etc/elasticsearch/ 目录下
vim /etc/elasticsearch/elasticsearch.yml

**集群名称
cluster.name: jhxxb
节点名称
node.name: node-1
数据文件与日志文件存放目录
path.data: /var/lib/elasticsearch
path.logs: /var/log/elasticsearch
网络设置
network.host: 0.0.0.0 //改为127.0.0.1 或者 localhost
http.port: 9200
集群设置
cluster.initial_master_nodes: ["node-1"]**

8.2 修改配置中目录的用户与用户组,不然无法启动
chown -R elasticsearch:elasticsearch /var/lib/elasticsearch
chown -R elasticsearch:elasticsearch /var/log/elasticsearch

【 启动 elasticsearch 】

9. 启动
systemctl start elasticsearch.service

10. 开机自启
systemctl enable elasticsearch.service

11. 查看状态
systemctl status elasticsearch.service

七. 创建新站点信息
./vhost.sh
./pureftpd_vhost.sh

八. 创建新站点数据库
通过phpMyAdmin完成建库

九. 为数据库添加用户权限
mysql -uroot -p
提示输入密码进入
执行:(换成你自己的数据库名,用户,密码)
MySQL [(none)]> grant all privileges on db_name.* to db_user@'%' identified by 'db_pass';
MySQL [(none)]> flush privileges;
MySQL [(none)]> exit;

十. 将magento下载的2.4.3数据样本上传到站点目录下面进行解压
tar -zxvf magento*******.tar.gz

十一. 给目录相应的用户组及权限, 根目录下面执行
chown -R www *
chown -R :www *

十二. 进入站点目录执行以下安装命令:
php bin/magento setup:install --base-url=https://www.域名.com/ --db-host=127.0.0.1 --db-name=数据库名 --db-user=数据库用户 --db-password=数据库密码 --admin-firstname=Admin --admin-lastname=User --admin-user=admin --admin-password=后台登陆密码 --language=en_US --currency=USD --timezone=America/Chicago --use-rewrites=1 --backend-frontname=后台名称 --search-engine=elasticsearch7 --elasticsearch-host=localhost --elasticsearch-port=9200

十三. 关闭双重验证模块
php bin/magento module:disable Magento_TwoFactorAuth

十四. 上传useful_commands.sh(由群里的大佬提示)文件到根目录下面执行一下
sh useful_commands.sh

sh文件内容如下:
find . -type f -exec chmod 644 {} \;
find . -type d -exec chmod 755 {} \;
find ./var -type d -exec chmod 777 {} \;
find ./pub/media -type d -exec chmod 777 {} \;
find ./pub/static -type d -exec chmod 777 {} \;
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento indexer:reindex
php bin/magento cache:clean
php bin/magento setup:static-content:deploy -f
php bin/magento cache:flush

十五, 登陆后台 大功告成。

events事件在magento2里是核心内容,用于监听某个事件来执行相关操作。类似于jquery的on或者wp的钩子hook。

在修改核心代码逻辑时非常方便 也不会产生模块间的冲突。

 

events监听例子

比如监听下单成功后事件:

假设你的插件是 Vendor/Extension

1,在events.xml里定义

在 app/code/Vendor/Extension/etc/ 创建events.xml文件。

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="sales_order_place_after">
        <observer name="place_order_after" instance="Vendor\Extension\Observer\Orderplaceafter"/>
    </event>
</config>

2,实现处理逻辑方法

app/code/Vendor/Extension/Observer/里创建Orderplaceafter.php

<?php

namespace Vendor\Extension\Observer;

use Magento\Framework\Event\ObserverInterface;
use Psr\Log\LoggerInterface;

class Orderplaceafter implements ObserverInterface
{
    protected $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        try {
            $order = $observer->getEvent()->getOrder();
            //在这里做你想做的事
        } catch (\Exception $e) {
            $this->logger->info($e->getMessage());
        }
    }
}

 

 

常用的events事件如下

具体event代表什么意思,需要你自己去分析,等用到的时候就会懂了。

 

文件位置 Event事件名
vendor/magento/module-backend/Block/System/Store/Edit/AbstractForm.php adminhtml_store_edit_form_prepare_form
vendor/magento/module-backend/Block/Template.php adminhtml_block_html_before
vendor/magento/module-backend/Block/Widget/Grid.php backend_block_widget_grid_prepare_grid_before
vendor/magento/module-backend/Console/Command/CacheCleanCommand.php adminhtml_cache_flush_system
vendor/magento/module-backend/Console/Command/CacheFlushCommand.php adminhtml_cache_flush_all
vendor/magento/module-backend/Controller/Adminhtml/Cache/CleanImages.php clean_catalog_images_cache_after
vendor/magento/module-backend/Controller/Adminhtml/Cache/CleanMedia.php clean_media_cache_after
vendor/magento/module-backend/Controller/Adminhtml/Cache/CleanStaticFiles.php clean_static_files_cache_after
vendor/magento/module-backend/Controller/Adminhtml/Cache/FlushAll.php adminhtml_cache_flush_all
vendor/magento/module-backend/Controller/Adminhtml/System/Design/Save.php theme_save_after
vendor/magento/module-backend/Controller/Adminhtml/System/Store/DeleteStorePost.php store_delete
vendor/magento/module-backend/Controller/Adminhtml/System/Store/Save.php store_edit
vendor/magento/module-backend/Controller/Adminhtml/System/Store/Save.php store_add
vendor/magento/module-backend/Controller/Adminhtml/System/Store/Save.php store_group_save
vendor/magento/module-backend/Model/Auth.php backend_auth_user_login_success
vendor/magento/module-backend/Model/Auth.php backend_auth_user_login_failed
vendor/magento/module-bundle/Block/Catalog/Product/View/Type/Bundle.php catalog_product_option_price_configuration_after
vendor/magento/module-bundle/Model/Product/Price.php prepare_catalog_product_collection_prices
vendor/magento/module-bundle/Model/Product/Price.php catalog_product_get_final_price
vendor/magento/module-bundle/Model/ResourceModel/Indexer/Price.php catalog_product_prepare_index_select
vendor/magento/module-catalog-import-export/Model/Import/Product.php catalog_product_import_bunch_delete_commit_before
vendor/magento/module-catalog-import-export/Model/Import/Product.php catalog_product_import_bunch_delete_commit_after
vendor/magento/module-catalog-import-export/Model/Import/Product.php catalog_product_import_finish_before
vendor/magento/module-catalog-import-export/Model/Import/Product.php catalog_product_import_bunch_save_after
vendor/magento/module-catalog-rule/Controller/Adminhtml/Promo/Catalog/Index.php catalogrule_dirty_notice
vendor/magento/module-catalog-rule/Controller/Adminhtml/Promo/Catalog/Save.php adminhtml_controller_catalogrule_prepare_save
vendor/magento/module-catalog-search/Model/Indexer/Fulltext/Action/DataProvider.php catelogsearch_searchable_attributes_load_after
vendor/magento/module-catalog-search/Model/ResourceModel/Fulltext.php catalogsearch_reset_search_result
vendor/magento/module-catalog/Block/Adminhtml/Category/Tree.php adminhtml_catalog_category_tree_is_moveable
vendor/magento/module-catalog/Block/Adminhtml/Category/Tree.php adminhtml_catalog_category_tree_can_add_root_category
vendor/magento/module-catalog/Block/Adminhtml/Category/Tree.php adminhtml_catalog_category_tree_can_add_sub_category
vendor/magento/module-catalog/Block/Adminhtml/Product/Attribute/Edit/Tab/Advanced.php product_attribute_form_build
vendor/magento/module-catalog/Block/Adminhtml/Product/Attribute/Edit/Tab/Front.php product_attribute_form_build_front_tab
vendor/magento/module-catalog/Block/Adminhtml/Product/Attribute/Edit/Tab/Front.php adminhtml_catalog_product_attribute_edit_frontend_prepare_form
vendor/magento/module-catalog/Block/Adminhtml/Product/Attribute/Edit/Tab/Main.php adminhtml_product_attribute_types
vendor/magento/module-catalog/Block/Adminhtml/Product/Attribute/Edit/Tab/Main.php product_attribute_form_build_main_tab
/vendor/magento/module-catalog/Block/Adminhtml/Product/Attribute/Grid.php product_attribute_grid_build
vendor/magento/module-catalog/Block/Adminhtml/Product/Attribute/NewAttribute/Product/Attributes.php adminhtml_catalog_product_edit_prepare_form
vendor/magento/module-catalog/Block/Adminhtml/Product/Attribute/NewAttribute/Product/Attributes.php adminhtml_catalog_product_edit_element_types
vendor/magento/module-catalog/Block/Adminhtml/Product/Attribute/Set/Main.php adminhtml_catalog_product_attribute_set_main_html_before
vendor/magento/module-catalog/Block/Adminhtml/Product/Attribute/Set/Toolbar/Main.php adminhtml_catalog_product_attribute_set_toolbar_main_html_before
vendor/magento/module-catalog/Block/Adminhtml/Product/Edit/Action/Attribute/Tab/Attributes.php adminhtml_catalog_product_form_prepare_excluded_field_list
vendor/magento/module-catalog/Block/Adminhtml/Product/Edit/Tab/Attributes.php adminhtml_catalog_product_edit_tab_attributes_create_html_before
vendor/magento/module-catalog/Block/Adminhtml/Product/Grid.php adminhtml_catalog_product_grid_prepare_massaction
vendor/magento/module-catalog/Block/Adminhtml/Product/Helper/Form/Gallery/Content.php catalog_product_gallery_prepare_layout
vendor/magento/module-catalog/Block/Product/AbstractProduct.php catalog_block_product_status_display
vendor/magento/module-catalog/Block/Product/ListProduct.php catalog_block_product_list_collection
vendor/magento/module-catalog/Block/Product/ProductList/Upsell.php catalog_product_upsell
vendor/magento/module-catalog/Block/Product/View.php catalog_product_view_config
vendor/magento/module-catalog/Block/Rss/Category.php rss_catalog_category_xml_callback
vendor/magento/module-catalog/Block/Rss/Product/NewProducts.php rss_catalog_new_xml_callback
vendor/magento/module-catalog/Block/Rss/Product/Special.php rss_catalog_special_xml_callback
vendor/magento/module-catalog/Block/ShortcutButtons.php shortcut_buttons_container
vendor/magento/module-catalog/Controller/Adminhtml/Category.php category_prepare_ajax_response
vendor/magento/module-catalog/Controller/Adminhtml/Category/Delete.php catalog_controller_category_delete
vendor/magento/module-catalog/Controller/Adminhtml/Category/Save.php catalog_category_prepare_save
vendor/magento/module-catalog/Controller/Adminhtml/Product/Action/Attribute/Save.php catalog_product_to_website_change
vendor/magento/module-catalog/Controller/Adminhtml/Product/Edit.php catalog_product_edit_action
vendor/magento/module-catalog/Controller/Adminhtml/Product/Gallery/Upload.php catalog_product_gallery_upload_image_after
vendor/magento/module-catalog/Controller/Adminhtml/Product/NewAction.php catalog_product_new_action
vendor/magento/module-catalog/Controller/Adminhtml/Product/Save.php controller_action_catalog_product_save_entity_after
vendor/magento/module-catalog/Controller/Category/View.php catalog_controller_category_init_after
vendor/magento/module-catalog/Controller/Product/Compare/Add.php catalog_product_compare_add_product
vendor/magento/module-catalog/Controller/Product/Compare/Remove.php catalog_product_compare_remove_product
vendor/magento/module-catalog/Helper/Product.php catalog_controller_product_init_before
vendor/magento/module-catalog/Helper/Product.php catalog_controller_product_init_after
vendor/magento/module-catalog/Helper/Product/View.php catalog_controller_product_view
vendor/magento/module-catalog/Model/Category.php _move_before
vendor/magento/module-catalog/Model/Category.php _move_after
vendor/magento/module-catalog/Model/Category.php category_move
vendor/magento/module-catalog/Model/Product.php _validate_before
vendor/magento/module-catalog/Model/Product.php _validate_after
vendor/magento/module-catalog/Model/Product.php catalog_product_is_salable_before
vendor/magento/module-catalog/Model/Product.php catalog_product_is_salable_after
vendor/magento/module-catalog/Model/Product/Action.php catalog_product_attribute_update_before
vendor/magento/module-catalog/Model/Product/Attribute/Source/Inputtype.php adminhtml_product_attribute_types
vendor/magento/module-catalog/Model/Product/Type/AbstractType.php catalog_product_type_prepare_%s_options
vendor/magento/module-catalog/Model/ResourceModel/Category.php catalog_category_change_products
vendor/magento/module-catalog/Model/ResourceModel/Category.php catalog_category_delete_after_done
vendor/magento/module-catalog/Model/ResourceModel/Category/Collection.php _add_is_active_filter
vendor/magento/module-catalog/Model/ResourceModel/Category/Flat.php catalog_category_tree_init_inactive_category_ids
vendor/magento/module-catalog/Model/ResourceModel/Category/Flat.php catalog_category_flat_loadnodes_before
vendor/magento/module-catalog/Model/ResourceModel/Category/Tree.php catalog_category_tree_init_inactive_category_ids
vendor/magento/module-catalog/Model/ResourceModel/Product.php catalog_product_delete_after_done
vendor/magento/module-catalog/Model/ResourceModel/Product/Collection.php catalog_prepare_price_select
vendor/magento/module-catalog/Model/ResourceModel/Product/Collection.php catalog_product_collection_load_after
vendor/magento/module-catalog/Model/ResourceModel/Product/Collection.php catalog_product_collection_before_add_count_to_categories
vendor/magento/module-catalog/Model/ResourceModel/Product/Collection.php catalog_product_collection_apply_limitations_after
vendor/magento/module-catalog/Model/ResourceModel/Product/Compare/Item/Collection.php catalog_product_compare_item_collection_clear
vendor/magento/module-catalog/Model/ResourceModel/Product/Indexer/Eav/AbstractEav.php prepare_catalog_product_index_select
vendor/magento/module-catalog/Model/Rss/Product/NotifyStock.php rss_catalog_notify_stock_collection_select
vendor/magento/module-catalog/etc/events.xml magento_catalog_api_data_productinterface_save_before
vendor/magento/module-catalog/etc/events.xml magento_catalog_api_data_productinterface_save_after
vendor/magento/module-catalog/etc/events.xml magento_catalog_api_data_productinterface_delete_before
vendor/magento/module-catalog/etc/events.xml magento_catalog_api_data_productinterface_delete_after
vendor/magento/module-catalog/etc/events.xml magento_catalog_api_data_productinterface_load_after
vendor/magento/module-catalog/etc/events.xml magento_catalog_api_data_categoryinterface_save_before
vendor/magento/module-catalog/etc/events.xml magento_catalog_api_data_categoryinterface_save_after
vendor/magento/module-catalog/etc/events.xml magento_catalog_api_data_categoryinterface_delete_before
vendor/magento/module-catalog/etc/events.xml magento_catalog_api_data_categoryinterface_delete_after
vendor/magento/module-catalog/etc/events.xml magento_catalog_api_data_categoryinterface_load_after
vendor/magento/module-catalog/etc/events.xml magento_catalog_api_data_categorytreeinterface_save_before
vendor/magento/module-catalog/etc/events.xml magento_catalog_api_data_categorytreeinterface_save_after
vendor/magento/module-catalog/etc/events.xml magento_catalog_api_data_categorytreeinterface_delete_before
vendor/magento/module-catalog/etc/events.xml magento_catalog_api_data_categorytreeinterface_delete_after
vendor/magento/module-catalog/etc/events.xml magento_catalog_api_data_categorytreeinterface_load_after
vendor/magento/module-catalog/etc/events.xml admin_system_config_changed_section_catalog
vendor/magento/module-catalog/etc/events.xml store_save_after
vendor/magento/module-catalog-inventory/etc/events.xml catalog_product_load_after
vendor/magento/module-catalog-inventory/etc/events.xml catalog_product_save_before
vendor/magento/module-catalog-inventory/etc/events.xml catalog_product_save_after
vendor/magento/module-catalog-inventory/etc/events.xml admin_system_config_changed_section_cataloginventory
vendor/magento/module-catalog-inventory/etc/events.xml sales_quote_item_collection_products_after_load
vendor/magento/module-catalog-url-rewrite/etc/events.xml catalog_category_save_after
vendor/magento/module-catalog-url-rewrite/etc/events.xml catalog_product_import_bunch_delete_after
vendor/magento/module-catalog-url-rewrite/etc/events.xml catalog_product_delete_before
vendor/magento/module-catalog-url-rewrite/etc/events.xml catalog_category_save_before
vendor/magento/module-catalog-url-rewrite/etc/events.xml catalog_category_move_after
vendor/magento/module-config/Block/System/Config/Form/Fieldset/Modules/DisableOutput.php adminhtml_system_config_advanced_disableoutput_render_before
vendor/magento/module-config/Model/Config.php admin_system_config_changed_section_{$this->getSection()}
vendor/magento/module-config/etc/admihtml/events.xml admin_system_config_changed_section_admin
vendor/magento/module-configurable-product/Model/Product/Validator/Plugin.php catalog_product_validate_variations_before
vendor/magento/module-cookie/Controller/Index/NoCookies.php controller_action_nocookies
vendor/magento/module-currency-symbol/Model/System/Currencysymbol.php admin_system_config_changed_section_currency_before_reinit
vendor/magento/module-currency-symbol/Model/System/Currencysymbol.php admin_system_config_changed_section_currency
vendor/magento/module-customer/etc/events.xml customer_address_save_before
vendor/magento/module-customer/etc/events.xml customer_address_save_after
vendor/magento/module-customer/etc/events.xml sales_quote_save_after
vendor/magento/module-gift-message/Block/Message/Inline.php gift_options_prepare_items
endor/magento/module-customer/Controller/Account/CreatePost.php customer_register_success
vendor/magento/module-customer/Controller/Account/EditPost.php customer_account_edited
vendor/magento/module-customer/Controller/Adminhtml/Index/Save.php adminhtml_customer_prepare_save
vendor/magento/module-customer/Controller/Adminhtml/Index/Save.php adminhtml_customer_save_after
vendor/magento/module-customer/Model/AccountManagement.php customer_customer_authenticated
vendor/magento/module-customer/Model/AccountManagement.php customer_data_object_login
vendor/magento/module-customer/Model/Address/AbstractAddress.php customer_address_format
vendor/magento/module-customer/Model/ResourceModel/CustomerRepository.php customer_save_after_data_object
vendor/magento/module-customer/Model/Session.php customer_session_init
vendor/magento/module-customer/Model/Session.php customer_login
vendor/magento/module-customer/Model/Session.php customer_data_object_login
vendor/magento/module-customer/Model/Session.php customer_logout
vendor/magento/module-customer/Model/Visitor.php visitor_init
vendor/magento/module-customer/Model/Visitor.php visitor_activity_save
vendor/magento/module-downloadable/etc/events.xml sales_order_item_save_commit_after
vendor/magento/module-downloadable/etc/events.xml sales_order_save_commit_after
vendor/magento/module-eav/Block/Adminhtml/Attribute/Edit/Main/AbstractMain.php adminhtml_block_eav_attribute_edit_form_init
vendor/magento/module-eav/Model/Entity/Collection/AbstractCollection.php eav_collection_abstract_load_before
vendor/magento/module-customer/Block/Adminhtml/Edit/Tab/Carts.php
adminhtml_block_html_before
vendor/magento/module-google-optimizer/etc/events.xml cms_page_save_after
vendor/magento/module-google-optimizer/etc/events.xml cms_page_delete_after
vendor/magento/module-grouped-product/Model/ResourceModel/Product/Indexer/Price/Grouped.php catalog_product_prepare_index_select
vendor/magento/module-indexer/Model/Processor/CleanCache.php clean_cache_after_reindex
vendor/magento/module-multishipping/Controller/Checkout/ShippingPost.php checkout_controller_multishipping_shipping_post
vendor/magento/module-multishipping/Controller/Checkout/Success.php multishipping_checkout_controller_success_action
vendor/magento/module-multishipping/Model/Checkout/Type/Multishipping.php checkout_type_multishipping_set_shipping_items
vendor/magento/module-multishipping/Model/Checkout/Type/Multishipping.php checkout_type_multishipping_create_orders_single
vendor/magento/module-multishipping/Model/Checkout/Type/Multishipping.php checkout_submit_all_after
vendor/magento/module-multishipping/Model/Checkout/Type/Multishipping.php checkout_multishipping_refund_all
vendor/magento/module-newsletter/Model/Subscriber.php newsletter_subscriber_save_commit_after
vendor/magento/module-newsletter/Model/Subscriber.php newsletter_subscriber_save_commit_before
vendor/magento/module-offline-payments/etc/events.xml sales_order_payment_save_before
vendor/magento/module-page-cache/Model/Cache/Type.php adminhtml_cache_refresh_type
vendor/magento/module-page-cache/Model/Layout/DepersonalizePlugin.php depersonalize_clear_session
vendor/magento/module-persistent/Controller/Index/UnsetCookie.php persistent_session_expired
vendor/magento/module-payment/Model/Cart.php payment_cart_collect_items_and_amounts
vendor/magento/module-payment/Model/Method/AbstractMethod.php payment_method_is_active
vendor/magento/module-payment/Model/Method/AbstractMethod.php payment_method_assign_data_{PAYMENT_CODE}
vendor/magento/module-payment/Model/Method/AbstractMethod.php payment_method_assign_data
vendor/magento/module-payment/etc/events.xml sales_order_status_unassign
vendor/magento/module-payment/Block/Form/Cc.php
payment_form_block_to_html_before
vendor/magento/module-cms/etc/events.xml magento_cms_api_data_blockinterface_save_before
vendor/magento/module-cms/etc/events.xml magento_cms_api_data_blockinterface_save_after
vendor/magento/module-cms/etc/events.xml magento_cms_api_data_blockinterface_delete_before
vendor/magento/module-cms/etc/events.xml magento_cms_api_data_blockinterface_delete_after
vendor/magento/module-cms/etc/events.xml magento_cms_api_data_blockinterface_load_after
vendor/magento/module-cms/etc/events.xml magento_cms_api_data_pageinterface_save_before
vendor/magento/module-cms/etc/events.xml magento_cms_api_data_pageinterface_save_after
vendor/magento/module-cms/etc/events.xml magento_cms_api_data_pageinterface_delete_before
vendor/magento/module-cms/etc/events.xml magento_cms_api_data_pageinterface_delete_after
vendor/magento/module-cms/etc/events.xml magento_cms_api_data_pageinterface_load_after
vendor/magento/module-cms/Controller/Adminhtml/Page/Delete.php adminhtml_cmspage_on_delete
vendor/magento/module-cms/Controller/Adminhtml/Page/Save.php cms_page_prepare_save
vendor/magento/module-cms/Controller/Router.php cms_controller_router_match_before
vendor/magento/module-cms/Helper/Page.php cms_page_render
vendor/magento/module-cms/Helper/Wysiwyg/Images.php cms_wysiwyg_images_static_urls_allowed
vendor/magento/module-quote/Model/Quote/Address/ToOrder.php sales_convert_quote_to_order
vendor/magento/module-quote/Model/Cart/Totals/ItemConverter.php items_additional_data
vendor/magento/module-quote/Model/Quote.php sales_quote_remove_item
vendor/magento/module-quote/Model/Quote.php sales_quote_add_item
vendor/magento/module-quote/Model/Quote.php sales_quote_product_add_after
vendor/magento/module-quote/Model/Quote.php sales_quote_merge_before
vendor/magento/module-quote/Model/Quote.php sales_quote_merge_after
vendor/magento/module-quote/Model/Quote/Item.php sales_quote_item_set_product
vendor/magento/module-quote/Model/Quote/Item.php sales_quote_item_qty_set_after
vendor/magento/module-quote/Model/Quote/Payment.php sales_quote_payment_import_data_before
vendor/magento/module-quote/Model/Quote/TotalsCollector.php sales_quote_collect_totals_before
vendor/magento/module-quote/Model/Quote/TotalsCollector.php sales_quote_collect_totals_after
vendor/magento/module-quote/Model/Quote/TotalsCollector.php sales_quote_address_collect_totals_after
vendor/magento/module-quote/Model/QuoteManagement.php checkout_submit_before
vendor/magento/module-quote/Model/QuoteManagement.php checkout_submit_all_after
vendor/magento/module-quote/Model/QuoteManagement.php sales_model_service_quote_submit_before
vendor/magento/module-quote/Model/QuoteManagement.php sales_model_service_quote_submit_success
vendor/magento/module-quote/Model/QuoteManagement.php sales_model_service_quote_submit_failure
vendor/magento/module-quote/Model/ResourceModel/Quote/Address/Collection.php sales_quote_address_collection_load_after
vendor/magento/module-reports/etc/frontend/events.xml wishlist_add_product
vendor/magento/module-reports/etc/frontend/events.xml sales_quote_item_save_before
vendor/magento/module-reports/etc/frontend/events.xml sales_quote_item_save_after
vendor/magento/module-reports/Block/Adminhtml/Grid.php adminhtml_widget_grid_filter_collection
vendor/magento/module-reports/Model/ResourceModel/Order/Collection.php sales_prepare_amount_expression
vendor/magento/module-review/Controller/Product.php review_controller_product_init_before
vendor/magento/module-review/Controller/Product.php review_controller_product_init
vendor/magento/module-review/Model/ResourceModel/Rating/Collection.php rating_rating_collection_load_before
vendor/magento/module-review/Model/ResourceModel/Review/Collection.php review_review_collection_load_before
vendor/magento/module-review/Model/Rss.php rss_catalog_review_collection_select
vendor/magento/module-sales/Block/Adminhtml/Reorder/Renderer/Action.php adminhtml_customer_orders_add_action_renderer
vendor/magento/module-sales/Model/Order.php sales_order_load_after
vendor/magento/module-sales/Model/Order.php sales_order_save_before
vendor/magento/module-sales/Model/Order.php sales_order_save_after
vendor/magento/module-sales/Model/Order.php sales_order_delete_before
vendor/magento/module-sales/Model/Order.php sales_order_invoice_load_after
vendor/magento/module-sales/Model/Order.php sales_order_invoice_load_before
vendor/magento/module-sales/Model/Order.php sales_order_shipment_load_after
vendor/magento/module-sales/Model/Order.php sales_order_shipment_load_before
vendor/magento/module-sales/Model/Order.php sales_order_creditmemo_load_after
vendor/magento/module-sales/Model/Order.php sales_order_creditmemo_load_before
vendor/magento/module-sales/Model/Order.php sales_order_grid_collection_load_before
vendor/magento/module-sales/Observer/GridSyncInsertObserver.php sales_order_invoice_save_after
vendor/magento/module-sales/Observer/GridSyncInsertObserver.php sales_order_shipment_save_after
vendor/magento/module-sales/Observer/GridSyncInsertObserver.php sales_order_creditmemo_save_after
vendor/magento/module-sales/etc/adminhtml/events.xml catalogrule_before_apply
vendor/magento/module-sales/etc/adminhtml/events.xml catalogrule_after_apply
vendor/magento/module-sales/etc/events.xml sales_order_process_relation
vendor/magento/module-sales/etc/events.xml sales_order_invoice_process_relation
vendor/magento/module-sales/etc/events.xml sales_order_shipment_process_relation
vendor/magento/module-sales/etc/events.xml sales_order_creditmemo_process_relation
vendor/magento/module-sales/etc/events.xml sales_order_delete_after
vendor/magento/module-sales/etc/events.xml sales_order_invoice_delete_after
vendor/magento/module-sales/etc/events.xml sales_order_shipment_delete_after
vendor/magento/module-sales/etc/events.xml sales_order_creditmemo_delete_after
vendor/magento/module-sales/etc/events.xml admin_sales_order_address_update
vendor/magento/module-sales/etc/events.xml sales_order_delete_after
vendor/magento/module-sales/etc/events.xml sales_order_invoice_delete_after
vendor/magento/module-sales/etc/events.xml sales_order_shipment_delete_after
vendor/magento/module-sales/etc/events.xml sales_order_creditmemo_delete_after
vendor/magento/module-sales/etc/events.xml sales_order_creditmemo_process_relation
vendor/magento/module-sales/etc/events.xml config_data_dev_grid_async_indexing_disabled
vendor/magento/module-sales/etc/events.xml config_data_sales_email_general_async_sending_disabled
vendor/magento/module-sales-rule/Block/Adminhtml/Promo/Quote/Edit/Tab/Actions.php adminhtml_block_salesrule_actions_prepareform
vendor/magento/module-sales-rule/Model/Quote/Discount.php sales_quote_address_discount_item
vendor/magento/module-sales-rule/Model/Rule.php salesrule_rule_get_coupon_types
vendor/magento/module-sales-rule/Model/Rule/Condition/Combine.php salesrule_rule_condition_combine
vendor/magento/module-sales/Controller/Adminhtml/Order/Create.php adminhtml_sales_order_create_process_data_before
vendor/magento/module-sales/Controller/Adminhtml/Order/Create.php adminhtml_sales_order_create_process_item_before
vendor/magento/module-sales/Controller/Adminhtml/Order/Create.php adminhtml_sales_order_create_process_item_after
vendor/magento/module-sales/Controller/Adminhtml/Order/Create.php adminhtml_sales_order_create_process_data
vendor/magento/module-sales/Controller/Adminhtml/Order/CreditmemoLoader.php adminhtml_sales_order_creditmemo_register_before
vendor/magento/module-sales/Model/AdminOrder/Create.php sales_convert_order_to_quote
vendor/magento/module-sales/Model/AdminOrder/Create.php sales_convert_order_item_to_quote_item
vendor/magento/module-sales/Model/AdminOrder/Create.php checkout_submit_all_after
vendor/magento/module-sales/Model/Order.php sales_order_place_before
vendor/magento/module-sales/Model/Order.php sales_order_place_after
vendor/magento/module-sales/Model/Order.php order_cancel_after
vendor/magento/module-sales/Model/Order/Creditmemo/RefundOperation.php sales_order_creditmemo_refund
vendor/magento/module-sales/Model/Order/Invoice.php sales_order_invoice_pay
vendor/magento/module-sales/Model/Order/Invoice.php sales_order_invoice_cancel
vendor/magento/module-sales/Model/Order/Invoice/PayOperation.php sales_order_invoice_register
vendor/magento/module-sales/Model/Order/Item.php sales_order_item_cancel
vendor/magento/module-sales/Model/Order/Payment.php sales_order_payment_place_start
vendor/magento/module-sales/Model/Order/Payment.php sales_order_payment_place_end
vendor/magento/module-sales/Model/Order/Payment.php sales_order_payment_pay
vendor/magento/module-sales/Model/Order/Payment.php sales_order_payment_cancel_invoice
vendor/magento/module-sales/Model/Order/Payment.php sales_order_payment_void
vendor/magento/module-sales/Model/Order/Payment.php sales_order_payment_refund
vendor/magento/module-sales/Model/Order/Payment.php sales_order_payment_cancel_creditmemo
vendor/magento/module-sales/Model/Order/Payment.php sales_order_payment_cancel
vendor/magento/module-sales/Model/ResourceModel/Sale/Collection.php sales_sale_collection_query_before
vendor/magento/module-sales/Model/Rss/NewOrder.php rss_order_new_collection_select
vendor/magento/module-sales/Model/Service/CreditmemoService.php sales_order_creditmemo_cancel
vendor/magento/module-sales/Model/Order/Email/Sender/OrderSender.php email_order_set_template_vars_before
vendor/magento/module-sales/Model/Service/OrderService.php sales_order_state_change_before
vendor/magento/module-sales/Model/Order/Payment/Operations/CaptureOperation.php sales_order_payment_capture
vendor/magento/module-sales/Model/Order/Creditmemo/Sender/EmailSender.php email_creditmemo_set_template_vars_before
vendor/magento/module-sales/Model/Order/Creditmemo/Sender/EmailSender.php email_creditmemo_comment_set_template_vars_befor
vendor/magento/module-sales/Model/Order/Email/Sender/InvoiceCommentSender.php email_invoice_comment_set_template_vars_before
vendor/magento/module-sales/Model/Order/Email/Sender/InvoiceCommentSender.php email_invoice_set_template_vars_before
vendor/magento/module-sales/Model/Order/Email/Sender/InvoiceCommentSender.php email_order_comment_set_template_vars_before
vendor/magento/module-sales/Model/Order/Email/Sender/ShipmentCommentSender.php email_shipment_comment_set_template_vars_before
vendor/magento/module-sales/Model/Order/Email/Sender/ShipmentSender.php email_shipment_set_template_vars_before
vendor/magento/module-signifyd/etc/events.xml paypal_express_place_order_success
vendor/magento/module-search/Controller/Adminhtml/Term/Report.php on_view_report
vendor/magento/module-send-friend/Controller/Product/Send.php sendfriend_product
vendor/magento/module-store/Model/Address/Renderer.php store_address_format
vendor/magento/module-tax/Model/Calculation.php tax_rate_data_fetch
vendor/magento/module-tax/Model/Calculation/Rate.php tax_settings_change_after
vendor/magento/module-theme/etc/events.xml theme_delete_before
vendor/magento/module-theme/etc/events.xml theme_save_after
vendor/magento/module-user/Block/Role.php permissions_role_html_before
vendor/magento/module-wishlist/Block/Customer/Wishlist/Item/Options.php product_option_renderer_init
vendor/magento/module-wishlist/Controller/Index/Send.php wishlist_share
vendor/magento/module-vault/etc/events.xml payment_method_assign_data
vendor/magento/module-wishlist/Model/Rss/Wishlist.php rss_wishlist_xml_callback
vendor/magento/module-wishlist/Model/Wishlist.php wishlist_add_item
vendor/magento/module-wishlist/Model/Wishlist.php wishlist_product_add_after
vendor/magento/module-vault/etc/events.xml sales_order_payment_save_after
vendor/magento/module-wishlist/Helper/Data.php wishlist_items_renewed
vendor/magento/module-vault/etc/events.xml payment_method_assign_data_vault
vendor/magento/module-checkout/Controller/Cart/Add.php checkout_cart_add_product_complete
vendor/magento/module-checkout/Controller/Cart/UpdateItemOptions.php checkout_cart_update_item_complete
vendor/magento/module-checkout/Controller/Onepage/SaveOrder.php checkout_controller_onepage_saveOrder
vendor/magento/module-checkout/Controller/Onepage/Success.php checkout_onepage_controller_success_action
vendor/magento/module-checkout/Helper/Data.php checkout_allow_guest
vendor/magento/module-checkout/Model/Cart.php checkout_cart_product_add_after
vendor/magento/module-checkout/Model/Cart.php checkout_cart_update_items_before
vendor/magento/module-checkout/Model/Cart.php checkout_cart_update_items_after
vendor/magento/module-checkout/Model/Cart.php checkout_cart_save_before
vendor/magento/module-checkout/Model/Cart.php checkout_cart_save_after
vendor/magento/module-checkout/Model/Cart.php checkout_cart_product_update_after
vendor/magento/module-checkout/Model/Session.php custom_quote_process
vendor/magento/module-checkout/Model/Session.php checkout_quote_init
vendor/magento/module-checkout/Model/Session.php load_customer_quote_before
vendor/magento/module-checkout/Model/Session.php checkout_quote_destroy
vendor/magento/module-checkout/Model/Session.php restore_quote
vendor/magento/module-checkout/Model/Type/Onepage.php checkout_type_onepage_save_order_after
vendor/magento/module-checkout/Model/Type/Onepage.php checkout_submit_all_after
vendor/magento/framework/App/View.php controller_action_layout_render_before
vendor/magento/framework/App/Action/Action.php controller_action_postdispatch
vendor/magento/framework/App/Http.php controller_front_send_response_before
vendor/magento/framework/App/Action/Action.php
controller_action_predispatch
vendor/magento/framework/Controller/Noroute/Index.php controller_action_noroute
vendor/magento/framework/Data/AbstractSearchResult.php abstract_search_result_load_before
vendor/magento/framework/Data/AbstractSearchResult.php abstract_search_result_load_after
vendor/magento/framework/Locale/Currency.php currency_display_options_forming
vendor/magento/framework/EntityManager/Operation/Create.php entity_manager_save_after
vendor/magento/framework/EntityManager/Operation/Delete.php entity_manager_delete_before
vendor/magento/framework/EntityManager/Operation/Read.php entity_manager_load_before
vendor/magento/framework/EntityManager/Operation/Read.php entity_manager_load_after
vendor/magento/framework/Message/Manager.php session_abstract_add_messages
vendor/magento/framework/EntityManager/Operation/Update.php entity_manager_save_after
vendor/magento/framework/EntityManager/Operation/Create.php
entity_manager_save_before
vendor/magento/framework/Message/Manager.php session_abstract_clear_messages
vendor/magento/framework/EntityManager/Operation/Update.php entity_manager_save_before
vendor/magento/framework/Model/AbstractModel.php model_load_before
vendor/magento/framework/Model/AbstractModel.php model_load_after
vendor/magento/framework/Model/AbstractModel.php model_save_commit_after
vendor/magento/framework/Model/AbstractModel.php model_save_before
vendor/magento/framework/Model/AbstractModel.php model_save_after
vendor/magento/framework/Model/AbstractModel.php model_delete_before
vendor/magento/framework/Model/AbstractModel.php model_delete_after
vendor/magento/framework/Model/AbstractModel.php clean_cache_by_tags
vendor/magento/framework/Model/AbstractModel.php model_delete_commit_after
vendor/magento/framework/Model/ResourceModel/Db/Collection/AbstractCollection.php core_collection_abstract_load_before
vendor/magento/framework/Model/ResourceModel/Db/Collection/AbstractCollection.php core_collection_abstract_load_after
vendor/magento/framework/View/Element/AbstractBlock.php view_block_abstract_to_html_after
vendor/magento/framework/View/Element/Messages.php view_message_block_render_grouped_html_after
vendor/magento/framework/View/Layout.php core_layout_render_element
vendor/magento/framework/View/Layout/Builder.php layout_load_before
vendor/magento/framework/View/Layout/Builder.php layout_generate_blocks_before
vendor/magento/framework/View/Layout/Builder.php layout_generate_blocks_after
vendor/magento/framework/View/Layout/Generator/Block.php core_layout_block_create_after
vendor/magento/framework/View/Result/Layout.php layout_render_before
vendor/magento/framework/View/Result/Layout.php layout_render_before_{frontname}_{foldername}_{controllerfile}
vendor/magento/framework/View/Element/AbstractBlock.php
view_block_abstract_to_html_before

 

本文内容来自QQ群大佬陈伟明(一叶知秋)的学习分享

 

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Aune_Stripe" setup_version="2.1.0">
        <sequence>
            <module name="Magento_Customer"/>
            <module name="Magento_Quote"/>
            <module name="Magento_Payment"/>
            <module name="Magento_Checkout"/>
            <module name="Magento_Vault"/>
        </sequence>
    </module>
</config>

 

主是模块组件的定义

  • name的值 一般是 Vendor_Module 和目录名一致
  • <sequence> 是定义加载顺序 ,特别要重新前某个模块的方法时,就要用到