轻源码

  • QingYuanMa.com
  • 全球最大的互联网技术和资源下载平台
搜索
一起源码网 门户 微信小程序 查看主题

面向新手《二十三》微信小程序简单总结,获取openid实例,

发布者: chinasars | 发布时间: 2018-1-27 19:29| 查看数: 8264| 评论数: 1|帖子模式

作者:赵吉彤,来自授权地址

1、添加一些图片素材(网上找的),复制到项目的根目录下面,和pages目录同级

2、查看微信文档介绍

3、打开blog文件夹,编辑blog.js,page函数里面添加对象,data对象表示数据,即和后台交互的数据都在这里面存储和展示,onLoad,onReady等函数是微信在页面加载时默认存在的函数,我们可以重写,实现我们自己的逻辑

4、点击编译查看对应的效果,及函数加载顺序,onLoad、onShow 、onReady的加载顺序

5、网络请求

打开微信文档,里面有对应的网络请求api,wx.request(),接收一个对象,包含我们请求的各种参数(交互的域名正式环境有限制,而且需要为https)

6、编辑blog.js,在onLoad函数里面发起网络请求,接口地址是我测试用的地址,会返回对应的数据列表,注意的地方是this指向问题,因为是在回调函数里面获取数据的,然后需要放到data对象里面,所以需要提前保存this对象的地址

现在进入页面就可看到控制台打印接收到的数据了(数据请求也可以这样发送)

  1. //发起网络请求
  2. wx.request({
  3. url: app.globalData.blog_url+'/article/findHotArticles.action',
  4. data:{
  5. size:20
  6. },
  7. success: function(res) {
  8. console.log(res.data);
  9. //把获取到的结果放到数据层
  10. that.setData({
  11. list:res.data
  12. })
  13. }
  14. })

7、ok,现在就是展示数据的时候了,打开微信微信官方文档,主要使用的是view标签,详情参考文档

8、展示层代码,使用 遍历文章对象,{{}} 取的是data数据层里面的数据,

9、绑定的下拉函数(不做处理)

10、处理样式,view标签可以使用CSS3的样式,并且微信本身也提供一些计算尺寸的方法,也支持样式选择器,类选择器,id选择器,直接看代码,编辑我们的blog.wxss

11、现在就可以保存,然后点击左侧的编译,就完成了列表展示

二:获取openid实例

作者:appss,来自原文地址

获取微信OpenId

  • 先获取code
  • 再通过code获取authtoken,从authtoken中取出openid给前台
  • 微信端一定不要忘记设定网页账号中的授权回调页面域名

流程图如下

主要代码

页面js代码

  1. /* 写cookie */
  2. function setCookie(name, value) {
  3. var Days = 30;
  4. var exp = new Date();
  5. exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
  6. document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/";
  7. }
  8. /* 读cookie */
  9. function getCookie(name) {
  10. var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
  11. if (arr != null) {
  12. return unescape(arr[2]);
  13. }
  14. return null;
  15. }
  16. /* 获取URL参数 */
  17. function getUrlParams(name) {
  18. var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  19. var r = window.location.search.substr(1).match(reg);
  20. if (r != null) {
  21. return unescape(r[2]);
  22. }
  23. return null;
  24. }
  25. /* 获取openid */
  26. function getOpenId(url) {
  27. var openid = getCookie("usropenid");
  28. if (openid == null) {
  29. openid = getUrlParams('openid');
  30. alert("openid="+openid);
  31. if (openid == null) {
  32. window.location.href = "wxcode?url=" + url;
  33. } else {
  34. setCookie("usropenid", openid);
  35. }
  36. }
  37. }

WxCodeServlet代码

  1. //访问微信获取code
  2. @Override
  3. protected void doPost(HttpServletRequest req, HttpServletResponse resp)
  4. throws ServletException, IOException {
  5. String state = req.getParameter("url");
  6. //WxOpenIdServlet的地址
  7. String redirect ="http://"+Configure.SITE+"/wxopenid";
  8. redirect = URLEncoder.encode(redirect, "utf-8");
  9. StringBuffer url = new StringBuffer("")
  10. .append(Configure.APP_ID).append("&redirect_uri=").append(redirect)
  11. .append("&response_type=code&scope=snsapi_base&state=").append(state).append("#wechat_redirect");
  12. resp.sendRedirect(url.toString());
  13. }

