支付宝的demo:https://docs.open.alipay.com/270/106291/
一般是在notify_url 异步通知 里写业务代码。return_url只做付款成功后展示页。
要点
notify_url 要能直接访问到,不能有登录密码之类
写完后发现成功返回return_url,却进入不了notify_url的post,原来是外部无法访问,果断禁用登录访问
public $enableCsrfValidation = false; //关闭csrf验证,允许表单多次提交
public $layout=false; //禁用框架,包括不登录无法访问功能
controller
public function actionServermoney1()
{
$thirdid = Yii::$app->user->identity->thirdid;
$money = 0.01;
$randstr = RechargeController::getrandstr();
$out_trade_no = 'servermoney' . $randstr . '-' . time();
$models = new IbdThirdServicemoney();
$models->money = $money*100;
$models->time = time();
$models->thirdid = $thirdid;
$models->status = 0;
$models->tradeno = $out_trade_no;
$models->save();
//构造参数
$payRequestBuilder = new \AlipayTradePagePayContentBuilder();
$payRequestBuilder->setSubject('开通服务费');
$payRequestBuilder->setTotalAmount($money);
$payRequestBuilder->setOutTradeNo($out_trade_no);
$config=Yii::$app->params['config2'];
$aop = new \AlipayTradeService($config);
/**
* pagePay 电脑网站支付请求
* @param $builder 业务参数,使用buildmodel中的对象生成。
* @param $return_url 同步跳转地址,公网可以访问
* @param $notify_url 异步通知地址,公网可以访问
* @return $response 支付宝返回的信息
*/
$response = $aop->pagePay($payRequestBuilder, $config['return_url'], $config['notify_url']);
$json["status"] = 1;
$json["data"] = $response;
var_dump($response);
die;
}
params
'config2'=>[
'app_id' => "支付宝app_id",
'merchant_private_key' => "key1",
'notify_url' => "网站地址/third/notice/alinotify",
'return_url' => "网站地址/third/recharge/alireturn",
'charset' => "UTF-8",
'sign_type'=>"RSA2",
'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
'alipay_public_key' => "key2",
],
NoticeController
<?php
namespace third\controllers;
use common\models\GIm;
use Yii;
use \yii\filters\AccessControl;
use \yii\web\Controller;
require_once dirname(dirname(__DIR__)) . '/vendor/alipay/pagepay/buildermodel/AlipayTradePagePayContentBuilder.php';
require_once dirname(dirname(__DIR__)) . '/vendor/alipay/pagepay/service/AlipayTradeService.php';
class NoticeController extends Controller{
public $enableCsrfValidation = false;
public $layout=false; //重写这个属性就可以了 [yii2]不加载layout布局文件的实现方法
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'error','view','alinotify'],
'allow' => true,
],
[
'actions' => ['view','alinotify'],
'allow' => true,
'roles' => ['@'],
],
],
],
];
}
/**
* @inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
];
}
public function actionAlinotify(){
//获取回调参数,这里是以post传值
$data=Yii::$app->request->post();
//获取配置参数
$config=Yii::$app->params['config2'];
//实例化service对象
$serviceobj= new \AlipayTradeService($config);
//验证数据是否为支付宝返回
$result=$serviceobj->check($data);
if($result){
//成功
if($data['trade_status']=="TRADE_SUCCESS"){
//业务代码
}
}else{
echo "fail";
}
}
}