1 首先是认证的服务号
2 已经开启开发者模式
3 到开发者中心 -- 网页授权获取用户基本信息 填写网站域名 不带http://
3 自定义菜单 点击 打开网页 设置内容为 (也可以做一个中间跳转页面)
https://open.weixin.qq.com/connect/oauth2/authorize?appid=在开发者中心找&redirect_uri=回调网址&response_type=code&scope=snsapi_base&state=1#wechat_redirect
如果scope 参数是 snsapi_base 是静默的获取openid
snsapi_userinfo 获取用户基本信息 是需要用户确认的 由于用户同意过,所以无须关注,就可在授权后获取该用户的基本信息。
4 回调网址内容
// 1获取 code
if (isset($_GET['code'])){
$code= $_GET['code'];
}else{
// "没获取到数据 跳转页面";
}
// 2 根据 code 和 appid secret 获取 access_token
$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx4f96622722222&secret=69ece3785d2222ac5&code=$code&grant_type=authorization_code";
$rs= json_decode(file_get_contents($url));
// $rs->access_token
// $rs->openid
header('Location: www.php?a='.$rs->openid); //这里已经获取了openid
// 3 使用access_token获取用户信息 (必须是snsapi_userinfo 模式并且用户点击同意才能获取到)
$url="https://api.weixin.qq.com/sns/userinfo?access_token=".$rs->access_token."&openid=".$rs->openid;
$us= json_decode(file_get_contents($url));
var_dump($us);
5 www.php 处理页面
<?php
$oid=$_GET['a'];
require(dirname(__FILE__) . '/mobile/includes/init.php');
$sql = "SELECT * FROM oid WHERE oid = '".$oid."'"; //查询该openid 是否存在
$row = $db->getRow($sql);
setcookie('oid',$oid,3600); //保存cookie 登陆 注册时候绑定帐号用
if (empty($row['oid'])){ //如果没有查询到该openid 说明是新用户
$table = "oid";
$field_values = array("oid" => $oid);
$db->autoExecute($table, $field_values, "INSERT");
header('Location: /注册/');
}else{
if(empty($row['uname'])){ //如果有该用户信息 但是没绑定帐号
header('Location: /注册/');
exit;
}
设置用户名为 $row['uname']的用户登陆状态;
header('Location: /网站/');
}
?>