LoginSignup
0
0

More than 1 year has passed since last update.

[cURL] PHPにてAWSから外部へPOSTする

Last updated at Posted at 2022-05-27

CRMシステムのHubSpot導入にあたり社内システムで活用しているAWSから売上実績を定期的にHubSpotへAPIで投げる案件があり、Node.jsで仕組みを作った矢先、導入環境に合わず(?)phpで書くことに。phpでバックエンドと思ったものの案外すっきり出来たので、忘れないうちにメモ書き投稿。

MySQLへの接続

mysqlに接続。そして取ってきたデータをAPI用の配列にプッシュ。HubSpotのAPIは10件/回の上限のため10件に達したらAPIで投げるようにする。

php
<?php
    $cn252 = new mysqli("****.rds.amazonaws.com", "user", "password", "db");
    if ($cn252->connect_error) {
        echo $cn252->connect_error;
        exit();
    } else {
        $cn252->set_charset("utf8");
    }

    $sql = "SELECT...";
    $rs = $cn252->query($sql);

    $ary = []; //返り値を格納
    $c = 1;

    while ($item = $rs->fetch_array()) {
      $ary[] = array('id'=> $item['contact_id'],'properties'=> array('col'=> $item['val']));  
      if($c % 10 == 0){
        Hs_update($ary);
        $ary = [];          
      }    
      $c++;
    }

    if($c % 10 != 0) Hs_update($ary);

cURLにてAPIへデータを投げる

cURLはphpの関数を使ってセットして終了。
JSONの成型といい、1行1行書いてPOSTするなどjsとの違いに少し苦戦。

php
    function Hs_update($ary){       
        $data_json = json_encode(array('inputs'=> $ary));
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, 'https://api.hubapi.com/crm/v3/objects/contacts/batch/update?hapikey=<APIKEY>');
        $result=curl_exec($ch);
        echo 'RETURN:'.$result;
        curl_close($ch);        
    }

PHPにてcURLでGETする方法

今後の参考にGETする方法も出来るようにしておく。

php
<?php
$url="https://api.hubapi.com/crm/v3/objects/contacts?limit=10&archived=false&hapikey=<API KEY>";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
$result = json_decode($response,true);

for($i = 0; $i < count($result['results']); $i++){
    echo $result['results'][$i]["id"] . "<br>\n";
}

curl_close($ch);

配列の中に配列があり所定の値を取るのに苦戦したものの、HubSpotの顧客情報を取得する方法が出来て一先ず安心。

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