微信授权(获取openid和userinfo信息)

获取openid和userinfo信息

一:基于微信公众号的授权登录,获取openid和用户信息。

第一步:用户同意授权,获取code

在确保微信公众账号拥有授权作用域(scope参数)的权限的前提下(服务号获得高级接口后,默认拥有scope参数中的snsapi_base和snsapi_userinfo),引导关注者打开如下页面:

 

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect 若提示“该链接无法访问”,请检查参数是否填写错误,是否拥有scope参数对应的授权作用域权限。

代码实现:

package com.cxb.otherWx;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import com.cxb.wx.accesstoken.Account;
/**
 * @author ChenXb
 *
 *         2018年4月19日
 *                     这里从授权到获取微信openid以及用户信息完结
 */
public class WxAuthor {
//微信授权的地址
private static final String AUTHORIZE_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";

/*
* 获取网页授权url
*/
public static String getAuthorize_url() {
String REDIRECT_URI=null;
try {
//这里的url就是访问你后台的链接地址
REDIRECT_URI = URLEncoder.encode("http://www.joffro.com/Activity/sendMessage/sendMsg?appid=**************","UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//scope 应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),
//snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 )
String url = AUTHORIZE_URL.replace("APPID", Account.APPID).replace("REDIRECT_URI", REDIRECT_URI)
.replace("SCOPE", "snsapi_userinfo").replace("STATE", "123");
return url;
}

public static void main(String[] args) {
//这里的链接copy到微信浏览器里面访问
String authorize_url = getAuthorize_url();
System.out.println(authorize_url);
//根据上面的链接在微信里面访问到后台的配置链接  
//这些代码则是后台处理的逻辑,获取openid和userinfo等信息
/*String code = getPara("code");
log.error("*********code****"+code);
//根据code获取openid
String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+APPID
+ "&secret="+APPSECRET
+ "&code="+code
+ "&grant_type=authorization_code";
JSONObject jsonObject = doGetJson(url);
String openid = jsonObject.getString("openid");
log.error("*****openid***>"+openid);
String accessToken = jsonObject.getString("access_token");
//根据openid获取用户信息
String getUserInfoUrl="https://api.weixin.qq.com/sns/userinfo?access_token="+accessToken
+ "&openid="+openid
+ "&lang=zh_CN";
JSONObject userInfo = doGetJson(getUserInfoUrl);
log.error("*****userInfo****"+userInfo);*/

}
}
 //以下代码是后台程序中用到的   这里是上面配置的访问链接的后台地址
public static final String APPID="************************";   //这里修改为自己的APPID
public static final String APPSECRET="*********************";    //这里修改为自己的APPSECRET
public static JSONObject doGetJson(String url){
JSONObject jsonObject=null;
//这个方法过时了 换成下面的方式了
//DefaultHttpClient client=new DefaultHttpClient();
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet=new HttpGet(url);
HttpResponse response = null;
try {
response = httpclient.execute(httpGet);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity entity=response.getEntity();
if(entity!=null){
String result = null;
try {
result = EntityUtils.toString(entity,"UTF-8");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jsonObject = JSONObject.fromObject(result);
}
//处理完后,释放链接
httpGet.releaseConnection();
return jsonObject;

}

 

附录:

要在微信浏览器中获取openid,需要进行以下步骤: 1. 引入微信JS SDK 在网页中引入微信JS SDK,可以通过以下代码实现: ``` <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script> ``` 2. 配置微信JS SDK 在JS代码中,需要进行微信JS SDK的配置,例如: ``` wx.config({ debug: false, appId: 'your_app_id', timestamp: 1594736109, nonceStr: 'your_nonce_str', signature: 'your_signature', jsApiList: ['checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage'] }); ``` 其中,appId、timestamp、nonceStr和signature需要在服务器端进行计算和签名,并将结果传递给客户端。可以参考微信官方文档进行计算和签名。 3. 获取用户授权 在JS代码中,需要调用微信JS SDK提供的接口,获取用户授权,例如: ``` wx.ready(function() { wx.getUserInfo({ success: function(res) { var userInfo = res.userInfo; var nickName = userInfo.nickName; var avatarUrl = userInfo.avatarUrl; var gender = userInfo.gender; //性别 0:未知、1:男、2:女 var province = userInfo.province; var city = userInfo.city; var country = userInfo.country; } }); }); ``` 在用户授权后,可以获取到用户的基本信息,包括头像、昵称、性别、地区等。 4. 获取openid 通过微信JS SDK提供的接口,可以获取用户的openid,例如: ``` wx.ready(function() { wx.login({ success: function(res) { if (res.code) { // 发起网络请求 wx.request({ url: 'https://your.domain.com/api/getOpenId', data: { code: res.code }, success: function(res) { var openid = res.data.openid; console.log(openid); } }) } else { console.log('登录失败!' + res.errMsg) } } }); }); ``` 在获取到用户的code后,可以将code发送到服务器端,进行openid获取。服务器端需要进行相应的处理,包括获取access_token、获取openid等。可以参考微信官方文档进行开发。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值