您的位置:首页 > 移动开发 > 微信开发

从零开始开发微信小程序(三):微信小程序绑定系统账号并授权登录之微信端

2018-02-04 00:00 741 查看
1. 开发账号绑定及授权登录功能前,必须已经有了小程序项目,参考文章:

https://my.oschina.net/u/3337958/blog/1618214

2. 建立test页面进行测试

在pages根据目录下新建一个test目录,在test目录下新建一个测试页面test的page





增加底栏页签:在根目录的app.json下增加如下代码:

,
"tabBar": {
"color": "#6e6d6b",
"selectedColor": "#e64340",
"borderStyle": "white",
"backgroundColor": "#fff",
"box-shadow": "0 0 6px 0",
"list": [
{
"pagePath": "pages/index/index",
"iconPath": "images/nav/home-off.png",
"selectedIconPath": "images/nav/home-on.png",
"text": "首页"
},
{
"pagePath": "pages/test/test",
"iconPath": "images/nav/my-off.png",
"selectedIconPath": "images/nav/my-on.png",
"text": "test"
}
]
}

这样就有了首页和测试页的切换页签了,这里需要四个图片,首页的选择、未选中图和测试页的选中、未选中图。加入代码后,项目如下图:



在test.js中加入以下代码,其中APP_ID和APP_SECRET要改成你自己的

// pages/test/test.js
const APP_ID = 'wxxxxxxx';//输入小程序appid
const APP_SECRET = 'xxxxxxxxxxxxxxxxxxxx';//输入小程序app_secret
var OPEN_ID = ''//储存获取到openid
var SESSION_KEY = ''//储存获取到session_key
var CODE=''
Page({
getOpenIdTap: function () {
var that = this;
wx.login({
success: function (res) {
wx.request({
//获取openid接口
url: 'https://api.weixin.qq.com/sns/jscode2session',
data: {
appid: APP_ID,
secret: APP_SECRET,
js_code: res.code,
grant_type: 'authorization_code'
},
method: 'GET',
success: function (res) {
console.log(res.data)
OPEN_ID = res.data.openid;//获取到的openid
SESSION_KEY = res.data.session_key;//获取到session_key
console.log(OPEN_ID.length)
console.log(SESSION_KEY.length)
that.setData({
openid: res.data.openid.substr(0, 10) + '********' + res.data.openid.substr(res.data.openid.length - 8, res.data.openid.length),
session_key: res.data.session_key.substr(0, 8) + '********' + res.data.session_key.substr(res.data.session_key.length - 6, res.data.session_key.length)
})
}
})
}
})
},
getCodeTap:function(){
var that = this;
wx.login({
success: function (res) {
CODE = res.code;//code
console.log(CODE)
that.setData({
code: CODE
})
}
})
}
})

在test.wxml中加入以下代码

<image class="logo" src="{{userInfo.avatarUrl}}"></image>
<button bindtap="getOpenIdTap">获取用户唯一标识openid</button>
openid:{{openid}}session_key:{{session_key}}

<button bindtap="getCodeTap">获取CODE</button>
code:{{code}}

保存代码后,如下图所示,点击“获取code”,可以拿到小程序授权的code,拿到code后加上自己系统用户名密码就可以向你的系统后台发送请求进行绑定操作了。



增加了登录绑定页面,代码见以下链接



源码下载:https://gitee.com/xszhangmin/wechat-app-test/tree/master
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