微信获取code和openid
$url = urlencode(服务器上面用户的访问路径);
$appId = 微信公众号的唯一标识号;
$redrecite_url = https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appId&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
SCOP: snsapi_userinfo(弹出用户授权页面,获取用户基本信息,即使在用户未关注的情况下,只要用户点击确定也可以回去基本信息)和snsapi_base (不跳出授权页面,只能获取用的openid信息)
STATE:重定向所带的参数,只能为a-zA-Z0-9并且不能超过128位
#wechat_redirect:必带参数
代码:
网页授权初始化页面:
$redirecturl= urlencode("http://www.zhiweihome.com/zhixiu/qiqi/code.php");
$appid='';
$url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirecturl.'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
header("Location:$url");自动跳转到code界面获取code值。
获取code界面:
$code= $_GET['code'];//前端传来的code值
$appid= "";
$appsecret= "";
//获取openid
$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
$result= https_request($url);
$jsoninfo= json_decode($result, true);
$openid= $jsoninfo["openid"];//从返回json结果中读出openid
echo$openid; //把openid送回前端