LoginSignup
3
0

Next.jsでShopifyのREST Admin APIを叩く

Last updated at Posted at 2022-03-03

Shopifyの様々なAPI

Shopifyには主に以下のAPIがあります。
・Admin API:アプリやサービスがShopifyと連携するのに使う(メインAPI)
・Storefront API:商品データ、顧客情報などを取得する
・Partner API:パートナーダッシュボードにあるデータにアクセスする
・Marketing activities API:プロモーションキャンペーンとマーケティングオートメーションを管理

Storefront APIのjavascript用のsdk(shopify-buy)の日本語記事はよく見るのですが、Admin APIの日本語記事があまり見当たらなかったので、今回はAdmin API(shopify-api)を用いた簡単な実装を紹介します
Admin APIでもGraphQLかRESTがサポートされていますが、今回はREST Admin APIで実装します

Shopifyの管理画面でAdmin API用のaccess tokenを発行

Shopifyのアプリの作成はこちらの記事が分かりやすかったので参考にしてください。
プライベートアプリを作成するところまで完了したら、Admin APIのアクセストークンを発行するために、プライベートアプリ管理ページのConfigurationからAdmin API integrationでセッテイングをしてください(利用するscopeは、ここではとりあえず全てにチェックします)
スクリーンショット 2022-03-03 22.23.22.png
設定が完了するとAdmin API access tokenが発行されるので、それをどこかにコピーしておいてください、後で使います。(決してネットにあげるなどしてはいけません!笑)

pages/api下にAPIの処理を記述

ここからは実際にコードに書いていきます。
今回は顧客を新規作成する実装をしています。

api部分

pages/api/createCustomer.ts
import Shopify, { DataType } from '@shopify/shopify-api';

export default function createCustomer() {
    const client = new Shopify.Clients.Rest(
         //ここにXXX(shopの名前).myshopify.com(string)
        `${process.env.NEXT_PUBLIC_SHOPIFY_SHOP_DOMAIN}`, 
         //ここに先ほど発行したアクセストークン(string)
        `${process.env.NEXT_PUBLIC_SHOPIFY_ACCESS_TOKEN}`,
    );
    client.post({
        path: 'customers',
        data: {
            customer: {
                first_name: 'higu',
                last_name: 'chimmy',
                email: 'higu@example.com',
                phone: '+819012345678',
                verified_email: true,
            },
        },
        type: DataType.JSON,
    });
}

フロント部分

pages/index.tsx
import type { NextPage } from 'next';
import { MouseEventHandler } from 'react';

const Home: NextPage = () => {
    const createCustomer: MouseEventHandler<HTMLButtonElement> = async (event) => {
        event.preventDefault();
        await fetch('/api/createCustomer');
    };
    return (
            <button onClick={createCustomer}>顧客作成</button>
    );
};

export default Home;

ものすごく簡素なコードですがこのようにしてAdmin APIを叩くことができます。
本来であれば、createCustomer()にフロントで入力された色々な顧客情報を引数に渡して、それぞれ値を置き、顧客を新規作成するという使われ方をします。

参考程度にCustomerで取れるobjectを掲載しておきます。こちらから引用

Customerで取れる情報

{
"accepts_marketing": false,
"accepts_marketing_updated_at": "2013-06-27T08:48:27-04:00",
"addresses": [
{
"id": 207119551,
"zip": "40202",
"city": "Louisville",
"phone": "555-625-1199",
"company": null,
"country": "United States",
"default": true,
"address1": "Chestnut Street 92",
"address2": "Apartment 2",
"province": "Kentucky",
"last_name": "Norman",
"first_name": "Bob",
"customer_id": 6940095564,
"country_code": "US",
"country_name": "United States",
"province_code": "KY"
}
],
"currency": "JPY",
"created_at": "2013-06-27T08:48:27-04:00",
"default_address": {
"id": 207119551,
"zip": "40202",
"city": "Louisville",
"phone": "555-625-1199",
"company": null,
"country": "united states",
"default": true,
"address1": "Chestnut Street 92",
"address2": "Apartment 2",
"province": "Kentucky",
"last_name": "Norman",
"first_name": "Bob",
"country_code": "US",
"country_name": "United States",
"province_code": "KY"
},
"email": "bob.norman@hostmail.com",
"first_name": "John",
"id": 207119551,
"last_name": "Norman",
"last_order_id": 234132602919,
"last_order_name": "#1169",
"metafield": {
"key": "new",
"type": "string",
"value": "newvalue",
"namespace": "global"
},
"marketing_opt_in_level": "single_opt_in",
"multipass_identifier": null,
"note": "Placed an order that had a fraud warning",
"orders_count": 3,
"phone": "+16135551111",
"sms_marketing_consent": {
"state": "subscribed",
"opt_in_level": "single_opt_in",
"consent_updated_at": "2021-08-03T15:31:06-04:00",
"consent_collected_from": "OTHER"
},
"state": "disabled",
"tags": "loyal",
"tax_exempt": true,
"tax_exemptions": [
"CA_STATUS_CARD_EXEMPTION",
"CA_BC_RESELLER_EXEMPTION"
],
"total_spent": "375.30",
"updated_at": "2012-08-24T14:01:46-04:00",
"verified_email": true
}

使いたいapiはclient.postpath:XXXの部分で指定し、渡す値も使うapiによって様々なので、詳しくはREST Admin APIの公式docを参考にしてください。

3
0
1

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
3
0