Shopify

世界最大級のクラウド型ECプラットフォーム。包括的なeコマース機能とアプリエコシステムを提供。

CMSeコマースSaaSRuby on RailsLiquidAPIGraphQLREST
ライセンス
Commercial
言語
Ruby on Rails (SaaS)
料金
14日間無料トライアル

CMS

Shopify

概要

Shopifyは、世界最大級のクラウド型ECプラットフォームです。包括的なeコマース機能とアプリエコシステムを提供し、中小企業から大企業まで幅広く利用されています。

詳細

Shopify(ショッピファイ)は、2006年に創業されたカナダ発のクラウド型ECプラットフォームです。Ruby on Railsをベースに構築され、SaaS(Software as a Service)モデルで提供されています。500万以上のアクティブストアを持ち、世界175カ国以上で利用されています。テンプレートエンジンとしてLiquidを採用し、カスタマイズ性と使いやすさのバランスを実現しています。10,000以上のアプリを提供するApp Storeを通じて、決済、配送、マーケティング、在庫管理などあらゆる機能を拡張できます。Shopify PlusやShopify POS、Shop Payなど、企業のニーズに応じた多様なソリューションを提供し、オムニチャネル販売を支援します。GraphQLとREST APIの両方をサポートし、ヘッドレスコマースや外部システムとの連携も容易です。

メリット・デメリット

メリット

  • 簡単セットアップ: 技術的知識がなくても短時間でECサイトを構築可能
  • 豊富なアプリエコシステム: 10,000以上のアプリで機能を自由に拡張
  • 安定した運用: サーバー管理不要で99.99%の稼働率を保証
  • 包括的な機能: 決済、配送、在庫管理、マーケティングまで一元管理
  • 強力なサポート: 24時間365日のカスタマーサポート
  • マルチチャンネル販売: Facebook、Instagram、Amazon等での販売も可能
  • モバイル対応: 管理画面もストアフロントも完全モバイル対応

デメリット

  • 月額費用: $39/月からの継続的なコストが発生
  • カスタマイズ制限: SaaSのため、コアシステムの変更は不可
  • 取引手数料: 外部決済ゲートウェイ使用時に追加手数料
  • データ所有権の制限: プラットフォーム依存でデータエクスポートに制限
  • 日本語サポート: 英語中心で日本語リソースが限定的

主要リンク

使い方の例

Shopifyストアの初期設定

# Shopify CLIのインストール
npm install -g @shopify/cli@latest

# 新しいアプリプロジェクトの作成
shopify app init my-shopify-app

# 開発ストアの作成
shopify store create --name="My Dev Store"

# ローカル開発環境の起動
shopify app dev

Liquidテンプレートの基本

<!-- product.liquid - 商品ページテンプレート -->
{% assign current_variant = product.selected_or_first_available_variant %}

<div class="product-page">
  <h1>{{ product.title }}</h1>
  
  <!-- 商品画像 -->
  <div class="product-images">
    {% for image in product.images %}
      <img src="{{ image | img_url: '500x500' }}" 
           alt="{{ product.title }}">
    {% endfor %}
  </div>
  
  <!-- 商品価格 -->
  <div class="product-price">
    {% if product.compare_at_price > product.price %}
      <span class="sale-price">{{ product.price | money }}</span>
      <span class="original-price">{{ product.compare_at_price | money }}</span>
    {% else %}
      <span>{{ product.price | money }}</span>
    {% endif %}
  </div>
  
  <!-- カートに追加フォーム -->
  <form action="/cart/add" method="post">
    <input type="hidden" name="id" value="{{ current_variant.id }}">
    
    <!-- バリアント選択 -->
    {% if product.has_only_default_variant == false %}
      {% for option in product.options_with_values %}
        <label>{{ option.name }}</label>
        <select name="options[{{ option.name }}]">
          {% for value in option.values %}
            <option value="{{ value }}">{{ value }}</option>
          {% endfor %}
        </select>
      {% endfor %}
    {% endif %}
    
    <button type="submit">カートに追加</button>
  </form>
</div>

Shopify Admin API(GraphQL)の使用

// Shopify Admin APIクライアントの初期化
import { shopifyApi, ApiVersion } from '@shopify/shopify-api';

const shopify = shopifyApi({
  apiKey: process.env.SHOPIFY_API_KEY,
  apiSecretKey: process.env.SHOPIFY_API_SECRET,
  scopes: ['read_products', 'write_products'],
  hostName: process.env.HOST,
  apiVersion: ApiVersion.October23,
});

