公众号登录认证部分代码
2024-04-07


//1.换取code
  $appid = 'xxxxxx';//公众号appid
  $REDIRECT_URI = 'https://xxxx';//回调页面url
  $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$REDIRECT_URI}&response_type=code&scope=snsapi_userinfo#wechat_redirect";
  $this->redirect($url);
//2.回调页面拿到code,调用接口获取openid和用户信息
    $code = 'xxxxx';
    $appid = 'xxxxx';
    $APPSECRET = 'xxxxx';
    $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid
           . "&secret=" . $APPSECRET . "&code=" . $code . "&grant_type=authorization_code";
    $jsonResult = $this->reqs($url);
    $resultArray = json_decode($jsonResult, true);
    if(!$resultArray || !isset($resultArray['openid']) || !$resultArray['openid']) return ;

    $openid = $resultArray['openid']??'xx';
    $access_token = $resultArray['access_token']??'xx';

    $infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid . '&lang=zh_CN';
    $infoResult = $this->reqs($infoUrl);
    $infoArray = json_decode($infoResult, true);

    if(!$infoArray) return ;
    var_dump($infoArray);