Shopifyで問い合わせフォーム送信後に確認メールを送る機能を追加しました。アプリをインストールすれば解決しそうでしたが、ほとんどが何かしら有料だったのでこれくらいなら書いてしまえそうだなと。

まずはshopify側で以下の感じで既存フォームの送信ボタンにid振ってクリックされたら別サーバにPOSTします。

<button id="send_Doc" type="button">送信</button></form>
<script>// <![CDATA[
const btna = document.getElementById("send_Doc");
const form = document.getElementById("form");

btna.addEventListener('click', ()=>{

    const formData = new FormData(form);

    fetch('https://hogehogeo.com/fetch.php', {
        method: 'POST',
        body: formData,
    })
    .then(response =>  response.text())
    .then(data => {
        console.log(data);
    })
    .catch(error => {
    console.log("失敗しました");
    });
});
// ]]></script>

受側のfetch.phpでは、以下の感じ。ただこれだとザルなのでIPアドレスなどで絞り込みます。

<?php
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: X-Requested-With, Origin, X-Csrftoken, Content-Type, Accept");
header("Access-Control-Allow-Methods: POST ");
if($_POST){
    $fullname = filter_input(INPUT_POST, 'fullname');
    $email = filter_input(INPUT_POST, 'email');

    $to = $email;
    $subject = $fullname;
    $message = "テスト";
    $headers = "From: noripurai@hoge.com";
    mb_send_mail($email, $subject, $message, $headers); 
}

?>

javascriptを使って他所のサーバにデータ送るにはクロスドメイン問題をクリアする必要がありました。これさえ対策すれば、後は通常のフォーム作成するだけです。次回は、Shopify内でフォーム送信後にサンクスページの表示を実装してみます。

万屋物産は現在正社員を募集しています。映像制作会社ではありますがShopifyの内部いじり(.Liquid)に興味のある方からのご応募を心よりお待ちしています。