php怎么实现微信登录

发布时间:2022-05-25 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php怎么实现微信登录脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

phP实现微信登录的方法:1、经用户同意授权,获取code;2、通过code换取网页授权access_token;3、获取用户信息。

php怎么实现微信登录

本文操作环境:windows10系统、PHP 7ThinkPad t480脑。

使用php实现微信登录其实并不难,可以简单地分为三步进行,如下所示:

第一步:用户同意授权,获取code

//微信登录
	public function wxlogin()
	{
		$appid = "";
   	 	$secret = "";
   	 	
   	 	$str="http://***.***.COM/getToken";
   	 	$redirect_uri=urlencode($str);
		//通过code获得 access_token + oPEnid
		$url="https://open.weixin.QQ.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
      
       header("Location:" . $url);
	}

第二步:通过code换取网页授权access_token

public function getToken()
{
$code = $_GET["code"];

        $appid = "";
       $secret = "";

//通过code获得 access_token + openid
       $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid
        ."&secret=" . $secret . "&code=" . $code . "&grant_type=authorization_code";
        $jsonResult =$this->https_request($url);
        $resultArray = json_decode($jsonResult, true);

        $access_token = $resultArray["access_token"];
        $openid = $resultArray["openid"];

//第三步  获取用户信息
         //通过access_token + openid 获得用户所有信息,结果全部存储在$infoArray里,后面再写自己的代码逻辑
        $infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid.'&lang=zh_CN';
        $infoResult = $this->https_request($infoUrl);
        $infoArray = json_decode($infoResult, true);

       if($infoArray['unionid'])
        {
        
     }

}

附加:代码中用到的方法

// An highlighted block
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;
	}

推荐学习:php培训

以上就是php怎么实现微信登录的详细内容,更多请关注脚本宝典其它相关文章

脚本宝典总结

以上是脚本宝典为你收集整理的php怎么实现微信登录全部内容,希望文章能够帮你解决php怎么实现微信登录所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。