微信小程序现在成为了增长模式的宠儿,小程序的便利想必看这篇博客的各位都已经了解到了,本篇呢主要介绍小程序里面获取openId的方法。
其中涉及关键词:
openId:微信小程序用户唯一标示。
openUrl:微信为指定的小程序获取accessToken所需要的链接,开发者文档上有。https://developers.weixin.qq.com/miniprogram/dev/api/ (https://api.weixin.qq.com/sns/jscode2session?appid="+小程序appId+"&secret="+小程序secret+"&grant_type=authorization)
主要是用户小程序里面运行所需要的各个阶段openId。
需要小程序运营人员事先申请号小程序的appId和sercet,这两个在申请小程序主体时会得到。
其中调用顺序从上到下
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.获取下程序openID,其中code为小程序code,这个方法比较通用适合各个小程序 /** * 获取微信openId,如果获取失败失败null * @param code * @return */ public String getOpenId(String code,String appId,String secret){ LOGGER.info("获取微信openid的code=", code," ,appId=",appId," ,secret=",secret); String url="https://api.weixin.qq.com/sns/jscode2session?appid="+appId+"&secret="+secret+"&grant_type=authorization_code&js_code="; String httpResult = HttpClientUtils.httpsGet(url+code); if(StringUtils.isBlank(httpResult)){ LOGGER.error("获取微信openid异常 code:{}", code); return null; } return extractOpenId(httpResult); }3.解析微信返回生成openID,其中session_key 可用于服务端获取用户微信信息,昵称,头像,地址
/** * 解析openid * @param httpResult * @return */ private String extractOpenId(String httpResult){ JSONObject httpContent = JSONObject.parseObject(httpResult); String openId = httpContent.getString("openid"); String session_key = httpContent.getString("session_key"); if(StringUtils.isNotBlank(openId) && StringUtils.isNotBlank(session_key)){ redisHandler.setexValue(openId,session_key, DateUtil.getTodayResidueSeconds()); } LOGGER.info("获取微信openid的httpContent=", httpContent.toJSONString()); if(openId == null){ LOGGER.error("获取openId出错 errcode ", httpContent.get("errcode"), " errmsg: ", httpContent.get("errmsg")); return null; } return openId; }五、感悟与展望
在人口红利消退的下半场,用户增长是公共难题。硅谷出现了“Growth Hacker”,中国出现了“精细化运营”,两岸不约而同的出现了以数据为基础,以人工智能为抓手的新增长模式。潜客发掘,流失召回,用户留存,状态跃迁,一批新的模型被定义出来,成为先进增长模式的关键词。流量为王的时代还没有过去,与君共勉。
注:有些技术细节不便在本文中展示体现,如有问题可以评论私信,必有回响。
