支付宝小程序登录PHP

23 篇文章 1 订阅
7 篇文章 1 订阅

支付宝小程序登录PHP

时序图(现在有所改变,可以直接看后面的一部分,前面在爬坑)

img

前言

采用TP5.1的框架实现,我知道这里会有很多的坑,在开发这个之前,我就写了两篇前奏,因为这个登录需要一些参数,这个和微信小程序的不太一样

获取code

首先我们需要调用my.getAuthCode接口获取code,然后传给服务端

首先登录一下支付宝开发者工具

在这里插入图片描述

首先我们写一个简单的发送code的demo,这个在官网里面有https://opendocs.alipay.com/mini/api/openapi-authorize

在这里插入图片描述

后面我这里改了一下js里面的

Page({
  onLoad() {},
  data: {},
  getAuthCode: () => {
    my.getAuthCode({
      scopes: 'auth_user',
      success: (res) => {
        console.log(res.authCode);
        // my.alert({
        //   content: res.authCode,
        // });
        let code = res.authCode
        console.log(res);
        my.request({
            url: 'http://localhost/ttft_2/public/api/v1/getcodeali',
            data: code,
            method: 'POST',
            success: (mes) => {
              console.log(mes);
            }
        });
      },
    });
  },
});

但是这里面又发现了一个坑,不能使用http的请求,因此我们需要在服务器上部署才行,这个口面再发一篇,这里先拿到code再说,注释一下代码,换成这样的

Page({
  onLoad() {},
  data: {},
  getAuthCode: () => {
    my.getAuthCode({
      scopes: 'auth_user',
      success: (res) => {
        console.log(res.authCode);
        my.alert({
          content: res.authCode,
        });
        // let code = res.authCode
        // console.log(res);
        // my.request({
        //     url: 'http://localhost/ttft_2/public/api/v1/getcodeali',
        //     data: code,
        //     method: 'POST',
        //     success: (mes) => {
        //       console.log(mes);
        //     }
        // });
      },
    });
  },
});

其他的就按照官网给的就行,然后我们点击获取授权码

在这里插入图片描述

会弹出这样的消息,在控制台中打印的可以复制

在这里插入图片描述

这样一来,code码到手了

把code码发给服务端

下载支付宝sdk还是给出地址https://docs.open.alipay.com/54/103419

下载好之后把aop文件放到项目的extend目录下

在这里插入图片描述

另外开发这个登录需要的参数我们要准备好,不知道的话,我的前一篇博客里面有

https://blog.csdn.net/qq_45163122/article/details/104148904

我把它写到配置文件当中,(一些公共的资料注意还是一律填写到配置文件当中,方便日后的维护和管理)

在这里插入图片描述

登录需要的就是以上的四个参数

然后开始写我们的方法

<?php

namespace app\api\model;

use think\facade\Env;
use think\Model;


require Env::get('root_path').'extend/aop/aopClient.php';
require Env::get('root_path').'extend/aop/request/AlipaySystemOauthTokenRequest.php';

class User extends Model
{
    public static function getCodeAli($param){
        $aop = new \aopClient();
        $aop->gatewayUrl = config('base.ali_gatewayUrl');
        $aop->appId = config('base.ali_app_id');
        $aop->rsaPrivateKey = config('base.ali_rsaPrivateKey');
        $aop->alipayrsaPublicKey = config('base.ali_alipayrsaPublicKey');
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='utf-8';
        $aop->format='json';
        $request = new \AlipaySystemOauthTokenRequest();
        $request->setGrantType("authorization_code");
        $request->setCode($param['code']);
        //$request->setRefreshToken("201208134b203fe6c11548bcabd8da5bb087a83b");
        $result = $aop->execute($request);
        return $result;

    }
}

就这样就可以登录了

这里再贴出支付宝的文档https://docs.open.alipay.com/api_9/alipay.system.oauth.token/

不过有个问题,难道我说登录就登录了吗?程序怎么会这么听话?当然不是,既然支付宝工具调试不了,那就使用api调试工具,我这里使用Postman

在这里插入图片描述

使用的是post请求,把我们的地址放进去,输入code,不过好像有点问题,因为我们的code码已经过期了需要重新获取,来,重新获取一个新的code

在这里插入图片描述

像这个就是正确的啦,现在服务器已经获取到了access_token这个参数,我们就要进行下一步操作了。

获取用户信息(不能再使用)

通过token接口调用支付宝会员查询接口获取会员信息

来,文档地址https://docs.open.alipay.com/api_2/alipay.user.info.share

上面我们获取的那个access_token是有有效期的,建议存到缓存当中

我们把程序改好了在试一次

<?php

namespace app\api\model;

use think\facade\Env;
use think\Model;


require Env::get('root_path').'extend/aop/aopClient.php';
require Env::get('root_path').'extend/aop/request/AlipaySystemOauthTokenRequest.php';
require Env::get('root_path').'extend/aop/request/AlipayUserInfoShareRequest.php';

class User extends Model
{
    /**
     * 支付宝获取code
     * @param $param
     * @return bool|mixed|\SimpleXMLElement
     * @throws \Exception
     */
    public static function getCodeAli($param){
        $aop = new \aopClient();
        $aop->gatewayUrl = config('base.ali_gatewayUrl');
        $aop->appId = config('base.ali_app_id');
        $aop->rsaPrivateKey = config('base.ali_rsaPrivateKey');
        $aop->alipayrsaPublicKey = config('base.ali_alipayrsaPublicKey');
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='utf-8';
        $aop->format='json';
        $request = new \AlipaySystemOauthTokenRequest();
        $request->setGrantType("authorization_code");
        $request->setCode($param['code']);
        //$request->setRefreshToken("201208134b203fe6c11548bcabd8da5bb087a83b");
        $result = $aop->execute($request);
        //return $result;
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $accessToken= $result->$responseNode->access_token;
        return self::getUserInfoAli($accessToken);
    }

