ワイメールAPIでシステム連携(PHP, cURL)

ワイメールで API を使って顧客データと連携するためPHPでテストしてみた。。。

PHPの所は以下で取り合えず登録はできた

<?php
  $http_res = '';
  if ( isset( $_POST['email'] ) && $_POST['email'] != '' ) {
    $api_fqdn = "hoge.jp";
    $method = "POST";
    $apikey_id = "xxxxxxxxxxxxxxxx";
    $secret_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    $mlmaga_id = "test";
    $end_point = "/api/rest/v1/add-user";
    $url = "https://" . $api_fqdn . $end_point . "/";
    // 署名を除くクエリパラメータ
    $params = array(
      "apikeyid" => $apikey_id,
      "id" => $mlmaga_id,
      "email" => $_POST['email'],
      "name" => $_POST['name'],
    );
    // キーでソート はじめはソートしてなく署名の値が違うとなって困った
    ksort($params);
    // 署名を作るため、文字列作成し、HMAC方式でハッシュ値作成、base64エンコード、URLエンコード
    $query_word = http_build_query($params, "", "&");
    $sign_word = $method . "\n" . $api_fqdn . "\n" . $end_point . "\n" . $query_word;
    $hash = hash_hmac('sha256', $sign_word, $secret_key, true);
    $base64 = base64_encode($hash);
    $urlenc = urlencode($base64);
    // 署名をパラメータに追加
    $params["signature"] = $urlenc;
    // ヘッダの指定
    $headers = array(
      "content-type: application/x-www-form-urlencoded;charset=UTF-8"
    );
    // cURL 接続
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
    $http_res = curl_exec($ch);
    curl_close($ch);
  }
?>

HTML

<!DOCTYPE html>
<html lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Language" content="ja">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<title>ワイメール・ユーザー登録</title>
</head>
<body>
<form method="post" action="./ymail-adduser.php">
<div style="max-width:500px; margin:50px auto; border: 1px solid #000000;">
  <div style="margin: 10px 0; font-size: 20px; font-weight: bold; text-align:center;">ワイメール・ユーザー登録</div>
  <div style="margin: 10px 30px 0px 30px;">
    <div style="font-size: 14px; font-weight: bold;">お名前(*)</div>
    <input type="text" id="name" name="name" style="width: 100%;" />
  </div>
  <div style="margin: 10px 30px 0px 30px;">
    <div style="font-size: 14px; font-weight: bold;">メールアドレス(*)</div>
    <input type="text" id="email" name="email" style="width: 100%;" />
  </div>
  <div style="margin: 10px 30px 30px 30px; text-align: center;">
    <input type="submit" name="submit" value="読者登録">
  </div>
</div>
<div style="max-width:800px; margin:50px auto;">
  <div>レスポンス</div>
  <div style="width:100%; border: 1px solid #000000;">
    <?php print($http_res); ?>
  </div>
</div>
</body>
</html>

ブログランキング・にほんブログ村へにほんブログ村

にほんブログ村 IT技術ブログ IT技術情報へにほんブログ村

開発めも

Posted by mikio