微信小程序获取用户手机号存数据库,前后端都有《Java后台版 》
生活随笔
收集整理的這篇文章主要介紹了
微信小程序获取用户手机号存数据库,前后端都有《Java后台版 》
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
開發(fā)這個(gè)功能的時(shí)候走了很多彎路磨了很多時(shí)間,我發(fā)一下我自己用的來幫助大家
流程圖
前端
index.wxml
index.js
Page({data: {//判斷小程序的API,回調(diào),參數(shù),組件等是否在當(dāng)前版本可用。canIUse: wx.canIUse('button.open-type.getUserInfo'),isHide: false},onLoad: function() {},//獲取用戶codegetcode: function(res){var that = this;// 查看是否授權(quán)wx.getSetting({success: function(res) {if (res.authSetting['scope.userInfo']) {wx.getUserInfo({success: function(res) {// 用戶已經(jīng)授權(quán)過,不需要顯示授權(quán)頁面,所以不需要改變 isHide 的值 根據(jù)自己的需求有其他操作再補(bǔ)充 我這里實(shí)現(xiàn)的是在用戶授權(quán)成功后,調(diào)用微信的 wx.login 接口,從而獲取codewx.login({// success: res => {// 獲取到用戶的 code 之后:res.code 可以傳給后臺,再經(jīng)過解析獲取用戶的 openid 代碼如下// wx.login({success: function (res) {console.log("用戶的code:" + res.code);// if (res.code) { //使用小程序登錄接口完成后端用戶登錄wx.request({url: "填寫服務(wù)器接口一定要HTTPS的可以去natapp買一個(gè)" +"/getOpenid",data: {code: res.code,appid: "自己的APPID",secret: "自己的APPSECRET", },method:'POST',header: {'content-type': 'application/json' // POST請求},success: function (res) {//把openid保存到緩存里wx.setStorageSync("openid", res.openid);wx.setStorageSync("session_key", res.session_key);}})// } else {// console.log('獲取用戶登錄態(tài)失敗!' + res.errMsg)// }}});// }// });}});} else {// 用戶沒有授權(quán)// 改變 isHide 的值,顯示授權(quán)頁面that.setData({isHide: true});}}});},//獲取用戶開發(fā)信息bindGetUserInfo: function(e) {if (e.detail.userInfo) {//用戶按了允許授權(quán)按鈕var that = this;// 獲取到用戶的信息了,打印到控制臺上看下console.log("用戶的信息如下:");console.log(e.detail.openid);console.log(e.detail.userInfo);//授權(quán)成功后,通過改變 isHide 的值,讓實(shí)現(xiàn)頁面顯示出來,把授權(quán)頁面隱藏起來that.setData({isHide: false});} else {//用戶按了拒絕按鈕wx.showModal({title: '警告',content: '您點(diǎn)擊了拒絕授權(quán),將無法進(jìn)入小程序,請授權(quán)之后再進(jìn)入!!!',showCancel: false,confirmText: '返回授權(quán)',success: function(res) {// 用戶沒有授權(quán)成功,不需要改變 isHide 的值if (res.confirm) {console.log('用戶點(diǎn)擊了“返回授權(quán)”');}}});}}, //獲取用戶手機(jī)號授權(quán)按鈕 getPhoneNumber: function (e) {var app = getApp();wx.request({url: "填寫服務(wù)器接口一定要是HTTPS的可以去natapp買一個(gè)" +"/postPhoneNumber", //解密手機(jī)號碼接口data: {encryptedData: e.detail.encryptedData,iv: e.detail.iv},method:'POST',header: {'content-type': 'application/json' // POST請求},success: function (res) {console.log(res.data.phoneNumber);wx.setStorageSync("phonenumber", res.data.phoneNumber);}})},})后端Java代碼
Controller層代碼
package com.pyx.wechatapplet2.conntroller.wechat;import com.alibaba.fastjson.JSON; import com.pyx.wechatapplet2.entity.user.Openid; import com.pyx.wechatapplet2.util.AesCbcUtil; import com.pyx.wechatapplet2.util.JDBCUtil; import com.pyx.wechatapplet2.util.redis.RedisUtil; import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.json.JSONObject; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException;@RestController @Slf4j public class WechatgetPhone {public String Openid;public String session_key;public String getOpenid() {return Openid;}public void setOpenid(String openid) {Openid = openid;}@PostMapping("/getOpenid")@Transactional(rollbackFor = Exception.class)public synchronized com.alibaba.fastjson.JSONObject getSessionKeyOropenid(@RequestBody Openid openid ) throws Exception {System.out.println("Openid code:" + openid.getCode());CloseableHttpClient httpclient = HttpClients.createDefault();//發(fā)送get請求讀取調(diào)用微信 https://api.weixin.qq.com/sns/jscode2session 接口獲取openid用戶唯一標(biāo)識HttpGet httpget = new HttpGet("https://api.weixin.qq.com/sns/jscode2session?appid=" + "自己的APPID" + "&secret=" + "自己的appsecret" + "&js_code=" + openid.getCode() + "&grant_type=authorization_code");CloseableHttpResponse response = httpclient.execute(httpget);HttpEntity entity = response.getEntity();com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(entity));RedisUtil.setStringValue("session_key" , jsonObject.getString("session_key"));session_key=jsonObject.getString("session_key");Openid=jsonObject.getString("openid");System.out.println("Openid:" + Openid);RedisUtil.setStringValue("openid",jsonObject.getString("openid"));log.info(jsonObject.toJSONString());//----------------------------------解密用戶信息----------------------------------------- // String userInfo = null; // JSONObject userInfoJSON = null; // Thread.sleep(500); // try { // byte[] resultByte = AES.decrypt(Base64.decodeBase64(openid.getEncryptedData()), // Base64.decodeBase64(jsonObject.getString("session_key")), // Base64.decodeBase64(openid.getIv())); // // userInfo = new String(resultByte, "UTF-8"); // System.out.println("userInfo:" + userInfo); // userInfoJSON = JSON.parseObject(userInfo); // } catch (Exception e) { // e.printStackTrace(); // } // System.out.println("userInfo:" + userInfoJSON); //----------------------------------解密用戶信息-----------------------------------------return null;}//獲取用戶手機(jī)號信息@PostMapping(value ="/postPhoneNumber")// @GetMapping(value = "/getPhoneNumber")public Object getPhoneNumber(@RequestBody Openid openid , @RequestParam(value = "param") String param) throws Exception {// 加密秘鑰String sessionKey = RedisUtil.getStringValue("session_key");//手機(jī)號數(shù)據(jù)String類型String result = AesCbcUtil.decrypt(openid.getEncryptedData() , sessionKey , openid.getIv() , "UTF-8");System.out.println(result);//把String類型轉(zhuǎn)變成JSONObjectJSONObject resultObj = new JSONObject(result);//resultArray.optJSONObject(0);//用spring從JSONObject拿需要的數(shù)據(jù)String phoneNumber= resultObj.getString("phoneNumber");String watermark= resultObj.getString("watermark");JSONObject resultObj2 = new JSONObject(watermark);String appid=resultObj2.getString("appid");//數(shù)據(jù)庫操作HttpServletRequest request = null;Connection connection=null;PreparedStatement ps=null;ResultSet rs;try{connection= JDBCUtil.getConnection();String selectSQL = "select * from user_information where phoneNumber = ?";ps=connection.prepareStatement(selectSQL);ps.setString(1,phoneNumber);ps.execute();String phone=null;rs=ps.executeQuery();while(rs.next()){phone = rs.getString("phoneNumber");//rs.getInt("UserName");}System.out.println(phone+"查詢到的數(shù)據(jù)");if(phone==null){String sql="insert into user_information values(null,?,?,? ) ";ps=connection.prepareCall(sql);ps.setString(1,appid);ps.setString(2,phoneNumber);ps.setString(3,Openid);ps.execute();}else {System.out.println("已經(jīng)有該數(shù)據(jù)");}//增加代碼}catch (SQLException e){e.printStackTrace();}finally {JDBCUtil.close(connection);}System.out.println("_____下面是拿到的數(shù)據(jù)_____");System.out.println(phoneNumber);System.out.println(watermark);System.out.println(appid);return result;}}手機(jī)號解密代碼
AesCbcUtil
redis代碼用于儲存微信服務(wù)器發(fā)過來的session_key
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.JedisShardInfo; import redis.clients.jedis.ShardedJedis; import redis.clients.jedis.ShardedJedisPool;import java.io.*; import java.util.LinkedList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock;/*** Redis工具類*/ public class RedisUtil {private static Logger logger = LoggerFactory.getLogger(RedisUtil.class);/*** 默認(rèn)過期時(shí)間,單位/秒, 60*60*2=2H, 兩小時(shí)*/private static final int DEFAULT_EXPIRE_TIME = 7200;private static List<Redis> redisList;public static void init(List<Redis> redisList) {RedisUtil.redisList = redisList;}// ------------------------ ShardedJedisPool ------------------------private static ShardedJedisPool shardedJedisPool;private static ReentrantLock INSTANCE_INIT_LOCL = new ReentrantLock(false);/*** 獲取ShardedJedis實(shí)例** @return*/private static int timeout = 2;private static ShardedJedis getInstance() {if (shardedJedisPool == null) {try {if (INSTANCE_INIT_LOCL.tryLock(timeout, TimeUnit.SECONDS)) {try {if (shardedJedisPool == null) {// JedisPoolConfigJedisPoolConfig config = new JedisPoolConfig();// 最大連接數(shù), 默認(rèn)8個(gè)config.setMaxTotal(200);// 最大空閑連接數(shù), 默認(rèn)8個(gè)config.setMaxIdle(50);// 設(shè)置最小空閑數(shù)config.setMinIdle(8);// 獲取連接時(shí)的最大等待毫秒數(shù)(如果設(shè)置為阻塞時(shí)BlockWhenExhausted),如果超時(shí)就拋異常, 小于零:阻塞不確定的時(shí)間, 默認(rèn)-1config.setMaxWaitMillis(10000);// 在獲取連接的時(shí)候檢查有效性, 默認(rèn)falseconfig.setTestOnBorrow(true);// 調(diào)用returnObject方法時(shí),是否進(jìn)行有效檢查config.setTestOnReturn(true);// Idle時(shí)進(jìn)行連接掃描config.setTestWhileIdle(true);//表示idle object evitor兩次掃描之間要sleep的毫秒數(shù)config.setTimeBetweenEvictionRunsMillis(30000);//表示idle object evitor每次掃描的最多的對象數(shù)config.setNumTestsPerEvictionRun(10);//表示一個(gè)對象至少停留在idle狀態(tài)的最短時(shí)間,然后才能被idle object evitor掃描并驅(qū)逐;這一項(xiàng)只有在timeBetweenEvictionRunsMillis大于0時(shí)才有意義config.setMinEvictableIdleTimeMillis(60000);// JedisShardInfo ListList<JedisShardInfo> jedisShardInfos = new LinkedList<JedisShardInfo>();for (Redis redis : redisList) {String[] addressInfo = redis.getAddress().split(":");String host = addressInfo[0];int port = Integer.valueOf(addressInfo[1]);JedisShardInfo jedisShardInfo = new JedisShardInfo(host, port, 10000);if (redis.getPassword() != null && !"".equals(redis.getPassword())) {jedisShardInfo.setPassword(redis.getPassword());}jedisShardInfos.add(jedisShardInfo);}shardedJedisPool = new ShardedJedisPool(config, jedisShardInfos);logger.info(">>>>>>>>>>> JedisUtil.ShardedJedisPool init success.");}} finally {INSTANCE_INIT_LOCL.unlock();}}} catch (InterruptedException e) {logger.error(e.getMessage(), e);}}if (shardedJedisPool == null) {throw new NullPointerException(">>>>>>>>>>> JedisUtil.ShardedJedisPool is null.");}ShardedJedis shardedJedis = shardedJedisPool.getResource();return shardedJedis;}// ------------------------ serialize and unserialize ------------------------/*** 將對象-->byte[] (由于jedis中不支持直接存儲object所以轉(zhuǎn)換成byte[]存入)** @param object* @return*/private static byte[] serialize(Object object) {ObjectOutputStream oos = null;ByteArrayOutputStream baos = null;try {// 序列化baos = new ByteArrayOutputStream();oos = new ObjectOutputStream(baos);oos.writeObject(object);byte[] bytes = baos.toByteArray();return bytes;} catch (Exception e) {logger.error("{}", e);} finally {try {oos.close();baos.close();} catch (IOException e) {logger.error("{}", e);}}return null;}/*** 將byte[] -->Object** @param bytes* @return*/private static Object unserialize(byte[] bytes) {ByteArrayInputStream bais = null;try {// 反序列化bais = new ByteArrayInputStream(bytes);ObjectInputStream ois = new ObjectInputStream(bais);return ois.readObject();} catch (Exception e) {logger.error("{}", e);} finally {try {bais.close();} catch (IOException e) {logger.error("{}", e);}}return null;}// ------------------------ jedis util ------------------------/*** Set String** @param key* @param value* @param seconds 存活時(shí)間,單位/秒* @return*/public static String setStringValue(String key, String value, int seconds) {String result = null;ShardedJedis client = getInstance();try {result = client.setex(key, seconds, value);} catch (Exception e) {logger.info("{}", e);} finally {client.close();}return result;}/*** Set String (默認(rèn)存活時(shí)間, 2H)** @param key* @param value* @return*/public static String setStringValue(String key, String value) {return setStringValue(key, value, DEFAULT_EXPIRE_TIME);}/*** Set Object** @param key* @param obj* @param seconds 存活時(shí)間,單位/秒*/public static String setObjectValue(String key, Object obj, int seconds) {String result = null;ShardedJedis client = getInstance();try {result = client.setex(key.getBytes(), seconds, serialize(obj));} catch (Exception e) {logger.info("{}", e);} finally {client.close();}return result;}/*** Set Object (默認(rèn)存活時(shí)間, 2H)** @param key* @param obj* @return*/public static String setObjectValue(String key, Object obj) {return setObjectValue(key, obj, DEFAULT_EXPIRE_TIME);}/*** Get String** @param key* @return*/public static String getStringValue(String key) {String value = null;ShardedJedis client = getInstance();try {value = client.get(key);} catch (Exception e) {logger.info("", e);} finally {client.close();}return value;}/*** Get Object** @param key* @return*/public static Object getObjectValue(String key) {Object obj = null;ShardedJedis client = getInstance();int index = key.indexOf("forever-");try {byte[] bytes = client.get(key.getBytes());if (bytes != null && bytes.length > 0) {obj = unserialize(bytes);}} catch (Exception e) {logger.info("", e);} finally {client.close();}//重置過期時(shí)間if (index < 0) {expire(key, DEFAULT_EXPIRE_TIME);}return obj;}/*** Delete** @param key* @return Integer reply, specifically:* an integer greater than 0 if one or more keys were removed* 0 if none of the specified key existed*/public static Long del(String key) {Long result = null;ShardedJedis client = getInstance();try {result = client.del(key);} catch (Exception e) {logger.info("{}", e);} finally {client.close();}return result;}/*** incrBy value值加i** @param key* @param i* @return new value after incr*/public static Long incrBy(String key, int i) {Long result = null;ShardedJedis client = getInstance();try {result = client.incrBy(key, i);} catch (Exception e) {logger.info("{}", e);} finally {client.close();}return result;}/*** exists** @param key* @return Boolean reply, true if the key exists, otherwise false*/public static Boolean exists(String key) {Boolean result = null;ShardedJedis client = getInstance();try {result = client.exists(key);} catch (Exception e) {logger.info("{}", e);} finally {client.close();}return result;}/*** expire 重置存活時(shí)間** @param key* @param seconds 存活時(shí)間,單位/秒* @return Integer reply, specifically:* 1: the timeout was set.* 0: the timeout was not set since the key already has an associated timeout (versions lt 2.1.3), or the key does not exist.*/public static Long expire(String key, int seconds) {Long result = null;ShardedJedis client = getInstance();try {result = client.expire(key, seconds);} catch (Exception e) {logger.info("{}", e);} finally {client.close();}return result;}/*** expireAt 設(shè)置存活截止時(shí)間** @param key* @param unixTime 存活截止時(shí)間戳* @return*/public static Long expireAt(String key, long unixTime) {Long result = null;ShardedJedis client = getInstance();try {result = client.expireAt(key, unixTime);} catch (Exception e) {logger.info("{}", e);} finally {client.close();}return result;}/*** Set Object(永久有效)** @param key* @param obj*/public static String setForeverObjectValue(String key, Object obj) {String result = null;ShardedJedis client = getInstance();try {result = client.set(key.getBytes(), serialize(obj));} catch (Exception e) {logger.info("{}", e);} finally {client.close();}return result;} }pom依賴
<dependencies><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>4.1.21</version></dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.9.2</version></dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.9.2</version></dependency><dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.8.2</version></dependency><!-- https://mvnrepository.com/artifact/com.alibaba/druid --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.10</version></dependency><!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.7</version></dependency><!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp --><dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>3.10.0</version></dependency><!-- https://mvnrepository.com/artifact/redis.clients/jedis --><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>2.9.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.1</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency><!-- https://mvnrepository.com/artifact/org.apache.ibatis/ibatis-core --><dependency><groupId>org.apache.ibatis</groupId><artifactId>ibatis-core</artifactId><version>3.0</version></dependency><!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.15</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency><!-- https://mvnrepository.com/artifact/dom4j/dom4j --><dependency><groupId>dom4j</groupId><artifactId>dom4j</artifactId><version>1.6.1</version></dependency><!--commons --><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.6</version></dependency><dependency><groupId>commons-configuration</groupId><artifactId>commons-configuration</artifactId><version>1.10</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.5</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId></dependency><dependency><groupId>com.fasterxml</groupId><artifactId>classmate</artifactId><version>1.4.0</version></dependency><!--解析Emoji表情 --><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>4.5.0</version></dependency><dependency><groupId>org.bouncycastle</groupId><artifactId>bcprov-jdk15on</artifactId><version>1.55</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.3.5</version></dependency><dependency><groupId>com.vaadin.external.google</groupId><artifactId>android-json</artifactId><version>0.0.20131108.vaadin1</version></dependency><dependency><groupId>com.vaadin.external.google</groupId><artifactId>android-json</artifactId><version>0.0.20131108.vaadin1</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>至此所有代碼都完成了
在這里特別感謝一下幫助我的大佬 王子洋
這里是他的博客大家可以去看看
王子洋老師在B站有一個(gè)微信公眾號的講解視頻大家感興趣的可以去看一看名字是《Java開發(fā)之旅》
總結(jié)
以上是生活随笔為你收集整理的微信小程序获取用户手机号存数据库,前后端都有《Java后台版 》的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 月盈利百万的茶馆是如何通过一套商业模式起
- 下一篇: R语言使用rnorm函数生成正太分布数据