天天看點

抖店開放平台php處理類

        抖店不提供php開發的sdk,工作中需要用到。封裝了一個。需要注意的是,抖音的php的簽名文檔說 使用v2,實際使用的v1簽名,而且比較坑的是簽名驗證用不等于。。。。。。

      開頭用Fxg是估計是抖音收購的放心購,簡稱fxg。

      比較坑的是:傳參需要排序,傳參還有多元素組。

<?php

class FxgClient

{

    private $appKey;

    private $appSecret;

    public function __construct(string $appKey,string $appSecret)

    {

        $this->appKey = $appKey;

        $this->appSecret = $appSecret;        

    }

    //v1版本簽名

    public function sign( string $timestamp,  string $paramJson)

    {

        //  String signPattern = appSecret + "app_key" + appKey + "param_json" + sortedParamStr +"timestamp" + timestamp + appSecret;

        $paramPattern = 'app_key' . $this->appKey . 'param_json' . $paramJson . 'timestamp' . $timestamp ;

        $signPattern = $this->appSecret . $paramPattern . $this->appSecret;

        return md5($signPattern);

    }

    //v2版本簽名

    public function signV2( $mothod,  $timestamp,  $paramJson)

    {

        $paramPattern = 'app_key' . $this->appKey .'mothod'.$mothod. 'param_json' . $paramJson . 'timestamp' . $timestamp .'v2' ;

        $signPattern = $this->appSecret . $paramPattern . $this->appSecret;

         //return md5($signPattern);

        return hash_hmac("sha256", $signPattern, $appSecret);

    }

    //傳回響應消息

    public function msg($code,$message='',$data=[])

    {

        die(json_encode(['code'=>$code,'data'=>$data,'message'=>$message]));

    }

    // 序列化參數,入參必須為關聯數組

    public function marshal(array $param): string {

        $this->rec_ksort($param); // 對關聯數組中的kv,執行排序,需要遞歸

        $s = json_encode($param, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); // 重新序列化,確定所有key按字典序排序

        // 加入flag,確定斜杠不被escape,漢字不被escape

        return $s;

    }

    // 關聯數組排序,遞歸

    private function rec_ksort(array &$arr)

    {

        $kstring = true;

        foreach ($arr as $k => &$v) {

            if (!is_string($k)) {

                $kstring = false;

            }

            if (is_array($v)) {

                $this->rec_ksort($v);

            }

        }

        if ($kstring) {

            ksort($arr);

        }

    }    

}

$appKey = ''; //  替換成你的app_key

$appSecret=''; //替換為你的appSecret

$method = '';

$timestamp = $_GET['timestamp'];

$paramJson=file_get_contents("php://input");

$fxg = new FxgClient($appKey,$appSecret);

$paramJson = $fxg->marshal(json_decode($paramJson,true));

// 計算簽名

$signVal = $fxg->sign( $timestamp, $paramJson);

$code = $signVal!=$_GET['sign']?100001:100002;

$fxg->msg($code);

?>