// 商品情報の取得(GraphQL)
async function getProduct(session, productId) {
  const client = new shopify.clients.Graphql({ session });
  
  const query = `
    query getProduct($id: ID!) {
      product(id: $id) {
        id
        title
        description
        priceRangeV2 {
          minVariantPrice {
            amount
            currencyCode
          }
        }
        images(first: 5) {
          edges {
            node {
              url
              altText
            }
          }
        }
        variants(first: 10) {
          edges {
            node {
              id
              title
              price
              inventoryQuantity
            }
          }
        }
      }
    }
  `;
  
  const response = await client.query({
    data: {
      query,
      variables: { id: `gid://shopify/Product/${productId}` }
    }
  });
  
  return response.body.data.product;
}

Shopifyアプリの開発(Webhooks)

// Webhookハンドラーの設定
import { DeliveryMethod } from '@shopify/shopify-api';

// Webhookハンドラーの登録
shopify.webhooks.addHandlers({
  // 注文作成時のWebhook
  ORDERS_CREATE: {
    deliveryMethod: DeliveryMethod.Http,
    callbackUrl: '/api/webhooks/orders/create',
    callback: async (topic, shop, body, webhookId) => {
      const order = JSON.parse(body);
      console.log(`新しい注文 #${order.order_number} が作成されました`);
      
      // 注文処理ロジック
      await processNewOrder(order);
    },
  },
  
  // 商品更新時のWebhook
  PRODUCTS_UPDATE: {
    deliveryMethod: DeliveryMethod.Http,
    callbackUrl: '/api/webhooks/products/update',
    callback: async (topic, shop, body, webhookId) => {
      const product = JSON.parse(body);
      console.log(`商品 "${product.title}" が更新されました`);
      
      // 在庫同期や価格更新など
      await syncProductData(product);
    },
  },
});

// Webhook検証ミドルウェア
app.post('/api/webhooks/*', express.raw({ type: 'application/json' }), async (req, res) => {
  try {
    await shopify.webhooks.process({
      rawBody: req.body,
      rawRequest: req,
      rawResponse: res,
    });
  } catch (error) {
    console.error('Webhook処理エラー:', error);
    res.status(500).send(error.message);
  }
});

Shopify Storefront APIの使用

// Storefront APIクライアントの作成
import { createStorefrontApiClient } from '@shopify/storefront-api-client';

const client = createStorefrontApiClient({
  storeDomain: 'your-store.myshopify.com',
  apiVersion: '2023-10',
  publicAccessToken: process.env.SHOPIFY_STOREFRONT_ACCESS_TOKEN,
});

// カートの作成と商品追加
async function createCart(variantId, quantity) {
  const mutation = `
    mutation createCart($input: CartInput!) {
      cartCreate(input: $input) {
        cart {
          id
          checkoutUrl
          totalQuantity
          lines(first: 10) {
            edges {
              node {
                id
                quantity
                merchandise {
                  ... on ProductVariant {
                    id
                    title
                    price {
                      amount
                      currencyCode
                    }
                  }
                }
              }
            }
          }
          cost {
            totalAmount {
              amount
              currencyCode
            }
          }
        }
        userErrors {
          field
          message
        }
      }
    }
  `;
  
  const variables = {
    input: {
      lines: [{
        merchandiseId: variantId,
        quantity: quantity
      }]
    }
  };
  
  const { data, errors } = await client.request(mutation, { variables });
  
  if (errors) {
    throw new Error(errors[0].message);
  }
  
  return data.cartCreate.cart;
}

カスタムディスカウント機能の実装

// Shopify Functions(Discount API)の実装
// functions/discounts/volume-discount.js

export default {
  async run(input) {
    const configuration = JSON.parse(
      input?.discountNode?.metafield?.value ?? "{}"
    );
    
    // 数量割引の計算
    const targets = input.cart.lines
      .filter(line => line.quantity >= configuration.minimumQuantity)
      .map(line => {
        const percentageDiscount = configuration.percentage;
        
        return {
          productVariant: {
            id: line.merchandise.id,
          },
          value: {
            percentage: {
              value: percentageDiscount.toString(),
            },
          },
        };
      });
    
    // 割引なしの場合
    if (!targets.length) {
      return { discounts: [] };
    }
    
    // 割引の適用
    return {
      discounts: [{
        targets,
        message: `${configuration.percentage}% OFF - 数量割引適用中`,
      }],
    };
  },
};

// GraphQLスキーマ定義
// extensions/volume-discount/schema.graphql
"""
数量ベースの割引設定
"""
input Configuration {
  minimumQuantity: Int!
  percentage: Float!
}

これらの例は、Shopifyプラットフォームの主要な開発パターンを示しています。Liquidによるテーマカスタマイズ、Admin APIを使った管理機能の拡張、Storefront APIによるカスタムストアフロントの構築、Webhookによるイベント駆動処理、そしてShopify Functionsによる高度なカスタマイズまで、幅広い開発シナリオに対応できます。