微信小程序

wx.login({
success (res) {
if (res.code) {
//发起网络请求
wx.request({
url: ‘https://test.com/onLogin’,
data: {
code: res.code
}
})
} else {
console.log(‘登录失败!’ + res.errMsg)
}
}
})

scope
对应接口
描述
scope.userInfo
wx.getUserInfo
用户信息
scope.userLocation
wx.getLocation, wx.chooseLocation
地理位置
scope.address
wx.chooseAddress
通讯地址
scope.invoiceTitle
wx.chooseInvoiceTitle
发票抬头
scope.werun
wx.getWeRunData
微信运动步数
scope.record
wx.startRecord
录音功能
scope.writePhotosAlbum
wx.saveImageToPhotosAlbum, wx.saveVideoToPhotosAlbum
保存到相册
scope.camera

摄像头

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
}
})

请求地址url为:
GET https://api.weixin.qq.com/sns/jscode2sessionappid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
我来解释下请求的参数

属性 类型 默认值 必填 说明
appid string 是 小程序 appId
secret string 是 小程序 appSecret
js_code string 是 登录时获取的 code
grant_type string 是 授权类型,此处只需填写 authorization_code
————————————————
、返回值
Object
返回的 JSON 数据包

属性 类型 说明
openid string 用户唯一标识
session_key string 会话密钥
unionid string 用户在开放平台的唯一标识符,在满足 UnionID 下发条件的情况下会返回,详见 UnionID 机制说明。
errcode number 错误码
errmsg string 错误信息

在这里插入图片描述

在这里插入图片描述
.index.wxml

    <view class='content'>
        <view>申请获取以下权限</view>
        <text>获得你的公开信息(昵称,头像等)</text>
    </view>

    <button class='bottom' type='primary' open-type="getUserInfo" lang="zh_CN" bindgetuserinfo="bindGetUserInfo">
        授权登录
    </button>
</view>
<view wx:else>请升级微信版本</view>

index.wcss

.header {
margin: 90rpx 0 90rpx 50rpx;
border-bottom: 1px solid #ccc;
text-align: center;
width: 650rpx;
height: 300rpx;
line-height: 450rpx;
}

.header image {
width: 200rpx;
height: 200rpx;
}

.content {
margin-left: 50rpx;
margin-bottom: 90rpx;
}

.content text {
display: block;
color: #9d9d9d;
margin-top: 40rpx;
}

.bottom {
border-radius: 80rpx;
margin: 70rpx 50rpx;
font-size: 35rpx;
}

.index.js

Page({
data: {
//判断小程序的API,回调,参数,组件等是否在当前版本可用。
canIUse: wx.canIUse(‘button.open-type.getUserInfo’),
isHide: false
},

onLoad: function() {
    var that = this;
    // 查看是否授权
    wx.getSetting({
        success: function(res) {
            if (res.authSetting['scope.userInfo']) {
                wx.getUserInfo({
                    success: function(res) {
                        // 用户已经授权过,不需要显示授权页面,所以不需要改变 isHide 的值
                        // 根据自己的需求有其他操作再补充
                        // 我这里实现的是在用户授权成功后,调用微信的 wx.login 接口,从而获取code
                        wx.login({
                            success: res => {
                                // 获取到用户的 code 之后:res.code
                                console.log("用户的code:" + res.code);
                                // 可以传给后台,再经过解析获取用户的 openid
                                // 或者可以直接使用微信的提供的接口直接获取 openid ,方法如下:
                                // wx.request({
                                //     // 自行补上自己的 APPID 和 SECRET
                                //     url: 'https://api.weixin.qq.com/sns/jscode2session?appid=自己的APPID&secret=自己的SECRET&js_code=' + res.code + '&grant_type=authorization_code',
                                //     success: res => {
                                //         // 获取到用户的 openid
                                //         console.log("用户的openid:" + res.data.openid);
                                //     }
                                // });
                            }
                        });
                    }
                });
            } else {
                // 用户没有授权
                // 改变 isHide 的值,显示授权页面
                that.setData({
                    isHide: true
                });
            }
        }
    });
},

bindGetUserInfo: function(e) {
    if (e.detail.userInfo) {
        //用户按了允许授权按钮
        var that = this;
        // 获取到用户的信息了,打印到控制台上看下
        console.log("用户的信息如下:");
        console.log(e.detail.userInfo);
        //授权成功后,通过改变 isHide 的值,让实现页面显示出来,把授权页面隐藏起来
        that.setData({
            isHide: false
        });
    } else {
        //用户按了拒绝按钮
        wx.showModal({
            title: '警告',
            content: '您点击了拒绝授权,将无法进入小程序,请授权之后再进入!!!',
            showCancel: false,
            confirmText: '返回授权',
            success: function(res) {
                // 用户没有授权成功,不需要改变 isHide 的值
                if (res.confirm) {
                    console.log('用户点击了“返回授权”');
                }
            }
        });
    }
}

})

