php curl 设置请求头 headers 和请求体 body 用json方式提交

正文开始

https://my.oschina.net/u/3714085/blog/1573924

   // post body
    public static function postBody($url, $postData = array(),  $ref=''){
        $header = array("Referer: ".$ref."","Cookie: ");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
        //指定post数据
        curl_setopt($ch, CURLOPT_POST, true);
        # 一个用来设置HTTP请求头字段的数组
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                # 设置编码格式
                'Content-Type: application/json;charset=utf-8',
                'Content-Length: ' . strlen(json_encode($postData))
            )
        );
        //添加变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

场景:抖音小程序授权登录 使用post+body json格式提交

 $sessionUrl = 'https://developer.toutiao.com/api/apps/v2/jscode2session';
        $postData = [
            'appid'=> Env::get('douyinXcx.appId'),
            'secret'=> Env::get('douyinXcx.secret'),
            'code'=> $code,
            'anonymous_code'=> $anonymousCode,
        ];
//        print_r($postData);exit;
        $res = File::postBody($sessionUrl, $postData);
        print_r($res);
        print_r($postData);

正文结束

PHP接口(interface)和抽象类(abstract) php中文转拼音、声母,支持生僻字。overtrue/pinyin:~3.0