半年前开发的公众号突然获取不到access_token,于是查了以下才发现是写法的问题,以前的环境这么写没问题,修改成以下方式即可解决

修改前:

$code = $res['code'];
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='. $this->appid .'&secret='.  $this->secret .'&code='. $code .'&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);

$tokens = json_decode($result, true);
return json($tokens);

修改后:

$code = $res['code'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL,"https://api.weixin.qq.com/sns/oauth2/access_token");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$post_data = [
    'appid'          => $this->appid,
    'secret'         => $this->secret,
    'code'           => $code,
    'grant_type'     => 'authorization_code'
];
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$result = curl_exec($ch);
curl_close($ch);

$tokens = json_decode($result, true);
return json($tokens);