我的首页内容

login.wxml文件编写页面


登陆

login.js里面写逻辑
// pages/login_test/login.js
Page({

/**
 * 页面的初始数据
 */
data: {
    username:'',
    password:''
},

input_name:function(e){
this.setData({
username:e.detail.value
})
},
input_pwd: function (e) {
this.setData({
password: e.detail.value
})
},
submitButton:function(){
console.log(“点击按钮!” + “获取到的用户名:” + this.data.username + “获取到的密码:” + this.data.password)
var that = this;

    wx.request({
      url: 'http://localhost:8080/login',
        method:'POST',
        header:{'content-type':'application/x-www-form-urlencoded'},
        data:{
          'username': that.data.username,
          'password': that.data.password
        },
        success:function(res){
            console.log("回调函数:"+res.data)
            var resData = res.data;
            if(resData == true){
                wx.showToast({
                    title: '登录成功',
                    duration:2000
                })
            }else{
                wx.showToast({
                    title: '登录失败',
                    duration:2000
                })
            }
        }

    })


},


/**
 * 生命周期函数--监听页面加载
 */
onLoad: function (options) {

},

/**
 * 生命周期函数--监听页面初次渲染完成
 */
onReady: function () {

},

/**
 * 生命周期函数--监听页面显示
 */
onShow: function () {

},

/**
 * 生命周期函数--监听页面隐藏
 */
onHide: function () {

},

/**
 * 生命周期函数--监听页面卸载
 */
onUnload: function () {

},

/**
 * 页面相关事件处理函数--监听用户下拉动作
 */
onPullDownRefresh: function () {

},

/**
 * 页面上拉触底事件的处理函数
 */
onReachBottom: function () {

},

/**
 * 用户点击右上角分享
 */
onShareAppMessage: function () {

}

})

Controller类
package com.springboot.controller;

import com.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**

  • Created by Administrator on 2018\9\8 0008.
    */
    @RestController
    public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public boolean login (String username, String password){
    System.out.println ( “微信小程序调用接口!!!用户名:” + username + “密码:” + password );
    boolean login = userService.login ( username, password );
    if (login) {
    return true;
    }
    return false;
    }
    }

Service类
package com.springboot.service;

public interface UserService {
boolean login(String username,String password);
}

实现Service类

package com.springboot.service;

import com.springboot.dao.UserEntityMapper;
import com.springboot.dao.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserEntityMapper userEntityMapper;
@Override
public boolean login(String username,String password){
UserEntity userEntity = new UserEntity ();
userEntity.setUsername ( username );
userEntity.setPassword ( password );

    UserEntity user = userEntityMapper.selectUser ( userEntity );
    if (user != null){
        return true;
    }
    return false;
}

}

Mapper类

UserEntity selectUser(UserEntity userEntity);

Mapper.xml

select * from user where username=#{username} and password=#{password}

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.7</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.56</version>
    </dependency>

开发一个请求工具类

