微信小程序wx.login登陆+php

wxml:

<button bindtap='login'>登录</button>

js:

 //登录获取code  
  login: function () {
    wx.login({
      success: function (res) {
        console.log(res)        //发送请求        
        wx.request({
          url: 'http://localhost:8099/login.php', //接口地址          
          data: { code: res.code },
          success: function (res) {
            if (res.statusCode == 200) {
              console.log(res.data)
              wx.setStorageSync('openid', res.data)
            }
            else {
              console.log(res.errMsg)
            }
          },
          fail:function(e){
            console.log(e)
          }
        })
      }
    })
  },

php:

<?php
//声明CODE,获取小程序传过来的CODE
if(!isset($_GET["code"])){
    echo json_encode(array("statusCode"=>0 , "data"=>null , "errMsg"=>"error"));
    exit;
}
$code = $_GET["code"];
//配置appid
$appid = "wx8b7c8ec48bde6f27";
//配置appscret
$secret = "91dcf8013656dd5335a4a6c820cbc9f7";

$url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
$info = file_get_contents($url);//get请求网址,获取数据
$jsonObj = json_decode($info);//对json数据解码
if(isset($jsonObj->errcode)){
    echo json_encode(array("statusCode"=>0 , "data"=>null , "errMsg"=>$info));
    exit;
}
$openid = $jsonObj->openid;
$session_key = $jsonObj->session_key;
echo json_encode(array("statusCode"=>0 , "data"=>$jsonObj , "errMsg"=>"success"));

?>

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值