php 微信公众号登录,PHP 实现微信公众号网页授权登录

本文详细介绍了微信OAuth2.0授权的三个步骤:首先,用户在index.php页面同意授权并获取code;然后,通过test.php页面的code换取access_token和openid;最后,使用access_token和openid获取用户的详细信息,包括openid、性别、语言、城市等。这个过程对于实现微信登录或获取用户资料功能至关重要。
摘要由CSDN通过智能技术生成

‍‍

第一步:index.php页面,用户同意授权,获取code<?php

$appid = 'APPID';

$redirect_uri = urlencode('http://example.com/test.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);

第二步:test.php页面,通过返回的code获取网页授权的access_token<?php

$appid = "APPID";

$secret = "APPSECRET";

$code = $_GET["code"];

$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'];

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);

}

第三步:通过access_token和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);

//array('openid' => 'oiuH-xxxxxxxxxxxxx',

'sex' => 1,

'language' => 'zh_CN',

'city' => '南宁',

'province' => '广西',

'country' => '中国',

'headimgurl' => '',

'privilege' => array()

);

‍‍

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值