    /**
     * 获取支付宝用户信息
     * @param $accessToken
     * @return bool|mixed|\SimpleXMLElement
     * @throws \Exception
     */
    public static function getUserInfoAli($accessToken){
        $aop = new \AopClient ();
        $aop->gatewayUrl = config('base.ali_gatewayUrl');
        $aop->appId = config('base.ali_app_id');
        $aop->rsaPrivateKey = config('base.ali_rsaPrivateKey');
        $aop->alipayrsaPublicKey = config('base.ali_alipayrsaPublicKey');
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='utf-8';
        $aop->format='json';
        $request = new \AlipayUserInfoShareRequest ();
        $result = $aop->execute ( $request , $accessToken );
        return $result;
    }
}

提醒一下,这里code只能使用一次,使用一次之后就会失效

程序写好之后调用发现了一个惊喜,好吧,坑还是有的,按照他的来

在这里插入图片描述

提升开发权限

找到我们的小程序

在这里插入图片描述

一步一步来

在这里插入图片描述

调用,然后再次出错,陷入一阵。。。。。

在这里插入图片描述

获取用户信息改变

好吧既然如此,就上官网查看

在这里插入图片描述

它居然说不能使用了

通过前台调用用户接口

my.getOpenUserInfo
https://opendocs.alipay.com/mini/api/ch8chh

现在换一种思路,在小程序端查询信息存入到数据库中,

改了一下代码,我在这里贴出来

var app = getApp()
Page({
  data: {
    hasUserInfo: false
  },
  getUserInfo() {
    my.getAuthCode({
      scopes: 'auth_user',
      fail: (error) => {
        console.error('getAuthCode', error);
      },
      success: (res) => {
        let code = res.authCode;
        my.request({
          url: 'https://www.guizimo.top/demo/public/index.php/api/v1/getcodeali',
          method: 'POST',
          data:{
            code:code
          },
        });
        my.getAuthUserInfo({
          fail: (error) => {
            console.error('getAuthUserInfo', error);
          },
          success: (userInfo) => {
            console.log(`userInfo:`, userInfo);
            this.setData({
              userInfo,
              hasUserInfo: true,
            });
            my.request({
              url: 'https://www.guizimo.top/demo/public/index.php/api/v1/setuserinfoali',
              method: 'POST',
              data:{
                avatar:userInfo.avatar,
                nickName:userInfo.nickName
              },
              success: (result) => {
                console.log(result);
                my.alert({
                  content: '登录成功',
                });
              }
            });
          }
        });
      }
    });
  },
  clear() {
    this.setData({
      hasUserInfo: false,
      userInfo: {}
    })
  }
})

后台主要是存入信息,用了两个接口我把实现的方法写在下面

<?php

namespace app\api\model;


use think\Db;
use think\facade\Cache;
use think\facade\Env;
use think\Model;


require Env::get('root_path').'extend/aop/AopClient.php';
require Env::get('root_path').'extend/aop/request/AlipaySystemOauthTokenRequest.php';

class User extends Model
{
    /**
     * 支付宝获取code
     * @param $param
     * @return bool|mixed|\SimpleXMLElement
     * @throws \Exception
     */
    public static function getCodeAli($param){
        //return $param;
        $aop = new \aopClient();
        $aop->gatewayUrl = config('base.ali_gatewayUrl');
        $aop->appId = config('base.ali_app_id');
        $aop->rsaPrivateKey = config('base.ali_rsaPrivateKey');
        $aop->alipayrsaPublicKey = config('base.ali_alipayrsaPublicKey');
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='utf-8';
        $aop->format='json';
        $request = new \AlipaySystemOauthTokenRequest();
        $request->setGrantType("authorization_code");
        $request->setCode($param['code']);
        //$request->setRefreshToken("201208134b203fe6c11548bcabd8da5bb087a83b");
        $result = $aop->execute($request);
        //return $result;
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        //$accessToken= $result->$responseNode->access_token;
        $userid = $result->$responseNode->user_id;
        //return $userid;
        return self::saveUserId($userid);
    }

    /**
     * 保存UserID到数据库
     * @param $userid
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function saveUserId($userid){
        $res = UserAli::where('userid',$userid)->find();
        if($res){
            $Uid = $res['id'];
        }else{
            $Uid = Db::name('user_ali')->insertGetId(['userid'=>$userid]);
        }
        $result = Cache::set('Uid',$Uid);
        return $result;
    }

    /**
     * 保存好信息
     * @param $param
     * @return int|string
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function setUserInfoAli($param){
        $Uid = Cache::get('Uid');
        //return $Uid;
        $res = UserAli::where('id',$Uid)
            ->update([
                'avatar' => $param['avatar'],
                'nickName' => $param['nickName']
            ]);
        return $res;
    }

}

演示

最后来演示一波,实在是太烦了,不过到现在又十分的简单了

在开发者工具中调用接口

在这里插入图片描述

注意这个两个接口的状态

在这里插入图片描述

说明调用没有什么大问题,后面还是搭建了一个环境来测试,不然每次登录都要来这里面获取,真的是很烦。

最后查看数据库,看看我们的数据是否存入成功了

在这里插入图片描述

现在就大功告成了

不过当然还有很多东西需要优化,支付宝的登录和微信小程序的登录有一些不太一样,后面也会写一篇关于微信小程序登录的。

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

归子莫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值