Table of Contents
1 Background to Introduction
Improved customer convenience and customer satisfaction
Important notifications such as Woocommerce “New Purchase”, “Process Completed”, “Canceled”, etc. can be sent to Line.
This avoids problems such as notifications not being sent to email addresses or being buried in mailboxes and missed, leading to improved customer satisfaction.
Increased Service Recognition and Loyalty
This service is expected to increase awareness of the LINE Official Account and increase loyalty by adding friends to the official account and sending important messages to them.
Since matching is based on phone numbers and can be delivered even to users who have not yet added friends, it can also be used to create an opportunity to add friends.
2 Terms of Use for LINE Notification Messages
Establishment of an official Line account (@line)
LINE’s new business support service, ” LINE Official Account “, is a service that allows you to send information directly to users who have added you as a friend through LINE. It is a generous service that allows you to communicate with users without obtaining their personal information.
Please refer to Line’s official website for details on how to set up this service.
Start using the Messaging API
After opening a ” LINE Official Account”, you can chat with users via Line as usual after setting up the chat mode, but in order to implement automatic notifications after receiving orders from Woocommerce, it is necessary to set up Messaging API.
Please refer to Line’s official website for more details as starting to use Messaging API and obtaining a channel access token are not the main points of this explanation.
3 Conditions for Activating LINE Notifications
Required plug-in for WordPress
Woocommerce, which boasts a 20% share of e-commerce sites worldwide, has become an indispensable part of WordPress.
You will need the LINE Messaging API SDK, which incorporates the Messaging API, but we recommend Line Connect here.
The Line Messaging API is called using a hook action (woocommerce_email_sent) that will send an email notification each time the status of an order changes, from new to completed and even cancelled orders in Woocommerce.
Notification of the issuance of an electronic receipt in an action from the client (user) side
Notification of e-receipts in actions from the administrator side
Implementing the hook action
Use Line Connect here, which has the Messaging API SKD required to send to Line. This plugin has excellent features such as notifications to Line when posting and Line integration in bot mode. Please try it.
add_action('woocommerce_email_sent', 'kure_customize_woocommerce_email_sent', 10, 3);
function kure_customize_woocommerce_email_sent($return, $id, $mailer)
{
// Line Connect & Easy Line login(KURE製) が必須
if (!class_exists('lineconnectMessage') || !function_exists('Esay_line_login')) {
return;
}
$line_messager_class_path = KURE_DIR_CLASS . "kure_customize_line_receipt.php";
if (!file_exists($line_messager_class_path)) {
return;
}
if (!did_action('woocommerce_email_order_details')) {
return;
}
try {
if (!isset($mailer->object) || !($mailer->object instanceof WC_Order)) {
return;
}
$order = $mailer->object;
// 注文のユーザーからLine Idを取得
if (!Esay_line_login()->has_line($order->get_user(), $line_id)) {
return;
}
static $is_sent;
if (isset($is_sent[$line_id]) && $is_sent[$line_id] == $order->get_order_number()) {
// 連続送信しない
return;
}
// メールの送信先が違い、同じオーダーで2回送信されることがある為、重複Line通知を回避
$is_sent[$line_id] = $order->get_order_number();
/** @var kure_customize_line_receipt */
$line_messager = include $line_messager_class_path;
foreach (lineconnect::get_all_channels() as $channel) {
// send_order_roleはKUREがカスタマイズした設定項目
if (empty($channel['send_order_role']) || !in_array($channel['send_order_role'], $line_role_names)) {
// 指定された通知対象か
continue;
}
$error = lineconnectMessage::sendPushMessage($channel, $line_id, $line_messager);
// 一方通行の為、ブロック中のユーザかどうか分からないです。その時、Webhookの配信完了イベントにて送信結果を拾う必要があるが、チャットモードの場合、Webhookが利用できない
// https://developers.line.biz/ja/docs/partner-docs/line-notification-messages/message-sending-complete-webhook-event/#overview-delivery-webhook-event
if ($error["success"]) {
// 一度成功したら、複数回の通知を実施しないよう、中断
break;
}
}
} catch (Throwable $th) {
//すべての例外を無視
}
}
4 Flex Message JSON sent to Messaging API
Template messages that can be sent to the Messaging API side are called Flex Messages. You can freely design it as long as it uses the specified JSON layout.
There are various tools that provide Flex Message design, but since I am a NO-charge kind of person, I tried to create a Flex Message based on Line’s manual.
First, find a receipt-like template from Line Developers Flex Message Simulator and arrange its JSON.
Here is the JSON after the arrangement.
BODY after arrangement JSON
"type": "bubble",
"body": {
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "image",
"url": "{site_logo}",
"align": "start"
},
{
"type": "text",
"text": "{order_status}",
"weight": "bold",
"color": "#1DB446",
"size": "sm",
"align": "end",
"gravity": "center"
}
]
},
{
"type": "text",
"text": "{order_title}",
"weight": "bold",
"size": "xxl",
"margin": "md",
"decoration": "underline",
"action": {
"type": "uri",
"label": "action",
"uri": "{order_link}"
}
},
{
"type": "text",
"text": "{order_address}",
"size": "xs",
"color": "#aaaaaa",
"wrap": true
},
{
"type": "separator",
"margin": "xxl"
},
{
"type": "box",
"layout": "vertical",
"margin": "xxl",
"spacing": "sm",
"contents": [
{order_items},
{
"type": "separator",
"margin": "xxl"
},
{order_total}
]
},
{
"type": "separator",
"margin": "xxl"
},
{
"type": "box",
"layout": "horizontal",
"margin": "md",
"contents": [
{
"type": "text",
"text": "{order_note}",
"size": "xs",
"color": "#aaaaaa",
"wrap": true
}
]
}
]
},
"styles": {
"footer": {
"separator": true
}
}
*”{order_NNN}”: Indicates the keyword for str_replace.
Detail Items (with URL) JSON
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": "{item_title}",
"size": "sm",
"color": "#555555",
"flex": 0,
"action": {
"type": "uri",
"label": "action",
"uri": "{item_link}"
}
},
{
"type": "text",
"text": "{item_value}",
"size": "sm",
"color": "#111111",
"align": "end"
}
]
Detail Items JSON
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": "{item_title}",
"size": "sm",
"color": "#555555",
"flex": 0
},
{
"type": "text",
"text": "{item_value}",
"size": "sm",
"color": "#111111",
"align": "end"
}
]
Arrangement Point
- Show site icon
- Display order status
- Order number is displayed in the header and URL is embedded to redirect to the corresponding order history
- Order details (product list) is automatically generated and URL is embedded to redirect to the relevant product
- Displays the total amount, shipping charges, and payment method as well as the footer field of the woocommerce order history
- Order Note added by the administrator is also displayed.
Here are some of the source codes.
Output of order product details
Generate a string and replace it with “{order_items}” in the BODYJSON.
// 注文商品を出力
foreach ($this->order->get_items() as $item_id => $item) {
if ($item instanceof WC_Order_Item_Product) {
$product = $item->get_product();
$json_items[] = $this->create_items_with_link(
$product->get_name(), // {item_title} 商品名
$product->get_permalink(), // {item_link} 商品へのリダイレクトする為、リンクを埋め込む
$this->order->get_formatted_line_subtotal($item) // {item_value} 値段
);
} else {
// 基本的にProduct以外のItemがないですが、Product Addons & Optionsなどプラグインを導入している場合、該当分岐に入る
$json_items[] = $this->create_items_no_link(
$item->get_name(),
$this->order->get_formatted_line_subtotal($item)
);
}
}
Output the total amount
Generate a string and replace with “{order_total}” in BODYJSON.
$faqurl = $this->get_order_payment_faqurl(); // 決済方法の案内(よくある質問)ページ
// 金額、送料など出力
foreach ($this->order->get_order_item_totals() as $item_id => $item) {
if ($item_id === 'payment_method' && !empty($faqurl)) {
$json_total[] = $this->create_items_with_link(
$item['label'],
$faqurl, // 決済方法へのリダイレクトを埋め込む
$item['value'],
);
} else {
$json_total[] = $this->create_items_no_link(
$item['label'],
$item['value']
);
}
}
Output Notes (Order Notes)
Notes (order notes) can be added on the admin screen of woocommerce’s order edit. There are two types of notes: notes for the administrator and notes for customer notification. Notifications to customers are also output to an electronic receipt.
The notes are to be entered manually, so you can enter any symbols you like. If double-cotation marks or special symbols are included, the JSON string will generate an error. Therefore, they are removed in advance to prevent JSON errors from occurring.
private function get_order_notes()
{
$notes = array();
foreach ($this->order->get_customer_order_notes() as $ext_note) {
if ($ext_note instanceof WP_Comment) {
// 日付 + 内容、wptexturizeにて特殊記号を有効な文字へ変換
$notes[] = date_i18n(get_option('date_format'), strtotime($ext_note->comment_date)) . ' ' . wptexturize($ext_note->comment_content);
}
}
$notes = array_filter(array_map('trim', $notes));
$str_notes = $this->del_specialchars(implode('n', $notes));
if (empty($str_notes)) {
// 空欄だと、Line側でエラーが発生する為、ノートがない場合も内容を設定
$str_notes = '注文メモなし';
}
return $str_notes;
}
private function del_specialchars($text)
{
$text = html_entity_decode(wp_strip_all_tags($text));
// json の 変換でエラーにならないよう、ダブルコーテーションをなくす
$text = str_replace(
['"', "'"],
' ',
$text
);
return $text;
}
5 Conclusion
Line boasts 93 million users in Japan alone. Numerous companies and government agencies also utilize Line to disseminate information to their users. The world is too big to ignore Line. Of course, the same goes for the author.
The author has devoted many years to the development of Krasaba. Thanks to Corona, he spends more time at home. Since 2022, he has been interested in Line + WordPress and continues to challenge himself. I am still a novice, but I would be happy if I can be of help to as many people/developers as possible, even if only in a small way. I will continue to challenge myself, so please look forward to it.
Please log in and leave a comment if you have any questions or suggestions.