【微信公众平台网页版登陆】微信公众平台网页获取用户OpenID方法

更新时间:2019-09-19    来源:微信    手机版     字体:

【www.bbyears.com--微信】

用户点击微信自定义菜单view类型按钮后,微信客户端将会打开开发者在按钮中填写的url值 (即网页链接),达到打开网页的目的,但是view不能获取用户的openid,需要使用微信“网页授权获取用户基本信息”高级接口结合使用,获得用户的登入个人信息。

具体方法

1、配置网页授权回调域名,如 www.111cn.net

2、模拟公众号的第三方网页,http://www.111cn.net/getcodeurl.php

          
    if(isset($_SESSION["user"])){  
        print_r($_SESSION["user"]);
    exit;
    }
    $APPID="公众号在微信的appid";
    $REDIRECT_URI="http://www.111cn.net/callback.php";
    $scope="snsapi_base";
    //$scope="snsapi_userinfo";//需要授权
    $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$APPID."&redirect_uri=".urlencode($REDIRECT_URI)."&response_type=code&scope=".$scope."&state=".$state."#wechat_redirect";
    
    header("Location:".$url);
    ?>

3、第三方网页的回跳url中,首先从请求中取得code,然后根据code进一步换取openid和access_token,然后就可以根据openid和access_token调用微信的相关接口查询用户信息了。

        //http://www.111cn.net/callback.php
      
    $appid = "公众号在微信的appid";  
    $secret = "公众号在微信的app secret";  
    $code = $_GET["code"];  
    $get_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";

    $ch = curl_init();  
    curl_setopt($ch,CURLOPT_URL,$get_token_url);  
    curl_setopt($ch,CURLOPT_HEADER,0);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );  
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);  
    $res = curl_exec($ch);  
    curl_close($ch);  
    $json_obj = json_decode($res,true);  
      
    //根据openid和access_token查询用户信息  
    $access_token = $json_obj["access_token"];  
    $openid = $json_obj["openid"];  
    $get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";  
      
    $ch = curl_init();  
    curl_setopt($ch,CURLOPT_URL,$get_user_info_url);  
    curl_setopt($ch,CURLOPT_HEADER,0);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );  
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);  
    $res = curl_exec($ch);  
    curl_close($ch);  
      
    //解析json  
    $user_obj = json_decode($res,true);  
    $_SESSION["user"] = $user_obj;  
    print_r($user_obj);  
      
    ?>  

参考资料

网页授权获取用户基本信息

http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html

本文来源:http://www.bbyears.com/shoujikaifa/68683.html

热门标签

更多>>

本类排行