微信开发 网页授权,获取用户信息

介绍

网页授权分两种 snsapi_basesnsapi_userinfo
snsapi_base 需要关注公众号才可以获取用户信息,但是用户无感
snsapi_userinfo 则不需要关注公众号,但需要用户确认是否被获取
这里以 snsapi_userinfo 为例实现获取用户信息

建立一个访问页面index.php

<?php
//scope=snsapi_userinfo实例
$appid='微信appid';
$redirect_uri = urlencode ( 'http://存放地址/getUserInfo.php' );
$url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
header("Location:".$url);

建立getUserInfo.php

<?php

$appid = "微信appid";
$secret = "微信secret";
$code = $_GET["code"];

//第一步:取得openid
$oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
$oauth2 = getJson($oauth2Url);

//第二步:根据全局access_token和openid查询用户信息
$access_token = $oauth2["access_token"];
$openid = $oauth2['openid'];
$get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
$userinfo = getJson($get_user_info_url);

//打印用户信息
print_r($userinfo);

function getJson($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    curl_close($ch);
    return json_decode($output, true);
}

访问

将两个文件直接放于服务器上,访问 index.php 地址即可

错误

access_token 非法 错误

解决方案参考

40001 无权限 错误

细察上面代码引用的
接口地址是
https://api.weixin.qq.com/sns/userinfo
而不是
https://api.weixin.qq.com/cgi-bin/user/info

获取用户信息思路

  1. 打开index.php页面跳转到getUserInfo.php页面
  2. 获取并存储用户信息,跳转到内容页面
    这么做是因为 网页授权获取用户信息 调用次数500 0000 次
    在这里插入图片描述

存储用户信息的思路

每次都进行建立连接,这样的实现方式是短链接,用完即关闭连接。因为mysql支持同一时间几千个连接数。而且我们的连接也没有到达一定量,不需要缓存实例或建立长连接

微信信息表结构

wx_OpenAndShare  
id,openid,nickname,phone,open,share,project,time
wx_Information
id,openid,nickname,sex,province,city,country,headimgurl,language,phone,privilege,unionid,project,time

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/tianxiaojie_blog/article/details/103522394