2023-07-28 1301
<?php //回调地址中获取code,拿到code后在去请求一个接口获取access_token和openid $code = $_GET["code"]; //当前回调地址(当前的页面地址) $url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; if ($code == '') { oauth1($url); } function oauth1($url) { // 跳转微信提供的地址获取code $appid = "你的appid"; $redirect_uri = urlencode($url); header("Location: https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_base&state=123#wechat_redirect"); } //根据code获取openid function get_user_openid1($code) { $appid = "你的appid"; $appsecret = "你的appsecret"; $access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecret}&code={$code}&grant_type=authorization_code"; $access_token_json = https_request($access_token_url); $access_token_array = json_decode($access_token_json, true); $access_token=$access_token_array['access_token']; $openid = $access_token_array['openid']; return $openid; } function https_request($url, $data = null) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); if (!empty($data)) { curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($curl); curl_close($curl); return $output; } // 用户的openid echo "openid:" . get_user_openid1($code);