end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

facebook conversion api client for php

facebook conversion api client for perl - end0tknr's kipple - web写経開発

先程のentryのphp版です

目次

form_fb_capi.php

<?php
require_once './form/lib/XeimForm4FacebookConversion.php';

$fb_api = new XeimForm4FacebookConversion();
$form_url = $_POST["referrer"];
$fb_api->notify_to_facebook("sexyxeim_com",$form_url,$_POST);

XeimForm4FacebookConversion.php

<?php
require_once 'XeimForm.php';

class XeimForm4FacebookConversion extends XeimForm {

    function __construct() {
        $this->ini_set();
    }

    function error_mail_subject(){
        return "【FacebookConversion】ERROR通知メール";
    }
    
    function error_mail_body($name_1,$refferer,$endpoint,$http_res_code){
        
        $mail_body =<<<EOF
$name_1 様の申し込みがfacebookへ連携されませんでした。
フォームURL        : $refferer
facebook URL       : $endpoint
HTTP RESPONSE CODE : $http_res_code

EOF;
        return $mail_body;
    }

    function notify_to_facebook($facebook_rule_name, $refferer, $req_params ){
        $func_name = __CLASS__." ".__FUNCTION__;
        $this->write_log("START $func_name for $facebook_rule_name $refferer");

        $facebook_rule = $this->facebook_rule($facebook_rule_name);
        if(! $facebook_rule ){
            $tmp_msg = "ERROR fail $func_name $facebook_rule_name";
            $this->write_log($tmp_msg);
            
            $tmp_msg = print_r($req_params,true);
            $this->write_log($tmp_msg);
            return false;
        }
        
 
        $form_data = [
         ["user_data"       =>
          $this->conv_req_params_for_facebook($req_params, $facebook_rule),
          "action_source"   =>"website",
          "event_name"      =>"FromRequest",
          "event_time"      => time(),
          "event_source_url"=>$refferer]
        ];
        //$this->write_log(print_r($form_data,true));

        $endpoint = $facebook_rule["FACEBOOK_URL"];
        $req_data = [
            "access_token"=>$facebook_rule["ACCESS_TOKEN"],
            "data"=> $this->json_encode($form_data),
        ];

        
        $http_res_code = $this->post_to_facebook($req_data, $endpoint);

        if ( in_array($http_res_code,["200","204"], true) ){
            $tmp_msg = "DONE $func_name $facebook_rule_name";
            $this->write_log($tmp_msg);
            return true;
        }

        $tmp_msg = "ERROR $func_name $facebook_rule_name HTTP_CODE:$http_res_code";
        $this->write_log($tmp_msg);
        $this->notify_error($req_params,$refferer,$endpoint,$http_res_code);

        return false;
    }

    private function notify_error($req_params,$refferer,$endpoint,$http_res_code){
        $func_name = __CLASS__." ".__FUNCTION__;
        
        $mail_body = $this->error_mail_body($req_params['name1'],
            $refferer,
            $endpoint,
            $http_res_code);
            
            //全体のシステム管理者へ、メール通知
            $sendmail = new XeimForm4Sendmail();
            $sendmail->mail_to_sys_admin(self::ERR_MAIL_SUBJECT, $mail_body);
            
            $tmp_msg = "ERROR $func_name";
            $this->write_log($tmp_msg);
            $this->write_log($mail_body);
            $this->write_log(print_r($req_params,true));
        }
        
        private function conv_req_params_for_facebook($org_params, $facebook_rule){
            
            $cooperation_items_def = $facebook_rule["COOPERATION_ITEM"];
            $new_params = [];
            foreach($cooperation_items_def as $facebook_key => $from_key){
            //$this->write_log( "$facebook_key , $from_key" );
             
             if(! isset($org_params[$from_key]) or
                 mb_strlen($org_params[$from_key]) == 0){
                 continue;
             }
             //$this->write_log("$facebook_key $from_key , ".$org_params[$from_key]);
             $new_params[$facebook_key] = $org_params[$from_key];
             # refer to https://developers.facebook.com/docs/marketing-api/conversions-api/parameters
             if( strcmp($facebook_key, "em") == 0 ){
                 $new_params[$facebook_key] = [ hash('sha256', $new_params[$facebook_key]) ];
             }
         }
         
         return $new_params;
    }
            

    private function facebook_rule($rule_name){
        $func_name = __CLASS__." ".__FUNCTION__;

        $conf_dir = $this->conf_dir();
        $file_path = $conf_dir ."/facebook/$rule_name.json";
        
        try{
            $file_obj = new SplFileObject($file_path,"rb");
            $json_str = $file_obj->fread($file_obj->getSize());
        } catch (Exception $e) {
            $tmp_msg = "ERROR fail open $file_path $func_name ". $e->getMessage();
            $this->write_log($tmp_msg);
            return;
        }
        
        $ret_def = $this->json_decode($json_str);
        return $ret_def;
    }

    private function post_to_facebook($postdata, $endpoint){
        $func_name = __CLASS__." ".__FUNCTION__;
        $this->write_log("START $func_name to $endpoint");
        //$this->write_log(print_r($postdata,true));
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postdata));
        curl_setopt($ch, CURLOPT_URL, $endpoint);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,TRUE);
        curl_setopt($ch, CURLOPT_FAILONERROR,   TRUE);

        $res_body_json = curl_exec($ch);
        
        $curl_getinfo = curl_getinfo($ch);
        $status_code = $curl_getinfo["http_code"];
        
        if (curl_errno($ch)) {
            $tmp_msg = "ERROR $func_name $endpoint $status_code $res_body_json";
            $this->write_log($tmp_msg);
            return;
        }
        
        $res_body = $this->json_decode($res_body_json);
        if( $res_body["events_received"] != 1 ){
            $tmp_msg = "ERROR $func_name $endpoint $status_code $res_body_json";
            $this->write_log($tmp_msg);
            return;
        }

        curl_close($ch);
        return (string)$status_code;
    }
}

sexyxeim_com.json

{"//":"ex. https://graph.facebook.com/{API_VERSION}/{PIXEL_ID}/events",
 "FACEBOOK_URL":"https://graph.facebook.com/v12.0/ないしょ/events",
 "ACCESS_TOKEN":"ないしょ",
 "NOTIFY_TO":"hogehoge1@example.com,hogehoge2@example.com",
 "//":"連携項目",
 "COOPERATION_ITEM" : {"em" :"email1"}
}

実行例

$ curl -X POST \
   -F 'email1=hogehoge@gmail.com'  \
   -F 'referrer=https://hoge.example.com/cgi-bin/form.cgi' \
   http://localhost/cgi-bin2/form_fb_capi.php