环境:宝塔-centOS8.5,php8.3
第一步:安装alipay v3版本的安装依赖包;
composer require alipaysdk/openapi:@dev
第二步:根据官方文档,把支付相关的类引用进来;
<?php
declare (strict_types = 1);namespace app\pc\controller;use think\Request;
use think\facade\Log;use \Alipay\OpenAPISDK\ApiException;
use Alipay\OpenAPISDK\Util\AlipayConfigUtil;
use Alipay\OpenAPISDK\Util\GenericExecuteApi;
use Alipay\OpenAPISDK\Util\Model\AlipayConfig;
use Alipay\OpenAPISDK\Util\Model\CustomizedParams;
use Alipay\OpenAPISDK\Util\Model\OpenApiGenericRequest;
use GuzzleHttp\Client;class Alipay
{public function index(){// 初始化SDK$alipayConfigUtil = new AlipayConfigUtil($this->getAlipayConfig());$apiInstance = new GenericExecuteApi($alipayConfigUtil,new Client());// 构造请求参数以调用接口$bizParams = array();$bizContent = array();// 设置订单标题$bizContent['subject'] = "Iphone6 16G";// 设置产品码$bizContent['product_code'] = "FAST_INSTANT_TRADE_PAY";// 设置订单附加信息$bizContent['body'] = "Iphone6 16G";// 设置商户订单号$bizContent['out_trade_no'] = "20150320010101001";// 设置订单总金额$bizContent['total_amount'] = "0.01";$bizParams['biz_content'] = $bizContent;try {// 如果是第三方代调用模式,请设置app_auth_token(应用授权令牌)$pageRedirectionData = $apiInstance->pageExecute('alipay.trade.page.pay', 'POST', $bizParams);// 如果需要返回GET请求,请使用// $pageRedirectionData = $apiInstance->pageExecute('alipay.trade.page.pay', 'GET', $bizParams);return view('/alipay', ['data'=>$pageRedirectionData]);} catch (ApiException $e) {echo '调用失败: ', $e->getMessage(), PHP_EOL;echo 'body: ', $e->getResponseBody(), PHP_EOL;echo 'header: ', $e->getResponseHeaders(), PHP_EOL;}}function getAlipayConfig(){$alipayConfig = new AlipayConfig();$alipayConfig->setServerUrl('https://openapi.alipay.com');$alipayConfig->setAppId('应用ID');$alipayConfig->setPrivateKey('应用密钥');$alipayConfig->setAlipayPublicKey('支付宝应用公钥');return $alipayConfig;}/*** 支付宝异步通知** @return \think\Response*/public function notify(){// 获取支付宝异步通知的信息,该信息是POST请求方式$res = request()->post();// $res是数组,需要转换为JSON;$data = json($res);// 通过tp的Log工具,存储信息,供排错和修改商户支付业务逻辑使用;Log::info($data);// 一定要返回success,否则支付宝服务器每间隔一段时间会发起异步回调通知;return 'success';}
}
第三步:视图页面代码
<!DOCTYPE html>
<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8" /><title>alipay page</title></head><body>{$data|raw} <!--一定不要转义,原生输出;--></body>
</html>