> ## Documentation Index
> Fetch the complete documentation index at: https://auth0.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Marketoにユーザーデータをエクスポートする

> Auth0のユーザーデータのエクスポートとMarketoへのインポート方法について説明します。

export const AuthCodeGroup = ({children, dropdown}) => {
  const [processedChildren, setProcessedChildren] = useState(children);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      unsubscribe = window.autorun(() => {
        const processChildren = node => {
          if (typeof node === "string") {
            let processedNode = node;
            for (const [key, value] of window.rootStore.variableStore.values.entries()) {
              const escapedKey = key.replaceAll(/[.*+?^${}()|[\]\\]/g, (String.raw)`\$&`);
              processedNode = processedNode.replaceAll(new RegExp(escapedKey, "g"), value);
            }
            return processedNode;
          } else if (Array.isArray(node)) {
            return node.map(processChildren);
          } else if (node && node.props && node.props.children) {
            return {
              ...node,
              props: {
                ...node.props,
                children: processChildren(node.props.children)
              }
            };
          }
          return node;
        };
        setProcessedChildren(processChildren(children));
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  return <CodeGroup dropdown={dropdown}>{processedChildren}</CodeGroup>;
};

この記事では、Auth0のユーザーデータをCSVファイルにエクスポートし、Market REST APIの[一括リードエンドポイント](http://developers.marketo.com/rest-api/endpoint-reference/lead-database-endpoint-reference/#/Bulk_Leads)を使用してMarketoにインポートする方法について説明します。

## ユーザーデータファイルを作成する

Dashboardの[［Extensions（拡張機能）］](https://manage.auth0.com/#/extensions)セクションに移動して、 **［User Import / Export Extension（ユーザーのインポート/エクスポート拡張機能）］** を開きます。拡張機能ページで、メニューから **［Export（エクスポート）］** を選択します。

次に、 **［Export Format（エクスポート形式）］** を必要なファイル形式に設定します。MarketoはCSV形式のファイルインポートを受け付けるため、`［Tab Separated Value file（タブ区切り値ファイル）（*.csv）］`オプションを選択してください。

**［Fields（フィールド）］** セクションの一番上で、各ユーザー属性の **［User Field（ユーザーフィールド）］** と **［Column Name（列名）］** を入力し、エクスポートに含めます。例：

| ユーザーフィールド     | 列名                     |
| ------------- | ---------------------- |
| `email`       | Email Address（メールアドレス） |
| `created_at`  | Created At（作成場所）       |
| `given_name`  | First Name（名）          |
| `family_name` | Last Name（姓）           |

ユーザーフィールドを追加したら、 **［Export Users（ユーザーのエクスポート）］** ボタンをクリックしてエクスポートを開始します。エクスポートが完了したら、CSVファイルをダウンロードして、以下の処理に使用します。

### ユーザーデータファイルのインポート

開始する前に、「[Marketoドキュメント：一括リードインポート](http://developers.marketo.com/rest-api/bulk-import/bulk-lead-import/)」で詳細を確認できます。

ユーザーデータファイルをMarketoにインポートするには、[一括リードエンドポイント](http://developers.marketo.com/rest-api/endpoint-reference/lead-database-endpoint-reference/#/Bulk_Leads)に対してPOST要求を実行します。要求のcontent-typeヘッダーを`multipart/form-data`に設定し、エクスポートしたCSVファイルを含む`file`パラメーターと、formatパラメーターを`csv`に設定します。例：

<AuthCodeGroup>
  ```bash cURL lines theme={null}
  curl --request POST \
    --url https://marketo_rest_api_base_url/bulk/v1/leads.json \
    --header 'authorization: Bearer {MARKETO_ACCESS_TOKEN}' \
    --form file=@auth0_users.csv \
    --form format=csv
  ```

  ```csharp C# lines theme={null}
  var client = new RestClient("https://marketo_rest_api_base_url/bulk/v1/leads.json");
  var request = new RestRequest(Method.POST);
  request.AddHeader("authorization", "Bearer {MARKETO_ACCESS_TOKEN}");
  request.AddHeader("content-type", "multipart/form-data; boundary=---011000010111000001101001");
  request.AddParameter("multipart/form-data; boundary=---011000010111000001101001", "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"; filename=\"auth0_users.csv\"\r\nContent-Type: text/csv\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"format\"\r\nContent-Type: text/plan\r\n\r\ncsv\r\n-----011000010111000001101001--\r\n", ParameterType.RequestBody);
  IRestResponse response = client.Execute(request);
  ```

  ```go Go lines expandable theme={null}
  package main

  import (
  	"fmt"
  	"strings"
  	"net/http"
  	"io/ioutil"
  )

  func main() {

  	url := "https://marketo_rest_api_base_url/bulk/v1/leads.json"

  	payload := strings.NewReader("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"; filename=\"auth0_users.csv\"\r\nContent-Type: text/csv\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"format\"\r\nContent-Type: text/plan\r\n\r\ncsv\r\n-----011000010111000001101001--\r\n")

  	req, _ := http.NewRequest("POST", url, payload)

  	req.Header.Add("authorization", "Bearer {MARKETO_ACCESS_TOKEN}")
  	req.Header.Add("content-type", "multipart/form-data; boundary=---011000010111000001101001")

  	res, _ := http.DefaultClient.Do(req)

  	defer res.Body.Close()
  	body, _ := ioutil.ReadAll(res.Body)

  	fmt.Println(res)
  	fmt.Println(string(body))

  }
  ```

  ```java Java lines theme={null}
  HttpResponse<String> response = Unirest.post("https://marketo_rest_api_base_url/bulk/v1/leads.json")
    .header("authorization", "Bearer {MARKETO_ACCESS_TOKEN}")
    .header("content-type", "multipart/form-data; boundary=---011000010111000001101001")
    .body("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"; filename=\"auth0_users.csv\"\r\nContent-Type: text/csv\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"format\"\r\nContent-Type: text/plan\r\n\r\ncsv\r\n-----011000010111000001101001--\r\n")
    .asString();
  ```

  ```javascript Node.JS lines theme={null}
  var axios = require("axios").default;

  var options = {
    method: 'POST',
    url: 'https://marketo_rest_api_base_url/bulk/v1/leads.json',
    headers: {
      authorization: 'Bearer {MARKETO_ACCESS_TOKEN}',
      'content-type': 'multipart/form-data; boundary=---011000010111000001101001'
    },
    data: '-----011000010111000001101001\r\nContent-Disposition: form-data; name="file"; filename="auth0_users.csv"\r\nContent-Type: text/csv\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name="format"\r\nContent-Type: text/plan\r\n\r\ncsv\r\n-----011000010111000001101001--\r\n'
  };

  axios.request(options).then(function (response) {
    console.log(response.data);
  }).catch(function (error) {
    console.error(error);
  });
  ```

  ```objc Obj-C lines expandable theme={null}
  #import <Foundation/Foundation.h>

  NSDictionary *headers = @{ @"authorization": @"Bearer {MARKETO_ACCESS_TOKEN}",
                             @"content-type": @"multipart/form-data; boundary=---011000010111000001101001" };
  NSArray *parameters = @[ @{ @"name": @"file", @"fileName": @"auth0_users.csv", @"contentType": @"text/csv" },
                           @{ @"name": @"format", @"value": @"csv", @"contentType": @"text/plan" } ];
  NSString *boundary = @"---011000010111000001101001";

  NSError *error;
  NSMutableString *body = [NSMutableString string];
  for (NSDictionary *param in parameters) {
      [body appendFormat:@"--%@\r\n", boundary];
      if (param[@"fileName"]) {
          [body appendFormat:@"Content-Disposition:form-data; name=\"%@\"; filename=\"%@\"\r\n", param[@"name"], param[@"fileName"]];
          [body appendFormat:@"Content-Type: %@\r\n\r\n", param[@"contentType"]];
          [body appendFormat:@"%@", [NSString stringWithContentsOfFile:param[@"fileName"] encoding:NSUTF8StringEncoding error:&error]];
          if (error) {
              NSLog(@"%@", error);
          }
      } else {
          [body appendFormat:@"Content-Disposition:form-data; name=\"%@\"\r\n\r\n", param[@"name"]];
          [body appendFormat:@"%@", param[@"value"]];
      }
  }
  [body appendFormat:@"\r\n--%@--\r\n", boundary];
  NSData *postData = [body dataUsingEncoding:NSUTF8StringEncoding];

  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://marketo_rest_api_base_url/bulk/v1/leads.json"]
                                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                     timeoutInterval:10.0];
  [request setHTTPMethod:@"POST"];
  [request setAllHTTPHeaderFields:headers];
  [request setHTTPBody:postData];

  NSURLSession *session = [NSURLSession sharedSession];
  NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                              completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                  if (error) {
                                                      NSLog(@"%@", error);
                                                  } else {
                                                      NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                                      NSLog(@"%@", httpResponse);
                                                  }
                                              }];
  [dataTask resume];
  ```

  ```php PHP lines expandable theme={null}
  $curl = curl_init();

  curl_setopt_array($curl, [
    CURLOPT_URL => "https://marketo_rest_api_base_url/bulk/v1/leads.json",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"; filename=\"auth0_users.csv\"\r\nContent-Type: text/csv\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"format\"\r\nContent-Type: text/plan\r\n\r\ncsv\r\n-----011000010111000001101001--\r\n",
    CURLOPT_HTTPHEADER => [
      "authorization: Bearer {MARKETO_ACCESS_TOKEN}",
      "content-type: multipart/form-data; boundary=---011000010111000001101001"
    ],
  ]);

  $response = curl_exec($curl);
  $err = curl_error($curl);

  curl_close($curl);

  if ($err) {
    echo "cURL Error #:" . $err;
  } else {
    echo $response;
  }
  ```

  ```python Python lines theme={null}
  import http.client

  conn = http.client.HTTPSConnection("marketo_rest_api_base_url")

  payload = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"; filename=\"auth0_users.csv\"\r\nContent-Type: text/csv\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"format\"\r\nContent-Type: text/plan\r\n\r\ncsv\r\n-----011000010111000001101001--\r\n"

  headers = {
      'authorization': "Bearer {MARKETO_ACCESS_TOKEN}",
      'content-type': "multipart/form-data; boundary=---011000010111000001101001"
      }

  conn.request("POST", "/bulk/v1/leads.json", payload, headers)

  res = conn.getresponse()
  data = res.read()

  print(data.decode("utf-8"))
  ```

  ```ruby Ruby lines theme={null}
  require 'uri'
  require 'net/http'
  require 'openssl'

  url = URI("https://marketo_rest_api_base_url/bulk/v1/leads.json")

  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE

  request = Net::HTTP::Post.new(url)
  request["authorization"] = 'Bearer {MARKETO_ACCESS_TOKEN}'
  request["content-type"] = 'multipart/form-data; boundary=---011000010111000001101001'
  request.body = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"; filename=\"auth0_users.csv\"\r\nContent-Type: text/csv\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"format\"\r\nContent-Type: text/plan\r\n\r\ncsv\r\n-----011000010111000001101001--\r\n"

  response = http.request(request)
  puts response.read_body
  ```

  ```swift Swift lines expandable theme={null}
  import Foundation

  let headers = [
    "authorization": "Bearer {MARKETO_ACCESS_TOKEN}",
    "content-type": "multipart/form-data; boundary=---011000010111000001101001"
  ]
  let parameters = [
    [
      "name": "file",
      "fileName": "auth0_users.csv",
      "contentType": "text/csv"
    ],
    [
      "name": "format",
      "value": "csv",
      "contentType": "text/plan"
    ]
  ]

  let boundary = "---011000010111000001101001"

  var body = ""
  var error: NSError? = nil
  for param in parameters {
    let paramName = param["name"]!
    body += "--\(boundary)\r\n"
    body += "Content-Disposition:form-data; name=\"\(paramName)\""
    if let filename = param["fileName"] {
      let contentType = param["content-type"]!
      let fileContent = String(contentsOfFile: filename, encoding: String.Encoding.utf8)
      if (error != nil) {
        print(error)
      }
      body += "; filename=\"\(filename)\"\r\n"
      body += "Content-Type: \(contentType)\r\n\r\n"
      body += fileContent
    } else if let paramValue = param["value"] {
      body += "\r\n\r\n\(paramValue)"
    }
  }

  let request = NSMutableURLRequest(url: NSURL(string: "https://marketo_rest_api_base_url/bulk/v1/leads.json")! as URL,
                                          cachePolicy: .useProtocolCachePolicy,
                                      timeoutInterval: 10.0)
  request.httpMethod = "POST"
  request.allHTTPHeaderFields = headers
  request.httpBody = postData as Data

  let session = URLSession.shared
  let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
    if (error != nil) {
      print(error)
    } else {
      let httpResponse = response as? HTTPURLResponse
      print(httpResponse)
    }
  })

  dataTask.resume()
  ```
</AuthCodeGroup>

応答はこのようになっているはずです。

```json lines theme={null}
{
    "requestId": "e42b#14272d07d78",
    "success": true,
    "result": [{
        "batchId": 1234,
        "status": "Importing"
    }]
}
```

インポートのステータスは、[Get Import Lead Status API](/docs/ja-jp/)とインポートジョブの`batchId`を使用して確認できます。例：

<AuthCodeGroup>
  ```bash cURL lines theme={null}
  curl --request GET \
    --url https://marketo_rest_api_base_url/bulk/v1/leads/batch/BATCH_ID.json \
    --header 'authorization: Bearer {MARKETO_ACCESS_TOKEN}'
  ```

  ```csharp C# lines theme={null}
  var client = new RestClient("https://marketo_rest_api_base_url/bulk/v1/leads/batch/BATCH_ID.json");
  var request = new RestRequest(Method.GET);
  request.AddHeader("authorization", "Bearer {MARKETO_ACCESS_TOKEN}");
  IRestResponse response = client.Execute(request);
  ```

  ```go Go lines theme={null}
  package main

  import (
  	"fmt"
  	"net/http"
  	"io/ioutil"
  )

  func main() {

  	url := "https://marketo_rest_api_base_url/bulk/v1/leads/batch/BATCH_ID.json"

  	req, _ := http.NewRequest("GET", url, nil)

  	req.Header.Add("authorization", "Bearer {MARKETO_ACCESS_TOKEN}")

  	res, _ := http.DefaultClient.Do(req)

  	defer res.Body.Close()
  	body, _ := ioutil.ReadAll(res.Body)

  	fmt.Println(res)
  	fmt.Println(string(body))

  }
  ```

  ```java Java lines theme={null}
  HttpResponse<String> response = Unirest.get("https://marketo_rest_api_base_url/bulk/v1/leads/batch/BATCH_ID.json")
    .header("authorization", "Bearer {MARKETO_ACCESS_TOKEN}")
    .asString();
  ```

  ```javascript Node.JS lines theme={null}
  var axios = require("axios").default;

  var options = {
    method: 'GET',
    url: 'https://marketo_rest_api_base_url/bulk/v1/leads/batch/BATCH_ID.json',
    headers: {authorization: 'Bearer {MARKETO_ACCESS_TOKEN}'}
  };

  axios.request(options).then(function (response) {
    console.log(response.data);
  }).catch(function (error) {
    console.error(error);
  });
  ```

  ```objc Obj-C lines theme={null}
  #import <Foundation/Foundation.h>

  NSDictionary *headers = @{ @"authorization": @"Bearer {MARKETO_ACCESS_TOKEN}" };

  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://marketo_rest_api_base_url/bulk/v1/leads/batch/BATCH_ID.json"]
                                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                     timeoutInterval:10.0];
  [request setHTTPMethod:@"GET"];
  [request setAllHTTPHeaderFields:headers];

  NSURLSession *session = [NSURLSession sharedSession];
  NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                              completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                  if (error) {
                                                      NSLog(@"%@", error);
                                                  } else {
                                                      NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                                      NSLog(@"%@", httpResponse);
                                                  }
                                              }];
  [dataTask resume];
  ```

  ```php PHP lines theme={null}
  $curl = curl_init();

  curl_setopt_array($curl, [
    CURLOPT_URL => "https://marketo_rest_api_base_url/bulk/v1/leads/batch/BATCH_ID.json",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => [
      "authorization: Bearer {MARKETO_ACCESS_TOKEN}"
    ],
  ]);

  $response = curl_exec($curl);
  $err = curl_error($curl);

  curl_close($curl);

  if ($err) {
    echo "cURL Error #:" . $err;
  } else {
    echo $response;
  }
  ```

  ```python Python lines theme={null}
  import http.client

  conn = http.client.HTTPSConnection("marketo_rest_api_base_url")

  headers = { 'authorization': "Bearer {MARKETO_ACCESS_TOKEN}" }

  conn.request("GET", "/bulk/v1/leads/batch/BATCH_ID.json", headers=headers)

  res = conn.getresponse()
  data = res.read()

  print(data.decode("utf-8"))
  ```

  ```ruby Ruby lines theme={null}
  require 'uri'
  require 'net/http'
  require 'openssl'

  url = URI("https://marketo_rest_api_base_url/bulk/v1/leads/batch/BATCH_ID.json")

  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE

  request = Net::HTTP::Get.new(url)
  request["authorization"] = 'Bearer {MARKETO_ACCESS_TOKEN}'

  response = http.request(request)
  puts response.read_body
  ```

  ```swift Swift lines theme={null}
  import Foundation

  let headers = ["authorization": "Bearer {MARKETO_ACCESS_TOKEN}"]

  let request = NSMutableURLRequest(url: NSURL(string: "https://marketo_rest_api_base_url/bulk/v1/leads/batch/BATCH_ID.json")! as URL,
                                          cachePolicy: .useProtocolCachePolicy,
                                      timeoutInterval: 10.0)
  request.httpMethod = "GET"
  request.allHTTPHeaderFields = headers

  let session = URLSession.shared
  let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
    if (error != nil) {
      print(error)
    } else {
      let httpResponse = response as? HTTPURLResponse
      print(httpResponse)
    }
  })

  dataTask.resume()
  ```
</AuthCodeGroup>

応答は次のようになります。

```json lines theme={null}
{
    "requestId": "8136#146daebc2ed",
    "success": true,
    "result": [{
        "batchId": 1234,
        "status": "Complete",
        "numOfLeadsProcessed": 123,
        "numOfRowsFailed": 0,
        "numOfRowsWithWarning": 0
    }]
}
```

これで作業完了です！Auth0ユーザーがMarketoにインポートされました。
