vue 接口获取微信用户信息
前端 vue代码
<script>
export default {
name: 'App',
components:{
Loading
},
created() {
//测试先关闭微信
window.localStorage.setItem('userid','VDaNI');
//当不存在用户userid时,获用微信户信息
if(!window.localStorage.getItem('userid')){
//当url存在code参数时
if(this.getUrlKey('code')){
let code = this.getUrlKey('code');
let userinfo = this.getUserinfo(code);
}else{
this.getcode();
}
}
},
methods:{
//请求微信code
getcode:function(){
//发起请求
let that = this;
let data = new FormData();
data.append('type','snsapi_userinfo'); //请求用户信息类型
data.append('backurl',window.location.href);
this.axios.post('/api/wx/codeUrl',data).then(function (response) {
window.location.href= response.data;
}).catch(function (error) {console.log(error)});
},
//获取微信用户信息
getUserinfo:function(code){
let that = this;
let data = new FormData();
data.append('code',code);
this.axios.post('/api/wx/getUserinfo',data).then(function (response) {
console.log(response.data);
if(response.data.sta == 1){
let userid = response.data.userid;
window.localStorage.setItem('userid',userid); //本地存储用户userid
}
}).catch(function (error) {console.log(error)});
},
//获取get参数方法
getUrlKey:function(name){
let url= window.location.href;
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [, ""])[1].replace(/\+/g, '%20')) || null
}
}
}
</script>php tp5框架 后端接口
<?php
namespace app\api\controller;
use think\Db;
class Wx extends Common
{
public $config;
//读取微信配置
//"wx_token" => "token",
//"wx_appid" => "appid",
//"wx_appsecret"=> "appsecret",
private function getConfig()
{
if(!$this->config){
$config = config('mySet.wxConfig');
$this->config = $config;
}
}
//获取请求微信code跳转地址
public function codeUrl()
{
if(!request()->isPost()){return false;}
$backurl = urlencode(input('backurl')); //回调地址
$type = input('type'); //获取用户信息类型
$this->getConfig();
$appid = $this->config['wx_appid'];
$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$backurl.'&response_type=code&scope='.$type.'&state=STATE#wechat_redirect';
return $url;
}
//获取微信用户信息,返回用户id
//post接收 code参数
//返回用户id
public function getUserinfo()
{
$this->getConfig();
if(!request()->isPost()){return false;}
$code = input('post.code');
//access_token
$access = $this->getAccessToken($code);
//请求用户信息
$getUserUrl = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access['access_token'].'&openid='.$access['openid'].'&lang=zh_CN';
$userInfo = file_get_contents($getUserUrl);
//记录用户信息到数据库
$res = $this->saveUser($userInfo);
return $res;
}
//通过code换取网页授权access_token并返回
public function getAccessToken($code)
{
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->config['wx_appid'].'&secret='.$this->config['wx_appsecret'].'&code='.$code.'&grant_type=authorization_code';
$res = file_get_contents($url);
$res = json_decode($res,true);
return $res;
}
//记录用户信息到数据库
public function saveUser($userInfo)
{
$userInfo =json_decode($userInfo,true);
//查看是否存在用户信息
$chcke = Db::name('goods_member')->where('openid',$userInfo['openid'])->find();
if(!empty($chcke))//存在帐号
{
return json(['msg'=>'获取用户信息成功','sta'=>1,'userid'=>lock($chcke['id'])]);
}
else //不存在帐号
{
$data = array();
$data['openid'] = $userInfo['openid'];
$data['headimgurl'] = $userInfo['headimgurl'];
$data['nickname'] = $userInfo['nickname'];
$data['city'] = $userInfo['city'];
$data['province'] = $userInfo['province'];
$data['sex'] = $userInfo['sex'];
$data['addtime'] = time();
$userid = Db::name('goods_member')->insertGetId($data);
return json(['msg'=>'新增用户信息成功','sta'=>1,'userid'=>lock($userid)]);
}
}
}