WxOpenIdServlet代码

  1. //访问微信获取openid
  2. @Override
  3. protected void doPost(HttpServletRequest req, HttpServletResponse resp)
  4. throws ServletException, IOException {
  5. String code = req.getParameter("code");
  6. String state = req.getParameter("state");
  7. Result ret = new Result();
  8. AuthToken token = WXUtil.getAuthToken(code);
  9. if(null != token.getOpenid()){
  10. ret.setCode(0);
  11. log.info("====openid=="+token.getOpenid());
  12. Map<String,String> map = new HashMap<String,String>();
  13. map.put("openid", token.getOpenid());
  14. map.put("state", state);
  15. ret.setData(map);
  16. }else{
  17. ret.setCode(-1);
  18. ret.setMsg("登录错误");
  19. }
  20. String redUrl = state+"?openid="+token.getOpenid();
  21. resp.sendRedirect(redUrl);
  22. }
  23. 复制代码
  24. 获取AuthTokenWXUtil.getAuthToken(code))代码
  25. public static AuthToken getAuthToken(String code){
  26. AuthToken vo = null;
  27. try {
  28. String uri = "";
  29. StringBuffer url = new StringBuffer(uri);
  30. url.append("appid=").append(Configure.APP_ID);
  31. url.append("&secret=").append(Configure.APP_SECRET);
  32. url.append("&code=").append(code);
  33. url.append("&grant_type=").append("authorization_code");
  34. HttpURLConnection conn = HttpClientUtil.CreatePostHttpConnection(url.toString());
  35. InputStream input = null;
  36. if (conn.getResponseCode() == 200) {
  37. input = conn.getInputStream();
  38. } else {
  39. input = conn.getErrorStream();
  40. }
  41. vo = JSON.parseObject(new String(HttpClientUtil.readInputStream(input),"utf-8"),AuthToken.class);
  42. } catch (Exception e) {
  43. log.error("getAuthToken error", e);
  44. }
  45. return vo;
  46. }

HttpClientUtil类

  1. package com.huatek.shebao.util;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.DataOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.net.HttpURLConnection;
  7. import java.net.MalformedURLException;
  8. import java.net.ProtocolException;
  9. import java.net.URL;
  10. public class HttpClientUtil {
  11. // 设置body体
  12. public static void setBodyParameter(String sb, HttpURLConnection conn)
  13. throws IOException {
  14. DataOutputStream out = new DataOutputStream(conn.getOutputStream());
  15. out.writeBytes(sb);
  16. out.flush();
  17. out.close();
  18. }
  19. // 添加签名header
  20. public static HttpURLConnection CreatePostHttpConnection(String uri) throws MalformedURLException,
  21. IOException, ProtocolException {
  22. URL url = new URL(uri);
  23. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  24. conn.setUseCaches(false);
  25. conn.setDoInput(true);
  26. conn.setDoOutput(true);
  27. conn.setRequestMethod("POST");
  28. conn.setInstanceFollowRedirects(true);
  29. conn.setConnectTimeout(30000);
  30. conn.setReadTimeout(30000);
  31. conn.setRequestProperty("Content-Type","application/json");
  32. conn.setRequestProperty("Accept-Charset", "utf-8");
  33. conn.setRequestProperty("contentType", "utf-8");
  34. return conn;
  35. }
  36. public static byte[] readInputStream(InputStream inStream) throws Exception {
  37. ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  38. byte[] buffer = new byte[1024];
  39. int len = 0;
  40. while ((len = inStream.read(buffer)) != -1) {
  41. outStream.write(buffer, 0, len);
  42. }
  43. byte[] data = outStream.toByteArray();
  44. outStream.close();
  45. inStream.close();
  46. return data;
  47. }
  48. }

封装AuthToken的VO类

  1. package com.huatek.shebao.wxpay;
  2. public class AuthToken {
  3. private String access_token;
  4. private Long expires_in;
  5. private String refresh_token;
  6. private String openid;
  7. private String scope;
  8. private String unionid;
  9. private Long errcode;
  10. private String errmsg;
  11. public String getAccess_token() {
  12. return access_token;
  13. }
  14. public void setAccess_token(String access_token) {
  15. this.access_token = access_token;
  16. }
  17. public Long getExpires_in() {
  18. return expires_in;
  19. }
  20. public void setExpires_in(Long expires_in) {
  21. this.expires_in = expires_in;
  22. }
  23. public String getRefresh_token() {
  24. return refresh_token;
  25. }
  26. public void setRefresh_token(String refresh_token) {
  27. this.refresh_token = refresh_token;
  28. }
  29. public String getOpenid() {
  30. return openid;
  31. }
  32. public void setOpenid(String openid) {
  33. this.openid = openid;
  34. }
  35. public String getScope() {
  36. return scope;
  37. }
  38. public void setScope(String scope) {
  39. this.scope = scope;
  40. }
  41. public String getUnionid() {
  42. return unionid;
  43. }
  44. public void setUnionid(String unionid) {
  45. this.unionid = unionid;
  46. }
  47. public Long getErrcode() {
  48. return errcode;
  49. }
  50. public void setErrcode(Long errcode) {
  51. this.errcode = errcode;
  52. }
  53. public String getErrmsg() {
  54. return errmsg;
  55. }
  56. public void setErrmsg(String errmsg) {
  57. this.errmsg = errmsg;
  58. }
  59. }

最新评论

xiebac 发表于 2022-5-15 05:00
歌曲编程软件下载

轻源码让程序更轻更快

QingYuanMa.com

工作时间 周一至周六 8:00-17:30

侵权处理

客服QQ点击咨询

关注抖音号

定期抽VIP

Copyright © 2016-2021 https://www.171739.xyz/ 滇ICP备13200218号

快速回复 返回顶部 返回列表