wordpress收费下载资源主题
wordpress付费下载资源插件

WordPress小程序开发之微信登录

WordPress小程序开发如何实现微信授权登录呢?下面模板兔给出简单的代码:

小程序端js:

wx.login({
success: function (res) {
if (res.code) {
wx.request({
url: app.globalData.appUrl,
data: {
code: res.code,
},
method: 'POST',
header: {
//'content-type': 'application/json'
'content-type': 'application/x-www-form-urlencoded'
}, 
success: function (res2) {
wx.hideToast();
console.log(res2.data);
if (res2.data.errCode == '0'){
wx.setStorageSync('UserId', res2.data.id);
wx.setStorageSync('UserUnionId', res2.data.unionid);

that.setData({ userId: res2.data.id, userAvatarUrl: res2.data.avatar, userNickname: res2.data.nickname})

wx.reLaunch({
url: '../user/user'
})
}else{
wx.showToast({
title: '登录失败',
icon: 'none',
duration: 3000
});
}
},
fail: function(){
wx.showToast({
title: '登录失败',
icon: 'none',
duration: 3000
});
}
})
}
}
})

服务端php:

$appid = '';
$appsecret = '';

$code = $_POST['code'];

$jscode2session = file_get_contents("https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$appsecret."&js_code=".$code."&grant_type=authorization_code");
$arr = json_decode($jscode2session, true);
//var_dump($arr);

$result = array();
$result['errMsg'] = ''; 
$result['errCode'] = 0;

if($arr['errcode']){
$result['errCode'] = $arr['errcode']; 
$result['errMsg'] = $arr['errmsg']; 
}else{
$openid = $arr['openid'];
$unionid = $arr['unionid'];

if($unionid){
$user_id = $wpdb->get_var("SELECT ID FROM $wpdb->users WHERE weixin_unionid='".esc_sql($unionid)."'");
if($user_id){
$result['id'] = $user_id;
$cuser = get_user_by('id',$user_id);
$result['nickname'] = $cuser->nickname;
}else{
$pass = wp_create_nonce(rand(10,1000));
$user_login = "u".mt_rand(1000,9999).mt_rand(1000,9999).mt_rand(1000,9999);
$userdata = array(
'user_login' => $user_login,
'user_pass' => $pass
);
$user_id = wp_insert_user( $userdata );
if ( !is_wp_error( $user_id ) ) {
$update = $wpdb->query("UPDATE $wpdb->users SET weixin_unionid = '".esc_sql($unionid)."' WHERE ID = '$user_id'");
if($update){
$result['id'] = $user_id;
$cuser = get_user_by('id',$user_id);
$result['nickname'] = $cuser->nickname;
}else{
$result['errMsg'] = '绑定用户失败'; 
$result['errCode'] = 1;
}
}else{
$result['errMsg'] = '注册用户失败'; 
$result['errCode'] = 1;
}
}
}else{
$result['errMsg'] = '获取用户信息失败'; 
$result['errCode'] = 1;
}

$result['openid'] = $openid;
$result['unionid'] = $unionid;

}
echo json_encode($result);

以上就是微信小程序wordpress开发微信登录的全部内容!

0 个评论

定制开发
本站承接WordPress等系统建站仿站、二次开发、主题插件定制等开发服务
在线咨询
  • 请直接说明需求,勿问在否
    QQ:1-247-246-247

  • QQ一群:104228692(满)
  • QQ二群:64786792
在线咨询
本站承接WordPress建站仿站、二次开发、主题插件定制等PHP开发服务!

了解详情