微信公众号授权

对接微信授权,由于之前没有这方面经验,开发完成便写下博客记录开发过程

公众号中微信授权开发步骤:

1.准备内网穿透工具 ngrok

   原因: 开发测试过程中,每次修改都需要打包然后翻到服务器上看效果,非常不方便,当然,不用这个工具也可以

   下载地址: https://dashboard.ngrok.com/get-started  

   如何使用: 解压后会得到一个ngrok.exe文件 ,然后在当前目录下打开cmd窗口 执行指令

                       nrgok http 8080  //8080改成 你的项目跑的端口

                       效果如下,我们可以得到一个公网可以访问的临时域名, 窗口勿关闭,因为每次的分配的域名不同

                        

2.测试环境 

  微信有提供接口测试环境 ,进入以下域名,申请一个测试号,并关注

  https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index

 找到 网页服务-网页账号-修改

 

 点击修改 

 

 改成ngrok中分配的域名

3.码代码

  参考官方文档,结合以下代码

  https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html

 编写工具类,用于发起请求 

 

public class WeixinUtil {
	public static final String APPID="你的appid";
	public static final String APPSECRET="你的appscret";
     
    //用于发起get请求
	public static JSONObject doGetStr(String url) {
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(url);
			JSONObject jsonObject=null;
			try {
				HttpResponse respone = httpClient.execute(httpGet);
				HttpEntity entity = respone.getEntity();
				if(entity!=null) {
					String result = EntityUtils.toString(entity,"UTF-8");
					jsonObject = JSONObject.fromObject(result);
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return jsonObject;
	}
   //用于发起post请求
   public static JSONObject doPostStr(String url,String outStr) {
	   DefaultHttpClient httpClient = new DefaultHttpClient();
	   HttpPost httpPost = new HttpPost(url);
	   JSONObject jsonObject  = null;
	   try {
		   httpPost.setEntity(new StringEntity(outStr, "UTF-8"));
		   HttpResponse respone = httpClient.execute(httpPost);
		   HttpEntity entity = respone.getEntity();
			if(entity!=null) {
				String result = EntityUtils.toString(entity,"UTF-8");
				jsonObject = JSONObject.fromObject(result);
			}
	   } catch (Exception e) {
			e.printStackTrace();
		}
	   return jsonObject;
   }
   

}

 按照步骤来 

  ·1.获取code

    向这个地址发起请求,将其中的各项参数替换掉,重定向过去 

  https://open.weixin.qq.com/connect/oauth2/authorize?    appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect

  @RequestMapping("login")
    public String login(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
        String sendUrl = url.replace("APPID", WeixinUtil.APPID)
                .replace("REDIRECT_URI", URLEncoder.encode("http://a9d21e30.ngrok.io/call", "utf-8"))  
                .replace("SCOPE", "snsapi_userinfo").replace("STATE", "1");
       return "redirect:"+sendUrl;
    }

 上述方法执行后,前端悔跳到一个页面,让用户确定授权

  

当用户点击确定后,则需要进行,我们就可以来获取用户的信息了 

 代码如下 

    @RequestMapping("call")
    public void callback(HttpServletRequest request){
        String access_Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        access_Url = access_Url.replace("APPID", WeixinUtil.APPID).replace("SECRET", WeixinUtil.APPSECRET ).replace("CODE", request.getParameter("code"));
        JSONObject token_data = WeixinUtil.doGetStr(access_Url); //获取access_token 这个是可以access_token无限制获取的 
        if(token_data.getString("openid")!=null && token_data.getString("openid").length()>0) { 
            String userinfo_Url="https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
            userinfo_Url = userinfo_Url.replace("ACCESS_TOKEN", token_data.getString("access_token")).replace("OPENID", token_data.getString("openid"));
            JSONObject  userinfo = WeixinUtil.doGetStr(userinfo_Url); //获取用户信息     
            System.out.println(userinfo);
            
        }else{
    System.out.println("信息获取失败");
       }
        
    }

至此,用户授权就差不多了

### 实现微信公众号授权登录的方法 #### 准备工作 为了实现微信公众号授权登录,需先完成必要的准备工作。这包括注册并认证一个微信公众号,在微信公众平台的开发者中心配置服务器地址和回调URL,并获取`AppID`和`AppSecret`[^1]。 #### 授权流程概述 一旦准备阶段完毕,接下来就是理解整个授权过程的工作原理。当用户点击登录按钮后,会自动跳转到由微信提供的授权页面。在此页面上,用户需要使用其微信账号进行身份验证并确认授权请求。成功之后,微信将把用户重定向回到预先设定的应用程序网址,并附加一个临时授权码作为参数传递给应用程序[^2]。 #### 获取访问令牌 收到授权码后,下一步是从微信接口交换得到访问令牌(access_token)。此操作通过向特定API发送POST请求来完成,其中应包含早前获得的`AppID`、`AppSecret`以及刚刚接收到的授权码。成功的响应将返回JSON对象形式的数据,内含所需的访问令牌和其他相关信息。 ```php // PHP示例代码用于换取access_token $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,"https://api.weixin.qq.com/sns/oauth2/access_token"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query( array('appid' => $appId,'secret'=> $appSecret,'code'=>$authCode,'grant_type'=>'authorization_code') )); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec ($ch); curl_close ($ch); $data = json_decode($response,true); // 将json字符串转换成数组处理 if(isset($data['access_token'])){ echo "Access Token: ".$data['access_token']; } else { echo 'Error fetching access token'; } ``` #### 用户信息拉取 最后一步是利用取得的访问令牌去调用微信开放平台提供的其他服务端口,比如获取用户的个人信息。同样地,这也是通过对指定API发起GET请求的方式来进行,传入必需的身份凭证即可接收期望的结果数据。 ```php // 使用access_token获取用户基本信息 $userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token={$data['access_token']}&openid={$data['openid']}"; $userInfoResponse = file_get_contents($userInfoUrl); $userInfoData = json_decode($userInfoResponse, true); print_r($userInfoData); // 输出用户信息供调试查看 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值