微信登录

uniapp实现微信授权登录功能,微信授权登录主要是用到了三个api,分别是uni.getProvider,uni.login,uni.getUserInfo但是在此之前,先要做一些准备

如果是APP端
微信授权登录的前提是有微信appid,和appsercret
需要去微信开发者平台创建app,或者小程序填写相关信息申请应用的appid和appSecret,直接登录微信开发者平台微信开放平台 然后登录,按照提示进行申请就好啦,然后在manifest.json中进行配置
image.png
如果是没有appid和appSecret是无法是现在功能的

  1. getUserInfo() {
  2. return new Promise((resolve, reject) => {
  3. uni.getUserProfile({
  4. lang: 'zh_CN',
  5. desc: '用户登录', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,
  6. success: (res) => {
  7. console.log(res, 'resss')
  8. resolve(res.userInfo)
  9. },
  10. fail: (err) => {
  11. reject(err)
  12. }
  13. })
  14. })
  15. },
  16. //先登录,获取access_token,refresh_token,expiires_in,openid,scope,unionid
  17. getLogin() {
  18. return new Promise((resolve, reject) => {
  19. uni.login({
  20. success(res) {
  21. console.log(res, 'res')//微信成功登录,获取到code
  22. resolve(res)
  23. },
  24. fail: (err) => {
  25. console.log(err, 'logoer')
  26. reject(err)
  27. }
  28. })
  29. })
  30. },
  31. weixinLogin() {
  32. let that = this;
  33. uni.getProvider({
  34. service: 'oauth',
  35. success: function(res) {
  36. //支持微信、qq和微博等
  37. if (~res.provider.indexOf('weixin')) {
  38. console.log(res, 'ress')
  39. let userInfo = that.getUserInfo();
  40. let loginRes = that.getLogin();
  41. Promise.all([userInfo, loginRes]).then((result) =>{
  42. let userInfo = result[0];
  43. let loginRes = result[1];
  44. let access_token = loginRes.authResult.access_token;
  45. let openid = loginRes.authResult.openid;
  46. let data = Object.assign(loginRes.authResult, userInfo);
  47. that.$store.dispatch('Login', {
  48. type: 'weixin',
  49. url: that.url,
  50. data
  51. }).then(r => {
  52. if (r == 'ok') {
  53. uni.hideLoading()
  54. }
  55. }).catch(err => {
  56. uni.hideLoading();
  57. uni.showToast({
  58. icon: 'none',
  59. title: err
  60. })
  61. })
  62. })
  63. }
  64. },
  65. fail: function(err) {
  66. uni.hideLoading();
  67. uni.showToast({
  68. icon: 'none',
  69. title: err
  70. })
  71. }
  72. })
  73. },

对于微信小程序的微信登录,不用去配置权限,也不用使用getProvider,直接调用uni.login,uni.getUserInfo就可以啦

这里出现了新的api,uni.getUserProfile (微信基础库2.10.4版本对用户信息相关接口进行了调整,使用 uni.getUserInfo 获取得到的 userInfo 为匿名数据,建议使用 uni.getUserProfile 获取用户信息。)

为什么要用promise拉成平级?
在实践过程中,如果在uni.login中嵌套uni.getUserProfile会出现直接不能弹出获取授权弹框,因为login失败就不会在调用getUserProfile(授权行为) - 用户提现会相对较差
因此promise在这个时候就重出江湖 - 和上面是一样的,只是删除了其他多么的代码

  1. getUserInfo() {
  2. return new Promise((resolve, reject) => {
  3. wx.getUserProfile({
  4. lang: 'zh_CN',
  5. desc: '用户登录',
  6. success: (res) => {
  7. resolve(res.userInfo)
  8. },
  9. fail: (err) => {
  10. reject(err)
  11. }
  12. })
  13. })
  14. },
  15. getLogin() {
  16. return new Promise((resolve, reject) => {
  17. wx.login({
  18. success(res) {
  19. resolve(res.code)
  20. },
  21. fail: (err) => {
  22. reject(err)
  23. }
  24. })
  25. })
  26. },
  27. login() {
  28. let userInfo = this.getUserInfo();
  29. let wxCode = this.getLogin();
  30. Promise.all([userInfo, wxCode]).then((res) => {
  31. //都获取权限成功
  32. }).catch(err => {
  33. })
  34. }

