微信自动登录获取openid

微信小程序自动登录之后会获取到一个code。

把code传入以下php代码。可以直接获取openid

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

class Demo
{
protected $appid = 'your_appid';
protected $appsecret = 'your_appsecret';
public function getOpenidByCode($code)
{
//缓存access_token open_id
$url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $this->appid . "&secret=" . $this->appsecret . "&js_code=" . $code . "&grant_type=authorization_code";
$weixin = file_get_contents($url);//通过code换取网页授权access_token
$jsondecode = json_decode($weixin, true); //对JSON格式的字符串进行编码
$openid = $jsondecode['openid'];//输出openid
return $openid;
}
}