LoginSignup
1
2

More than 5 years have passed since last update.

EC-Cubeの売り上げとかSlackに投げる

Last updated at Posted at 2017-01-31

Slack.php

  • Slack.php

適当なところに置いておくといいかもしれない



  /**
   * Slackに処理を伝搬するための処理
   * 注文IDが送られてくるので、注文情報に加工して、Slack送信機に送る
   */
  require_once '/var/www/eccube/require.php';
  class Slack{
    private $message = '';
    private $product_id = '';
    private $type = 0;
    private $hash = '#general';

    function __construct(){}
    function __destruct(){}
    public function setMessage($m){ $this->message = $m; }
    public function getMessage(){ return $this->message; }
    public function getOrderId(){ return $this->order_id; }
    public function setType($n){ $this->type= $n; }
    public function getType(){ return $this->type; }
    public function setHash($n){ $this->hash= $n; }
    public function getHash(){ return $this->hash; }

    /**
     * オーダIDをセットするとともに、投稿文章を設定する
     */
    public function setOrderId($order_id){

      $o = new Order;
      $o->setOrderId($order_id);
      $orderdProducts = $o->getOrder();

      ### 投稿文章を作成
      $names = Array();
      $domain = 'http://localhost/upload/save_image/';
      foreach ($orderdProducts as $product){
        array_push($names, $product['product_name'] . "\n" . $domain . $product['sub_image1']);
      }
      $name = join("\n", $names);
      $message = "*商品が購入されました*\n{$name}\n";

      ### メッセージをセット
      $this->setMessage($message);
    }

    /**
     *
     * slackにポストするために、
     * nodeで待受を行っている
     * ローカルの1337ポートに情報を送る
     *
     */
    public function sendLocalEndpoint(){
      $curl = curl_init("http://127.0.0.1/");
      curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
      curl_setopt($curl, CURLINFO_HEADER_OUT, true);
      curl_setopt($curl, CURLOPT_PORT, '1337');
      curl_setopt($curl, CURLOPT_POST, true);
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); //戻ってきたresponseを表示するかどうか
      curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query(
        array(
          'type' => $this->getType(),
          'text'=> $this->getMessage(),
          'hash'=> $this->getHash(),
          'n'=>3,
        )
      ));

      $response = curl_exec($curl);
      curl_close($curl);
      //echo $response ;

    }
  }


  • EC-Cube用の簡単なコード

LC_Page_Shopping_Complete.phpなどに追加しておくといいかもしれない。


        // スラックに情報を送っておく
        $slackControllFilePath = '~/Slack.php';
        if (file_exists($slackControllFilePath)) {
          try{
            include_once($slackControllFilePath);
            $sl = new Slack;
            $sl->setOrderId($_SESSION['order_id']);
            $sl->setType("2"); //コーディネータのタイプ男女
            $sl->setHash('#section_wedding');
            $sl->sendLocalEndpoint();

          } catch (Exception $e) {
            echo "ご不便をおかけいたします。";
            echo "何らかの不都合が発生したと推測される状況になりました。";
            echo "お手数ではございますが、今後の婚姻届製作所をもっと良くするため、";
            echo "お客様の観覧端末と観覧時間をシステム担当者にご連絡ください";
          }
        }



  • node用の簡単なコード

使っているのはrequireのところだけだから。
全て導入してしまえば、通知を送ることができるよ。
webhookは自分のものに入れ替えて、サーバを起動させたら
すぐ動く


/**
 * slackに売れたことを通知する処理
 */

var async = require('async');
var sleep = require('sleep');
var Slack = require('slack-node');
var http = require('http');
var querystring = require('querystring');
process.on('warning', (warning) => { console.log(warning); });

/**
 * slackへの送信切り分け機能
 * @param hash {String} サイト名
 * @param type {Number} 送信者を分けるために使っている
 * @param text {String} 送信者する文字列を記載している
 */
function postSlack(hash, type, text){
  let webhookUri = "https://hooks.slack.com/services/ーーーーーーーー";

  // 質問が来たとき
  if(type==1){
    (text.length>0)? text :"質問が来たよ";
    slack = new Slack();
    slack.setWebhook(webhookUri);
    slack.webhook({ channel: "#"+hash, username: "インフォメーション", text: text}, function(err, response) {
      console.log(response);
    });
  }

  // うれたとき
  if(type==2){
    (text.length>0)? text : "売れたよ";
    slack = new Slack();
    slack.setWebhook(webhookUri);
    slack.webhook({ channel: "#"+hash, username: "注文きたよ", text: text}, function(err, response) {
      console.log(response);
    });
  }

}

/**
 * サーバ機能
 */
http.createServer(function (req, res) {
  let data =''
  req.on('readable', function(chunk) { data += req.read(); });
  req.on('end', function() {
    res.end(data);

    type = getQueryVariable(data, 'type');
    text = getQueryVariable(data, 'text');
    hash = getQueryVariable(data, 'hash');
    (hash == "")? "#general" : hash;
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('200');

    /// タイプ番号をもち、Slackに通知
    postSlack(hash, type, text);
  });

}).listen('1337', '127.0.0.1');

/**
 * クエリストリングから特定要素を抽出するためのパーサ
 */
function getQueryVariable(data, variable) {
  var vars = data.split('&');
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split('=');
    if (decodeURIComponent(pair[0]) == variable) {
      return decodeURIComponent(pair[1]);
    }
  }
}
1
2
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
1
2