一、设置APPID等参数
1 <?php 2 //scope=snsapi_base 实例 3 $appid='*****APPID****'; 4 $redirect_uri = urlencode ( 'http://***域名**/getUserInfo.php' ); 5 $url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_base&state=1#wechat_redirect"; 6 header("Location:".$url);
二、获取用户信息
1 <?php 2 include("DBDA.class.php"); 3 $appid = "******APPID*****"; 4 $secret = "*****secret****"; 5 $code = $_GET["code"]; 6 7 //第一步:取全局access_token 8 $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret"; 9 $token = getJson($url); 10 11 //第二步:取得openid 12 $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code"; 13 $oauth2 = getJson($oauth2Url); 14 15 //第三步:根据全局access_token和openid查询用户信息 16 $access_token = $token["access_token"]; 17 $openid = $oauth2['openid']; 18 $get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN"; 19 $userinfo = getJson($get_user_info_url); 20 21 //打印用户信息 22 $openid = $userinfo['openid']; 23 session_start(); 24 $SESSION['openid']=$openid; 25 $db = new DBDA(); 26 27 28 if($openid!=""){ 29 header("Location:http://***域名**/mparents/login1/index"); 30 } 31 32 function getJson($url){ 33 $ch = curl_init(); 34 curl_setopt($ch, CURLOPT_URL, $url); 35 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 36 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 37 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 38 $output = curl_exec($ch); 39 curl_close($ch); 40 return json_decode($output, true); 41 }