下面的方法通用于不管你有多少个域名,都可以通过配置一个地址获取相同的微信用户的openid
逻辑
代码
// 获取code的 public function wechatLogin(){ $code = input('code'); // 如果cookie缓存里面已经保存着openid,则不会再次获取新的openid if (empty($code)) { $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; $url = $protocol.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; header('Location:https://统一获取code的域名/api/wechat/getCode/?url='.$url); exit; }else{ // 防止刷新时导致重复带入过期code导致获取openid错误 $options = array ( 'appid' => 'xxx', // 填写高级调用功能的appid 'appsecret' => 'xxx' // 填写高级调用功能的密钥 ); $wechat = new WechatApi($options); $result = $wechat->getOauthAccessToken($code); // access_token,expires_in,refresh_token,openid,scope } }
上面跳转获取code的代码
// 获取code public function getCode(){ ob_start(); $myurl = Request::param('url'); $options = array ( 'token' => '', // 填写你设定的key 'appid' => '', // 填写高级调用功能的appid 'appsecret' => '' // 填写高级调用功能的密钥 ); $wechat = new WechatApi($options); $callback = 'https://域名/oauth.php?url= '.$myurl; $url = $wechat->getOauthRedirect($callback,$state='',$scope='snsapi_base'); header("Location:".$url); exit; }
oauth.php
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>授权页面跳转中</title> </head> <body> <?php $url = $_GET['url']; $url = $url.'?code='.$_GET['code']; Header("Location: $url"); ?> </body> </html>
这里有上面代码所需要的类
点击这里查看 WechatApi类
可以用微信打开以下地址查看演示
https://www.liqingbo.cn/apis/wechat/wechatlogin