微信小程序获取accessToken方法

mac2025-10-31  18

一、前言

微信小程序现在成为了增长模式的宠儿,小程序的便利想必看这篇博客的各位都已经了解到了,本篇呢主要介绍小程序里面获取accessToken的方法。

其中涉及关键词:

accessToken:通过用户验证登录和授权,获取Access Token,为下一步获取用户的OpenID做准备。

tokenUrl:微信为指定的小程序获取accessToken所需要的链接,开发者文档上有。https://developers.weixin.qq.com/miniprogram/dev/api/

二、需求场景

主要是用户小程序获取openId,发送消息,微信支付,提现(商户退款)等多个场景使用。

三、准备

需要小程序运营人员事先申请号小程序的appId和sercet,这两个在申请小程序主体时会得到。

四、服务端(Java)获取

其中调用顺序为从上到下

1.需要的jar包maven坐标

<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.3</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.4</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.4</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency>

2.获取小程序的access Token代码,这个tokenUrl让调用方传过来比较通用

tokenUrl格式:

https://api.weixin.qq.com/cgi-bin/token?appid=你的小程序ID&secret=你的小程序密钥&grant_type=client_credential /** * 获取制定小程序的accesstoken * @param tokenUrl 获取该 token的链接 * @return */ public static String getAccessToken(String tokenUrl){ String s = HttpClientUtils.httpsGet(tokenUrl); if(s == null){ logger.error("获取微信accesstoken失败"); return null; } JSONObject result = JSONObject.parseObject(s); logger.info("access Token 获取结果 :", result.toJSONString()); return result.getString("access_token"); }

3.获取调用所需要的get请求方法

/** * https get请求 * @param url * @return */ public static String httpsGet(String url){ LOGGER.info("httpClient get入参:",url); Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory)new SSLProtocolSocketFactory(), 443)); HttpClient httpclient = new HttpClient(); GetMethod getMethod = new GetMethod(url); try { int status = httpclient.executeMethod(getMethod); LOGGER.info("httpClient get结果:", status, ", 出参:", getMethod.getResponseBodyAsString()); return getMethod.getResponseBodyAsString(); } catch (Exception e){ LOGGER.error("httpClient get error异常:", e); }finally { getMethod.releaseConnection(); } return null; }

 

五、总结与展望

    在人口红利消退的下半场,用户增长是公共难题。硅谷出现了“Growth Hacker”,中国出现了“精细化运营”,两岸不约而同的出现了以数据为基础,以人工智能为抓手的新增长模式。潜客发掘,流失召回,用户留存,状态跃迁,一批新的模型被定义出来,成为先进增长模式的关键词。流量为王的时代还没有过去,与君共勉。

 

注:有些技术细节不便在本文中展示体现,如有问题可以评论私信,必有回响。

最新回复(0)