app实现微信登录

  1. uni.getProvider({
  2. service: 'oauth',
  3. success: function(res) {
  4. //支持微信、qq和微博等
  5. if (~res.provider.indexOf('weixin')) {
  6. uni.login({
  7. provider: 'weixin',
  8. success: function(loginRes) {
  9. // 获取用户信息
  10. uni.getUserInfo({
  11. provider: 'weixin',
  12. success: function(infoRes) {
  13. let data = Object.assign(loginRes.authResult, infoRes);
  14. that.$store.dispatch('Login', {
  15. type: 'weixin',
  16. url: that.url,
  17. data
  18. }).then(res => {
  19. if (res == 'ok') {
  20. uni.hideLoading()
  21. }
  22. fail: function(err) {
  23. uni.hideLoading();
  24. uni.showToast({
  25. icon: 'none',
  26. title: err
  27. })
  28. }
  29. })
  30. },
  31. fail: function(err) {
  32. uni.hideLoading();
  33. uni.showToast({
  34. icon: 'none',
  35. title: err
  36. })
  37. }
  38. });
  39. }
  40. },
  41. fail: function(err) {
  42. uni.hideLoading();
  43. uni.showToast({
  44. icon: 'none',
  45. title: err
  46. })
  47. }
  48. })
  49. },

app的微信登录需要进行前面的配置,其次是不用进行getUserProfile。
简易版本
直接登录获取用户信息

  1. uni.login({
  2. provider: 'weixin',
  3. success: function (loginRes) {
  4. console.log(loginRes.authResult);
  5. // 获取用户信息
  6. uni.getUserInfo({
  7. provider: 'weixin',
  8. success: function (infoRes) {
  9. console.log('用户昵称为:' + infoRes.userInfo.nickName);
  10. }
  11. });
  12. }
  13. });

获取地理位置*

  1. https://blog.csdn.net/qq_37899792/article/details/111572423
  2. https://blog.csdn.net/oneya1/article/details/112708216

1.源生小程序

原生的微信小程序需要在app.json中配置permission字段。uni-app则需要在manifest.json中配置,如下图:
image.png

2.查看授权以及申请授权获取地理位置

  1. getUserLocation() {
  2. uni.getSetting({
  3. success: (res) => {
  4. if (!res.authSetting['scope.userLocation']) {
  5. console.log(res)
  6. uni.authorize({
  7. scope: 'scope.userLocation',
  8. success: () => { //1.1 允许授权
  9. this.geo();
  10. },
  11. fail:()=> { //1.2 拒绝授权
  12. console.log('拒绝')
  13. this.postAddress('')
  14. }
  15. })
  16. } else {
  17. this.geo();
  18. }
  19. }
  20. })
  21. },

uni.authorize

提前向用户发起授权请求。调用后会立刻弹窗询问用户是否同意授权小程序使用某项功能或获取用户的某些数据,但不会实际调用对应接口。如果用户之前已经同意授权,则不会出现弹窗,直接返回成功。如果用户之前拒绝了授权,此接口会直接进入失败回调,一般搭配uni.getSetting和uni.openSetting使用

3.获取经纬度之后,再借助第三方接口,将获取到的经纬度转为具体的地理位置(可以借助百度的或者腾讯的)。这里用的是腾讯的

注:这个第三方接口(https://apis.map.qq.com)需要在小程序平台设置request安全域名

1 在腾讯平台申请自己的秘钥(申请地址:腾讯位置服务 - 立足生态,连接未来)
2下载小程序js微信小程序JavaScriptSDK v1.0 引入自己的文件
3 var QQMapWX = require(‘@/common/js/qqmap-wx-jssdk.min.js’);
具体代码如下:

  1. // 获取定位城市
  2. //引入第三方接口
  3. geo() {
  4. var QQMapWX = require('@/common/js/qqmap-wx-jssdk.min.js');
  5. this.qqmapsdk = new QQMapWX({
  6. key: 'DL6BZ-***************-6XBEQ' //自己的key秘钥 http://lbs.qq.com/console/mykey.html 在这个网址申请
  7. });
  8. //使用接口获取本地地址
  9. uni.getLocation({
  10. type: 'wgs84',
  11. success: (res) => {
  12. var latitude = res.latitude
  13. var longitude = res.longitude
  14. var speed = res.speed
  15. var accuracy = res.accuracy
  16. //第三方接口
  17. this.qqmapsdk.reverseGeocoder({
  18. location: {
  19. latitude: latitude,
  20. longitude: longitude
  21. },
  22. success: (res) => {
  23. let loginAddress = res.result.ad_info.name
  24. this.postAddress(loginAddress)
  25. },
  26. fail: (res) => {
  27. console.log("fail");
  28. console.log(res);
  29. },
  30. complete: (res) => {
  31. }
  32. });
  33. }
  34. })
  35. },
  36. //postAddress请求后台接口
  37. postAddress(loginAddress) {
  38. let shareUserId = uni.getStorageSync('shareUserId')//分享人id
  39. //wx.getLaunchOptionsSync()获取小程序启动时的参数。与 App.onLaunch 的回调参数一致。
  40. let scene = wx.getLaunchOptionsSync().scene//登录场景
  41. this.$http({
  42. method: 'POST',
  43. hideLoading: true,
  44. url: '/api/****Info',
  45. data: {
  46. shareUserId,
  47. scene,
  48. loginAddress
  49. },
  50. }).then(res => {
  51. console.log(res)
  52. if (res.code == 0) {
  53. }
  54. }).catch(() => {
  55. }).finally(res => {
  56. })
  57. },

完整流程

  1. // 初次位置授权
  2. getAuthorize() {
  3. return new Promise((resolve, reject) => {
  4. uni.authorize({
  5. scope: "scope.userLocation",
  6. success: () => {
  7. resolve(); // 允许授权
  8. },
  9. fail: () => {
  10. reject(); // 拒绝授权
  11. },
  12. });
  13. });
  14. },
  15. // 确认授权后,获取用户位置
  16. getLocationInfo() {
  17. const that = this;
  18. uni.getLocation({
  19. type: "gcj02",
  20. success: function(res) {
  21. // 暂时
  22. that.longitude = res.longitude; //118.787575;
  23. that.latitude = res.latitude; //32.05024;
  24. console.log("获取当前的用户经度", that.longitude);
  25. console.log("获取当前的用户纬度", that.latitude);
  26. var long = 0;
  27. var lat = 0;
  28. //小数点保留六位 经度
  29. if (that.longitude.toString().indexOf('.') > 0) {
  30. const longlatsplit = that.longitude.toString().split('.');
  31. if (longlatsplit.length >= 2) {
  32. long = parseFloat(longlatsplit[0] === "" ? 0 : longlatsplit[0]) + parseFloat("." + longlatsplit[1].slice(0,6));
  33. }
  34. }
  35. if (that.latitude.toString().indexOf('.') > 0) {
  36. const longlatsplit1 = that.latitude.toString().split('.');
  37. if (longlatsplit1.length >= 2) {
  38. lat = parseFloat(longlatsplit1[0] === "" ? 0 : longlatsplit1[0]) + parseFloat("." + longlatsplit1[1].slice(0,6));
  39. }
  40. }
  41. cookie.set("longitude",long);
  42. cookie.set("latitude",lat);
  43. console.log("纬度", lat);
  44. // this.distance(that.latitude,that.longitude);
  45. that.markers = [{
  46. id: "",
  47. latitude: res.latitude,
  48. longitude: res.longitude,
  49. iconPath: "../../static/img/phone.png",
  50. width: that.markerHeight, //宽
  51. height: that.markerHeight, //高
  52. }, ];
  53. that.getList();
  54. },
  55. });
  56. },
  57. // 拒绝授权后,弹框提示是否手动打开位置授权
  58. openConfirm() {
  59. return new Promise((resolve, reject) => {
  60. uni.showModal({
  61. title: "请求授权当前位置",
  62. content: "我们需要获取地理位置信息,为您推荐附近的美食",
  63. success: (res) => {
  64. if (res.confirm) {
  65. uni.openSetting().then((res) => {
  66. if (res[1].authSetting["scope.userLocation"] === true) {
  67. resolve(); // 打开地图权限设置
  68. } else {
  69. reject();
  70. }
  71. });
  72. } else if (res.cancel) {
  73. reject();
  74. }
  75. },
  76. });
  77. });
  78. },
  79. // 彻底拒绝位置获取
  80. rejectGetLocation() {
  81. uni.showToast({
  82. title: "你拒绝了授权,无法获得周边信息",
  83. icon: "none",
  84. duration: 2000,
  85. });
  86. },
  87. getList() {
  88. console.log("获取周围美食");
  89. },
  90. onReady() {
  91. // wx请求获取位置权限
  92. this.getAuthorize()
  93. .then(() => {
  94. // 同意后获取
  95. this.getLocationInfo();
  96. })
  97. .catch(() => {
  98. // 不同意给出弹框,再次确认
  99. this.openConfirm()
  100. .then(() => {
  101. this.getLocationInfo();
  102. })
  103. .catch(() => {
  104. this.rejectGetLocation();
  105. });
  106. });
  107. },

实现uniapp打开地图app,并且将要去得店铺标记经纬度传入

  1. 注意:
  2. uni.openLocation({
  3. latitude: parseFloat(lat),//------》传入的经纬度必须是浮点数, 不能传入字符串,否则地图打不开
  4. longitude:parseFloat(lon),
  5. scale: 18
  6. })
  1. methods{
  2. //先获取当前位置,然后通过位置坐标,在内置地图中定位到当前位置
  3. openMap(lon,lat){
  4. console.log("获取经纬度ssssfff",lon,lat);
  5. //打开地图,并将门店位置传入
  6. uni.getLocation({
  7. success: res => {
  8. // res.latitude=lat;
  9. // res.longitude=lon;
  10. console.log('location success', parseFloat(lat),parseFloat(lon))
  11. uni.openLocation({
  12. latitude: parseFloat(lat),
  13. longitude:parseFloat(lon),
  14. scale: 18
  15. })
  16. }
  17. })
  18. },
  19. }

实现当前定位到门店位置距离计算:

  1. //进行经纬度转换为距离的计算
  2. Rad(d) {
  3. return d * Math.PI / 180.0; //经纬度转换成三角函数中度分表形式。
  4. },
  5. /*
  6. 计算距离,参数分别为第一点的纬度,经度;第二点的纬度,经度
  7. 默认单位km
  8. */
  9. getMapDistance(lat1, lng1, lat2, lng2) {
  10. var radLat1 = this.Rad(lat1);
  11. var radLat2 = this.Rad(lat2);
  12. var a = radLat1 - radLat2;
  13. var b = this.Rad(lng1) - this.Rad(lng2);
  14. var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
  15. Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
  16. s = s * 6378.137; // EARTH_RADIUS;
  17. s = Math.round(s * 10000) / 10000; //输出为公里
  18. //s=s.toFixed(2);
  19. return s;
  20. },

完整代码

  1. <template>
  2. <view class="content">
  3. <view class="text-area">
  4. <view class="item">
  5. <image class="logo" src="/static/logo.png"></image>
  6. </view>
  7. <view class="item item_two">
  8. <view class="title" @tap="openMap('104.060268','30.642047')">{{title}}(点击跳转)</view>
  9. <view class="distance">距离:{{distance}}km</view>
  10. </view>
  11. </view>
  12. </view>
  13. </template>
  14. <script>
  15. export default {
  16. data() {
  17. return {
  18. title: '四川大学华西医院',
  19. distance: 0, //"距离"
  20. latitude: 39.909, // 默认定在首都
  21. longitude: 116.39742,
  22. scale: 12, // 默认16
  23. markers: [],
  24. markerHeight: 30,
  25. doorAddress: [], //门店地址
  26. }
  27. },
  28. onLoad() {
  29. },
  30. mounted() {
  31. this.distance = this.getMapDistance('104.04311','30.64242','104.060268','30.642047');
  32. console.log('距离',this.distance);
  33. },
  34. methods: {
  35. // 确认授权后,获取用户位置
  36. getLocationInfo() {
  37. const that = this;
  38. uni.getLocation({
  39. type: "gcj02",
  40. success: function(res) {
  41. // 暂时
  42. that.longitude = res.longitude; //118.787575;
  43. that.latitude = res.latitude; //32.05024;
  44. console.log("获取当前的用户经度", that.longitude);
  45. console.log("获取当前的用户纬度", that.latitude);
  46. var long = 0;
  47. var lat = 0;
  48. //小数点保留六位 经度
  49. if (that.longitude.toString().indexOf('.') > 0) {
  50. const longlatsplit = that.longitude.toString().split('.');
  51. if (longlatsplit.length >= 2) {
  52. long = parseFloat(longlatsplit[0] === "" ? 0 : longlatsplit[0]) + parseFloat("." + longlatsplit[1].slice(0,6));
  53. }
  54. }
  55. if (that.latitude.toString().indexOf('.') > 0) {
  56. const longlatsplit1 = that.latitude.toString().split('.');
  57. if (longlatsplit1.length >= 2) {
  58. lat = parseFloat(longlatsplit1[0] === "" ? 0 : longlatsplit1[0]) + parseFloat("." + longlatsplit1[1].slice(0,6));
  59. }
  60. }
  61. // cookie.set("longitude", long);
  62. // cookie.set("latitude", lat);
  63. console.log("纬度", lat);
  64. // this.distance(that.latitude,that.longitude);
  65. that.markers = [{
  66. id: "",
  67. latitude: res.latitude,
  68. longitude: res.longitude,
  69. iconPath: "../../static/img/phone.png",
  70. width: that.markerHeight, //宽
  71. height: that.markerHeight, //高
  72. }, ];
  73. that.getList();
  74. },
  75. });
  76. },
  77. // 拒绝授权后,弹框提示是否手动打开位置授权
  78. openConfirm() {
  79. return new Promise((resolve, reject) => {
  80. uni.showModal({
  81. title: "请求授权当前位置",
  82. content: "我们需要获取地理位置信息,为您推荐附近的美食",
  83. success: (res) => {
  84. if (res.confirm) {
  85. uni.openSetting().then((res) => {
  86. if (res[1].authSetting["scope.userLocation"] === true) {
  87. resolve(); // 打开地图权限设置
  88. } else {
  89. reject();
  90. }
  91. });
  92. } else if (res.cancel) {
  93. reject();
  94. }
  95. },
  96. });
  97. });
  98. },
  99. // 彻底拒绝位置获取
  100. rejectGetLocation() {
  101. uni.showToast({
  102. title: "你拒绝了授权,无法获得周边信息",
  103. icon: "none",
  104. duration: 2000,
  105. });
  106. },
  107. getList() {
  108. console.log("获取周围美食");
  109. },
  110. onReady() {
  111. // wx请求获取位置权限
  112. this.getAuthorize()
  113. .then(() => {
  114. // 同意后获取
  115. this.getLocationInfo();
  116. })
  117. .catch(() => {
  118. // 不同意给出弹框,再次确认
  119. this.openConfirm()
  120. .then(() => {
  121. this.getLocationInfo();
  122. })
  123. .catch(() => {
  124. this.rejectGetLocation();
  125. });
  126. });
  127. },
  128. openMap(lon,lat) {
  129. console.log("获取经纬度ssssfff", lon, lat);
  130. //打开地图,并将门店位置传入
  131. uni.getLocation({
  132. success: res => {
  133. // res.latitude=lat;
  134. // res.longitude=lon;
  135. console.log('location success', parseFloat(lat), parseFloat(lon))
  136. uni.openLocation({
  137. latitude: parseFloat(lat),
  138. longitude: parseFloat(lon),
  139. scale: 18
  140. })
  141. }
  142. })
  143. },
  144. //进行经纬度转换为距离的计算
  145. Rad(d) {
  146. return d * Math.PI / 180.0; //经纬度转换成三角函数中度分表形式。
  147. },
  148. /*
  149. 计算距离,参数分别为第一点的纬度,经度;第二点的纬度,经度
  150. 默认单位km
  151. */
  152. getMapDistance(lat1, lng1, lat2, lng2) {
  153. var radLat1 = this.Rad(lat1);
  154. var radLat2 = this.Rad(lat2);
  155. var a = radLat1 - radLat2;
  156. var b = this.Rad(lng1) - this.Rad(lng2);
  157. var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
  158. Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
  159. s = s * 6378.137; // EARTH_RADIUS;
  160. s = Math.round(s * 10000) / 10000; //输出为公里
  161. //s=s.toFixed(2);
  162. return s;
  163. },
  164. //计算距离
  165. // 初次位置授权
  166. getAuthorize() {
  167. return new Promise((resolve, reject) => {
  168. uni.authorize({
  169. scope: "scope.userLocation",
  170. success: () => {
  171. resolve(); // 允许授权
  172. },
  173. fail: () => {
  174. reject(); // 拒绝授权
  175. },
  176. });
  177. });
  178. },
  179. }
  180. }
  181. </script>
  182. <style>
  183. .content {
  184. display: flex;
  185. flex-direction: column;
  186. align-items: center;
  187. justify-content: center;
  188. }
  189. .logo {
  190. width: 100%;
  191. height: 100%;
  192. }
  193. .text-area {
  194. border: 1px solid #CCCCCC;
  195. padding: 4px 4px;
  196. width: 95%;
  197. height: 200rpx;
  198. display: flex;
  199. justify-content:space-around;
  200. }
  201. .title {
  202. /* border: 1px solid; */
  203. font-size: 39rpx;
  204. color: #8f8f94;
  205. flex: 1;
  206. }
  207. .distance{
  208. font-size: 25rpx;
  209. color:red;
  210. /* border: 1px solid; */
  211. flex: 1;
  212. }
  213. .item{
  214. /* border: 1px solid; */
  215. flex: 1;
  216. }
  217. .item_two{
  218. padding-left: 5px;
  219. flex: 3;
  220. display: flex;
  221. flex-direction: column;
  222. }
  223. </style>

选择位置(地址)

wx.chooseLocation(Object object)

打开地图选择位置。

  • latitude:目标地纬度;longitude:目标地经度;

这里我们要先使用wx.getLocation获取到经度、纬度,然后给wx.chooseLocation使用就可以了,下面看代码:

  1. wx.getLocation({
  2. type: "wgs84",
  3. success(res) {
  4. wx.chooseLocation({
  5. latitude: res.latitude,
  6. longitude: res.longitude,
  7. success: function(data){
  8. console.log(data)
  9. }
  10. })
  11. }
  12. })

image.png
当我们选中某一个地址,点击确定时,就会返回当前地址的信息:
参数说明:

  • name:位置名称;address:详细地址;latitude:纬度,浮点数,范围为-90~90,负数表示南纬。使用 gcj02 国测局坐标系;longitude:经度,浮点数,范围为-180~180,负数表示西经。使用 gcj02 国测局坐标系;

    使用微信内置地图查看位置信息

    wx.openLocation(Object object)

    使用微信内置地图查看位置

  • latitude:纬度,范围为-90~90,负数表示南纬。使用 gcj02 国测局坐标系longitude:经度,范围为-180~180,负数表示西经。使用 gcj02 国测局坐标系scale:缩放比例,范围5~18name:位置名address:地址的详细说明

    1. wx.openLocation({
    2. latitude: 30.64242,
    3. longitude: 104.04311,
    4. name: "武侯区人民政府(武侯祠大街南)",
    5. address: "四川省成都市武侯区武侯祠大街264号"
    6. })

    另外,当我们点击右下角绿色按钮(到这去)时,它会自动调用本地地图,可以直接导航,相当方便。

    微信支付*

    1. https://blog.csdn.net/zlk4524718/article/details/118895849

    获取手机号

  1. 第一步 需要用户获取code,
    2. 拿code获取openId 和 session_key,
    3. 拉去获取手机号码权限,允许授权 获取encryptedData和iv
    4. 手机号码是在后台获取的,我们只需要传 encryptedData,iv,sessionKey,openId这个四个字段就能获取到用户手机号了。具体详细步骤请看下面。

    1.用户获取code

    调用login方法获取code ```javascript onLoad(){

    1. this.getuserNew(); // 获取openid

    },

    methods:{

    1. // 获取code
    2. getuserNew(){
    3. uni.login({
    4. provider: 'weixin',
    5. success:res=>{
    6. console.log(res.code);
    7. }
    8. });
    9. },

    }

  1. <a name="iBlVk"></a>
  2. ## 2.通过code获取获取openId 和 session_key
  3. 方法1, 通过微信官方接口获取
  4. ```javascript
  5. uni.request({
  6. url: 'https://api.weixin.qq.com/sns/jscode2session',
  7. method:'GET',
  8. data: {
  9. appid: 'wx9*******214e0', //你的小程序的APPID
  10. secret: '33c4d17e4********71253', //你的小程序的secret,
  11. js_code:res.code, //wx.login 登录成功后的code
  12. grant_type: 'authorization_code',
  13. },
  14. success: (cts) => {
  15. // 换取成功后 暂存这些数据 留作后续操作
  16. this.openId=cts.data.openid //openid 用户唯一标识
  17. this.unionid=cts.data.unionid //unionid 开放平台唯一标识 当公众号和小程序同时登录过才会有
  18. this.session_key=cts.data.session_key //session_key 会话密钥
  19. console.log(cts)
  20. console.log(this.openId,this.session_key)
  21. }
  22. });

方法2 通过后台接口获取
传我们在第一步获取的code参数去获取openId 和 session_key,

  1. uni.request({
  2. url:"http://192.168.0.93:6042/login/verifyMini****Code",
  3. method:"POST",
  4. data:{
  5. data:{
  6. code:res.code,
  7. }
  8. },
  9. success:(res)=>{
  10. if(res.data.errorinfo == null){
  11. console.log(res.data)
  12. this.openId=res.data.data.openId //openid 用户唯一标识
  13. this.session_key=res.data.data.sessionKey //session_key 会话密钥
  14. console.log(this.openId,this.session_key);
  15. }
  16. }
  17. })

3.拉去获取手机号码权限,允许授权 获取encryptedData和iv

  1. <button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">唤起授权手机号</button>
  1. // 获取用户手机号
  2. getPhoneNumber(e){
  3. console.log(e.detail.errMsg) // 判断用户是否允许获取手机号
  4. console.log(e.detail.iv) // 参数 iv
  5. console.log(e.detail.encryptedData) // 参数encryptedData
  6. if(e.detail.errMsg == "getPhoneNumber:ok"){ // 用户允许或去手机号
  7. uni.request({
  8. url:"http://192.168.0.93:6042/login/miniProgramLogin",
  9. method:"POST",
  10. data:{
  11. data:{
  12. encryptedData: e.detail.encryptedData,
  13. iv: e.detail.iv,
  14. sessionKey: this.session_key,
  15. openId: this.openId,
  16. }
  17. },
  18. success:(res)=>{
  19. if(res.data.errorinfo == null){
  20. console.log(res.data) // 这个里面就有手机号了
  21. }
  22. }
  23. })
  24. }
  25. },
  1. onLoad() {
  2. //获取appid
  3. // #ifdef MP-ALIPAY
  4. console.log('获取appid')
  5. const appIdRes = my.getAppIdSync();
  6. console.log("支付宝端appId :", appIdRes.appId);
  7. this.appID = appIdRes.appId
  8. // #endif
  9. // #ifdef MP-WEIXIN
  10. console.log('获取appid')
  11. const accountInfo = uni.getAccountInfoSync();
  12. console.log("微信端appid :",accountInfo.miniProgram.appId); // 小程序 appId
  13. this.appID = accountInfo.miniProgram.appId
  14. // #endif
  15. var that = this
  16. //获取 loginRes.code
  17. uni.login({
  18. provider: 'weixin',
  19. success: function(loginRes) {
  20. console.log("loginRes: ",loginRes);
  21. console.log("loginRes.code", loginRes.code);
  22. that.loginResCode = loginRes.code
  23. }
  24. });
  25. },
  26. //这样就获取到了手机号码。
  1. //获取手机号 发送到后台解密手机号
  2. getPhoneNumber(e) {
  3. console.log("errMsg", e.detail.errMsg)
  4. var that = this
  5. if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
  6. console.log('用户拒绝提供手机号');
  7. } else {
  8. console.log('用户同意提供手机号');
  9. console.log("iv", e.detail.iv)
  10. console.log("encryptedData", e.detail.encryptedData)
  11. var encryptedData = e.detail.encryptedData
  12. var iv = e.detail.iv
  13. //检查登录
  14. uni.checkSession({
  15. success: (res) => {
  16. console.log("checkSession--success---res", res)
  17. if (res.errMsg == 'checkSession:ok') {
  18. console.log(res);
  19. console.log('登录暂未过期');
  20. if (encryptedData !== undefined && iv !== undefined) {
  21. that.getPhone(that.loginResCode, encryptedData, iv)
  22. }
  23. }
  24. },
  25. fail: (res) => {
  26. console.log("checkSession---fail---res", res)
  27. console.log('登录已过期');
  28. //再执行一次login
  29. uni.login({
  30. provider: 'weixin',
  31. success: function(loginRes) {
  32. console.log("loginRes.code", loginRes.code);
  33. that.loginResCode = loginRes.code
  34. if (encryptedData !== undefined && iv !== undefined) {
  35. that.getPhone(that.loginResCode, encryptedData, iv)
  36. }
  37. }
  38. });
  39. }
  40. })
  41. }
  42. //e.detail.errMsg == 'getPhoneNumber:fail Error: 用户未绑定手机,请先在微信客户端进行绑定后重试' 微信会自动引导用户去绑定手机
  43. },
  44. //手机号发送至后台解密
  45. getPhone(loginResCode, encryptData, ivStr) {
  46. uni.request({
  47. url: this.$URL + '/school/app/getMobilePhone',
  48. method: 'GET',
  49. data: {
  50. appId: this.appID,
  51. code: loginResCode,
  52. encryptData: encryptData,
  53. ivStr: ivStr,
  54. },
  55. header: {
  56. 'Content-Type': 'application/json;charset=utf-8'
  57. },
  58. success: (res) => {
  59. console.log("获取解密后的手机号 -res:", res)
  60. if (res.data.code == 200) {
  61. console.log("手机号: ", res.data.obj);
  62. this.phone = res.data.obj
  63. } else {
  64. console.log('获取解密后的手机号失败', res.data.obj)
  65. uni.showToast({
  66. title: '获取手机失败,请重试',
  67. icon: 'none',
  68. duration: 1500,
  69. })
  70. }
  71. }
  72. })
  73. },