好的,接下来我将帮助你完成从获取 `code` 到使用 `code` 获取用户信息和手机号的完整流程。以下是详细的步骤和代码示例: Step 1: 获取 `code` 你需要在前端实现一个按钮或链接,引导用户跳转到微信授权页面。假设你已经有一个前端页面,可以使用以下代码生成授权链接: ```html <a href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=<?php echo $appid; ?>&redirect_uri=<?php echo urlencode('https://m.lzwdly.com/zt/yy'); ?>&response_type=code&scope=snsapi_userinfo,snsapi_phone&state=state#wechat_redirect">授权登录</a> ``` Step 2: 用户同意授权后,微信会重定向到你设置的 `redirect_uri`,并带上 `code` 参数 在你的 `redirect_uri` 页面(例如 `https://m.lzwdly.com/zt/yy`),你需要捕获 `code` 参数并使用它来获取用户的访问令牌(access token)。 ```php <?php $appid = 'wx61ecda51f43ab027'; $appsecret = '5589c866251c396b4b46552d9324d22e'; $redirect_uri = 'https://m.lzwdly.com/zt/yy'; // 获取 code $code = isset($_GET['code']) ? $_GET['code'] : ''; if (empty($code)) { die('未获取到 code,请重新授权。'); } // 使用 code 换取 access_token 和 openid $token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecret}&code={$code}&grant_type=authorization_code"; $response = file_get_contents($token_url); $token_data = json_decode($response, true); if (isset($token_data['errcode'])) { die('获取 access_token 失败:' . $token_data['errmsg']); } $access_token = $token_data['access_token']; $openid = $token_data['openid']; // 使用 access_token 和 openid 获取用户信息 $user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN"; $user_info_response = file_get_contents($user_info_url); $user_info = json_decode($user_info_response, true); if (isset($user_info['errcode'])) { die('获取用户信息失败:' . $user_info['errmsg']); } // 输出用户信息 echo '<pre>'; print_r($user_info); echo '</pre>'; // 使用 access_token 和 openid 获取手机号 $phone_info_url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={$access_token}"; $phone_info_data = [ 'openid' => $openid ]; $phone_info_json = json_encode($phone_info_data); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $phone_info_url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $phone_info_json); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); $phone_info_response = curl_exec($ch); curl_close($ch); $phone_info = json_decode($phone_info_response, true); if (isset($phone_info['errcode'])) { die('获取手机号失败:' . $phone_info['errmsg']); } // 输出手机号 echo '<pre>'; print_r($phone_info); echo '</pre>'; ?> ``` 解释 1. 获取 `code`:用户点击授权链接后,微信会重定向到你设置的 `redirect_uri`,并带上 `code` 参数。 2. 使用 `code` 换取 `access_token` 和 `openid`:通过调用微信的 `oauth2/access_token` 接口,使用 `code` 换取 `access_token` 和 `openid`。 3. 获取用户信息:使用 `access_token` 和 `openid` 调用微信的 `sns/userinfo` 接口,获取用户的详细信息。 4. 获取手机号:使用 `access_token` 和 `openid` 调用微信的 `wxa/business/getuserphonenumber` 接口,获取用户的手机号。 注意事项 - 确保你的服务器支持 `file_get_contents` 和 `curl` 功能。 - 处理好错误情况,确保在获取 `access_token`、用户信息和手机号时都能正确处理可能的错误。 - 保护好你的 `appid` 和 `appsecret`,不要在公开的地方泄露。 希望这些信息对你有帮助!如果有任何问题,请随时提问。 [2024-11-06 21:46:35 | AI写代码神器 | 1041点数解答]