小程序端代码

let that = this;
uni.login({
  success: (r) => {
    console.log('succ', r);
    requestUtil.get(url, {code: r.code, anonymousCode:r.anonymousCode}, (res) => {
      console.log('return', res);
      that.setData({
        sessionKey: res.datas.session_key,
        openid: res.datas.openid,
        unionid: res.datas.unionid || ''
      });
      callback && callback(res.datas.session_key);
    });
  }
})

服务器端代码

$code = I('post.code');
$url= 'https://developer.toutiao.com/api/apps/v2/jscode2session';

// 启动一个CURL会话
$ch = curl_init();

// 要访问的地址
curl_setopt($ch, CURLOPT_URL, $url); 
// 对认证证书来源的检测 https请求 不验证证书和hosts
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
// 从证书中检查SSL加密算法是否存在
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
//解决数据包大不能提交
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:')); 

// 发送一个常规的Post请求
curl_setopt($ch, CURLOPT_POST, true);

if (!empty($data)){
// Post提交的数据包
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
}
// 设置超时限制防止死循环
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
// 设置超时限制防止死循环 
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
// 获取的信息以文件流的形式返回
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
if (!empty($headers)){
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
}
$output = curl_exec($ch);

if ($output === false) {
return 'Curl error: ' . curl_error($ch);
}

curl_close($ch);
return $output;

返回内容

{"err_no":40014,"err_tips":"bad params","data":{"session_key":"","openid":"","anonymous_openid":"","unionid":"","dopenid":""}}

通过提交工单,抖音技术那边回复说是postman下请求返回值正常。因此猜测,是curl写法不严谨导致的。

$curl = curl_init ();

$options = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_VERBOSE => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode ($data),
CURLOPT_HTTPHEADER => array (
"Accept: application/json",
'Content-Type: application/json' 
) 
);

if (! curl_setopt_array ( $curl , $options )) {
throw new \RuntimeException ( 'curl_setopt_array failed. ' . curl_errno ( $ch ) . ': ' . curl_error ( $curl ) );
}

$response = curl_exec ( $curl );
$err = curl_error ( $curl );

curl_close ( $curl );

if ($err) {
return "cURL Error #:" . $err;
} else {
return $response;
}

作者 admin

百度广告效果展示