小程序php登录

转摘自:https://blog.csdn.net/gahoyeung/article/details/94593695

公司项目后续需要增加小程序前端,而公司项目用户使用时需要输入该项目用户的用户名与密码,用户每次使用都需要输入就非常不方便,所以通过小程序API接口取到用户唯一标识openid后可以与后台数据库中存储的批量openid进行对比查找,如果用户账号所对应的openid在数据库中则跳过登录界面直接使用。

目前只是写了一个demo:

小程序前端index.js通过wx.login获取登录凭证(code),然后通过RequestTask wx.request(Object object)发起 HTTPS 网络请求,向后台传输code,后台通过code去调用接口取到openid和session_key后返回给前端

Page({
  data: {
 
  },
  getOpenId: () => {
    wx.login({
      success: res => {
        console.log(res.code)
        wx.request({
          url: 'http://127.0.0.1/test.php',
          data: {
            code: res.code
          },
          
          success: res => {
            console.log(res.data)
          }
        })
      }
    })
  }
})

后台test.php需要有对应小程序的appid和appsecret,这两个都是开发者id,即开发者申请小程序开发后就有的,同一开发者名下所有小程序要用的appid和appsecret都是这个。test.php通过$_GET[ ]得到前端传过来的code,利用这个code调用微信小程序的auth.code2Session接口换取使用该小程序用户对应的openid,请求地址是

GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

<?php
 
define("WX_APPID", "wx0230c92de862ad84");
define("WX_SECRET", "b10a359aa0576a947fc9e5e9085ee840");
 
$code = $_GET["code"];
 
function getWX ($code) {
    $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' .WX_APPID .'&secret=' . WX_SECRET . '&js_code='. $code .'&grant_type=authorization_code';
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}
 
$resp = getWX($code);
echo $resp;
 
?>

wx.login API:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html

wx.request API:https://developers.weixin.qq.com/miniprogram/dev/api/network/request/wx.request.html

auth.code2Session 服务端接口:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值