首页 技术 正文
技术 2022年11月19日
0 收藏 610 点赞 4,372 浏览 1554 个字

微信小程序开放了微信登录的api,无论是个人还是企业申请的小程序均可使用。

首先创建一个项目,把这些代码都清空,我们自己写!

然后,开始写了!
首先index.wxml,写一个button用于发起登录

index.wxml

<!--index.wxml-->
<button bindtap='login'>登录</button>

然后写index.js

通过wx.login()来获取code
如果成功获取,那么返回code
然后调用wx.request()向服务端发起一个请求,即向登录api接口发送code
换取openid和session_key

api接口:

https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=APPSECRET&js_code=CODE&grant_type=authorization_code
//index.js
//获取应用实例
const app = getApp()
Page({
data: { },
//登录获取code
login:function(){
wx.login({
success:function(res){
console.log(res.code)
//发送请求
wx.request({
url: 'test.php', //接口地址
data: {code:res.code},
header: {
'content-type': 'application/json' //默认值
},
success: function (res) {
console.log(res.data)
}
})
}
})
}
})

app.js,这个清空,留下这样就行了

//app.js
App({})

那么到这里,小程序端已经搞定了。
开始写服务端,也很容易。

首先获取从小程序传过来的code
再配置自己小程序的appid和appscret
把这些参数拼接到api接口上进行请求发送就可以返回openid和session_key

<?php
//声明CODE,获取小程序传过来的CODE
$code = $_GET["code"];
//配置appid
$appid = "修改成你小程序的APPID";
//配置appscret
$secret = "修改成你小程序的APPSECRET";
//api接口
$api = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
//获取GET请求
function httpGet($url){
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 500);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
curl_setopt($curl, CURLOPT_URL, $url);
$res = curl_exec($curl);
curl_close($curl);
return $res;
}
//发送
$str = httpGet($api);
echo $str;
?>

OK完成!把服务端上传到服务器,换到上面的这里

然后就可以再控制台打印出openid和session_key了

获取到了,你想怎么玩就怎么玩!后面可以通过wx.getUserinfo获取用户基本信息(头像,昵称,城市,个性签名等相关信息)

作者:tanking

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,082
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,557
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,406
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,179
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,815
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898