1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Shopify] ページ管理 I、ページを生成する

Last updated at Posted at 2020-12-20

Shopifyはモノを販売するシステムとしても便利ですが、商品に関連する情報なども掲載するCMSとしても利用できます。そんな時さらにアドバンスな利用をしたいとき使うのがページAPIです。

本日はそのShopifyページAPIの活用方法をみて行きます。今回の環境はASP.NET CORE 3.1を使っています。

オフィシャルドキュメントはこちらです
https://shopify.dev/docs/admin-api/rest/reference/online-store/page

今日は下記の順でページのをみて行きます。

  • 作成
  • 検索
  • 更新
  • 検索
  • 削除

ページの作成

ページを生成するためのAPIのエンドポイントは下記です。

POST
/admin/api/2020-10/pages.json

モデル

APIでデータのやりとりをするためのモデル(ページオブジェクト)は下記です(フルバージョンはオフィシャルドキュメントを参照ください)


{
  "page": {
    "id": 1025371368,
    "title": "Warranty information",
    "shop_id": 690933842,
    "handle": "warranty-information",
    "body_html": "<h2>Warranty</h2>\n<p>Returns accepted if we receive items <strong>30 days after purchase</strong>.</p>",
    "author": "Shopify API",
    "created_at": "2020-11-04T16:19:16-05:00",
    "updated_at": "2020-11-04T16:19:16-05:00",
    "published_at": "2020-11-04T16:19:16-05:00",
    "template_suffix": null,
    "admin_graphql_api_id": "gid://shopify/OnlineStorePage/1025371368"
  }
}

これをC#オブジェクトになおすと下記になります。


 public class ShopifyPageObjectRootModel
    {
        public ShopifyPageObjectModel page { get; set; }
    }

    public class ShopifyPageObjectModel
    {
        public long id { get; set; }
        public string title { get; set; }
        public long shop_id { get; set; }
        public string handle { get; set; }
        public string body_html { get; set; }
        public string author { get; set; }
        public DateTime created_at { get; set; }
        public DateTime updated_at { get; set; }
        public DateTime published_at { get; set; }
        public object template_suffix { get; set; }
        public string admin_graphql_api_id { get; set; }
    }

クラス

では、さっそくページを生成するためのAPIをCallするクラスを書いてみます。


    public class ShopifyPageHandlers : IShopifyPageHandlers
    {
        private readonly IShopifyHandlers _shopifyHandlers;
        private readonly IOrganizationHandlers _organizationHandlers;
        private readonly TelemetryClient _telemetry;
        private static HttpClient client;
        private const string path = "/admin/api/2020-10/";

        public ShopifyPageHandlers(IShopifyHandlers shopifyHandlers,
            TelemetryClient telemetry,
            IOrganizationHandlers organizationHandlers)
        {
            _shopifyHandlers = shopifyHandlers;
            _telemetry = telemetry;
            _organizationHandlers = organizationHandlers;
        }

        public async Task<ShopifyPageObjectModel> CreateShopifyPageAsync(string storeUrl, string token, ShopifyPageObjectRootModel data)
        {
            client = new HttpClient();

            var url = "https://" + storeUrl + path + "pages.json";

            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("X-Shopify-Access-Token", token);

            var json = JsonConvert.SerializeObject(data);
            var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json");

            var response = await client.PostAsync(url, stringContent);

            var resultString = await response.Content.ReadAsStringAsync();

            var responseLog = new Dictionary<string, string>();
            responseLog.Add("ApiResponse", resultString);
            _telemetry.TrackEvent("from /pages.json", responseLog);

            return JsonConvert.DeserializeObject<ShopifyPageObjectModel>(resultString);
        }


    }

    public class ShopifyPageObjectRootModel
    {
        public ShopifyPageObjectModel page { get; set; }
    }

    public class ShopifyPageObjectModel
    {
        public long id { get; set; }
        public string title { get; set; }
        public long shop_id { get; set; }
        public string handle { get; set; }
        public string body_html { get; set; }
        public string author { get; set; }
        public DateTime created_at { get; set; }
        public DateTime updated_at { get; set; }
        public DateTime published_at { get; set; }
        public object template_suffix { get; set; }
        public string admin_graphql_api_id { get; set; }
    }
}

コントローラー

先ほど作ったクラスを呼ぶコントローラーは下記です


[HttpPost, Route("/App/Location/MakePage")]
public async Task<IActionResult> MakePage()
{
  // Read cookie
    string sdomain = Request.Cookies["sdomain_location"];

    var organization = _organizationHandlers.GetStoreLocationsOrganization(sdomain);

    var page = await _shopifyPageHandlers.CreateShopifyPageAsync(sdomain,    
      organization.ShopifyAccessToken, 
      new ShopifyPageObjectRootModel(){ 
        page =  new ShopifyPageObjectModel()
          {
            title = "Store Locations",
            body_html = "<p>This is store location page.</p>",
            handle = "StoreLocations",
            published_at = DateTime.Now
          }
    });

    return Ok(page);
}

ビュー、Html

上記のMakePageメソッドをCallするActionが下記です


<div class="py-2">
  <button class="btn btn-primary rounded-0" id="ButtonCreatePage">Create Page</button>
</div>


</div>

@section Scripts{
<script>
  $("#ButtonCreatePage").click(function () {

    $.ajax({
      url: "/App/Location/MakePage",
      type: "POST"
    })
    .done((data, status, jqXHR) => {
      console.log(data);
    })
    .fail((data) => {
      console.log(data.responseText);
    });
  });
</script>
}

ページ生成の確認

ページが生成されているか確認してみます。

image.png

先ほどのページが生成されていることを確認できました。

次(検索)

では、次はページの一覧の表示(検索)をみて行きます。

[Shopify] ページ管理 II、ページの一覧を表示する

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?