pc微信第三方登录一个网站应用授权多个域名 - xiaogardenz/Work GitHub Wiki

php相关代码

class WeChatController extends Controller
{
    public $appid;
    public $secret;
    public $scope;
    public $redirect_uri;
    public $state;
    public function __construct()
    {

        $this->appid  = C('wechat_login.appid');
        $this->secret = C('wechat_login.secret');
        $this->scope  = C('wechat_login.scope');
        $this->state  = urlencode(C('wechat_login.state'));
        $this->redirect_uri = urlencode(C('wechat_login.redirect_uri'));

    }

    /*
     * 获取code 中转网站
     * state:那个页面进来的
     * */
    public function centre()
    {
        if (!isset($_GET['code'])) {
            $state = $_GET['state']?trim(urlencode($_GET['state'])):$this->state;
            $url = 'https://open.weixin.qq.com/connect/qrconnect?appid='.$this->appid.'&redirect_uri='.$this->redirect_uri.'&response_type=code&scope='.$this->scope.'&state='. $state.'#wechat_redirect';
            header("location:$url");exit;
        } else {
            $code  = trim($_GET['code']);
            $state = trim(urldecode($_GET['state']));
            $openid = $this->getAccessToken($code);
            $server_url = $state.'&wx_openid='.$openid;
            header("location:$server_url");exit;
        }

    }

    //获取openid
    public function getAccessToken()
    {
        $code = $_GET['code'];
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->appid.'&secret='.$this->secret.'&code='.$code.'&grant_type=authorization_code';
        $access = file_get_contents($url);
        $data   = json_decode($access,true);
        return $data['openid'];

    }

}