package com.vx.utils;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**

  • @author zty
    */
    public class HttpClientUtil {

    public static String doGet(String url, Map<String, String> param) {

      // 创建Httpclient对象
      CloseableHttpClient httpclient = HttpClients.createDefault();
    
      String resultString = "";
      CloseableHttpResponse response = null;
      try {
          // 创建uri
          URIBuilder builder = new URIBuilder(url);
          if (param != null) {
              for (String key : param.keySet()) {
                  builder.addParameter(key, param.get(key));
              }
          }
          URI uri = builder.build();
    
          // 创建http GET请求
          HttpGet httpGet = new HttpGet(uri);
    
          // 执行请求
          response = httpclient.execute(httpGet);
          // 判断返回状态是否为200
          if (response.getStatusLine().getStatusCode() == 200) {
              resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
          }
      } catch (Exception e) {
          e.printStackTrace();
      } finally {
          try {
              if (response != null) {
                  response.close();
              }
              httpclient.close();
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
      return resultString;
    

    }

    public static String doGet(String url) {
    return doGet(url, null);
    }

    public static String doPost(String url, Map<String, String> param) {
    // 创建Httpclient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    String resultString = “”;
    try {
    // 创建Http Post请求
    HttpPost httpPost = new HttpPost(url);
    // 创建参数列表
    if (param != null) {
    List paramList = new ArrayList<>();
    for (String key : param.keySet()) {
    paramList.add(new BasicNameValuePair(key, param.get(key)));
    }
    // 模拟表单
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
    httpPost.setEntity(entity);
    }
    // 执行http请求
    response = httpClient.execute(httpPost);
    resultString = EntityUtils.toString(response.getEntity(), “utf-8”);
    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    try {
    response.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

      return resultString;
    

    }

    public static String doPost(String url) {
    return doPost(url, null);
    }

    public static String doPostJson(String url, String json) {
    // 创建Httpclient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    String resultString = “”;
    try {
    // 创建Http Post请求
    HttpPost httpPost = new HttpPost(url);
    // 创建请求内容
    StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
    httpPost.setEntity(entity);
    // 执行http请求
    response = httpClient.execute(httpPost);
    resultString = EntityUtils.toString(response.getEntity(), “utf-8”);
    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    try {
    response.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

      return resultString;
    

    }
    }
    开发一个json转实体类的工具类
    package com.vx.utils;

import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
*

  • @Title: JsonUtils.java

  • @Package com.lee.utils

  • @Description: 自定义响应结构, 转换类

  • Copyright: Copyright © 2016

  • Company:Nathan.Lee.Salvatore

  • @author zty

  • @date 2020年4月15日 下午11:05:03

  • @version V1.0
    */
    public class JsonUtils {

    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**

    • 将对象转换成json字符串。
    • Title: pojoToJson

    • Description:

    • @param data
    • @return
      */
      public static String objectToJson(Object data) {
      try {
      String string = MAPPER.writeValueAsString(data);
      return string;
      } catch (JsonProcessingException e) {
      e.printStackTrace();
      }
      return null;
      }

    /**

    • 将json结果集转化为对象
    • @param jsonData json数据
    • @param clazz 对象中的object类型
    • @return
      */
      public static T jsonToPojo(String jsonData, Class beanType) {
      try {
      T t = MAPPER.readValue(jsonData, beanType);
      return t;
      } catch (Exception e) {
      e.printStackTrace();
      }
      return null;
      }

    /**

    • 将json数据转换成pojo对象list

    • Title: jsonToList

    • Description:

    • @param jsonData

    • @param beanType

    • @return
      */
      public static List jsonToList(String jsonData, Class beanType) {
      JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
      try {
      List list = MAPPER.readValue(jsonData, javaType);
      return list;
      } catch (Exception e) {
      e.printStackTrace();
      }

      return null;
      }

}

/**
*后端控制器
*
*/
package cn.ailanglang.diary.login.controller;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.net.URI;

/**

  • @author smileyan
    */
    @RestController
    @RequestMapping("/wechat")
    public class WeChatLoginController {

    @Value(" w e c h a t . a p p i d " ) p r i v a t e S t r i n g a p p i d ; @ V a l u e ( " {wechat.appid}") private String appid; @Value(" wechat.appid")privateStringappid;@Value("{wechat.appsecret}")
    private String appsecret;

    private String openid;
    private String session_key;

    @GetMapping("/index")
    private String login(String code) {
    // 创建Httpclient对象
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String resultString = “”;
    CloseableHttpResponse response = null;
    String url=“https://api.weixin.qq.com/sns/jscode2session?appid=”+appid+"&secret="+appsecret+"&js_code="+code+"&grant_type=authorization_code";
    try {
    // 创建uri
    URIBuilder builder = new URIBuilder(url);
    URI uri = builder.build();

          // 创建http GET请求
          HttpGet httpGet = new HttpGet(uri);
    
          // 执行请求
          response = httpclient.execute(httpGet);
          // 判断返回状态是否为200
          if (response.getStatusLine().getStatusCode() == 200) {
              resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
          }
      } catch (Exception e) {
          e.printStackTrace();
      }
    
      // 解析json
      JSONObject jsonObject = (JSONObject) JSONObject.parse(resultString);
      session_key = jsonObject.get("session_key")+"";
      openid = jsonObject.get("openid")+"";
    
      System.out.println("session_key=="+session_key);
      System.out.println("openid=="+openid);
      return resultString;
    

    }

}

// TODO

敬请期待下次相遇

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值