官方文檔
下載支付寶sdk後解壓放到extend目錄下
在public/index.php中定義常量
參考文檔
define('ALI_PATH',__DIR__.'/../extend/alipay/aop/');
創建控制器並寫入代碼
require ALI_PATH.'AopClient.php';
require ALI_PATH.'request/AlipayFundAuthOrderAppFreezeRequest.php';
class Ali extends Controller{
public static $appid = ''; //appid
public static $pub_key = ''; //應用公鑰
public static $prikey = ''; //應用私鑰
public static $alipubkey = '';//支付寶公鑰
public function shouquan()
{
$aop = new \AopClient ();
$aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
$aop->appId = self::$appid;
$aop->rsaPrivateKey = self::$prikey;
$aop->alipayrsaPublicKey=self::$alipubkey;
$aop->apiVersion = '1.0';
$aop->signType = 'RSA2';
$aop->postCharset='UTF-8';
$aop->format='json';
$request = new \AlipayFundAuthOrderAppFreezeRequest ();
$order_no = time().rand(1111,9999).'orderid';
$l = time().rand(1111111,9999999).'liushui';
DB::name('ali_demo')->insert(['order_no'=>$order_no,'l'=>$l]); //將生成的訂單號和流水號存儲在數據庫,查訂單,撤銷訂單時需要用到
$request->setBizContent("{" .
"\"out_order_no\":\"".$order_no."\"," . //商戶訂單號
"\"out_request_no\":\"".$l."\"," . //商戶流水號
"\"order_title\":\"測試預授權凍結\"," . //描述
"\"amount\":0.01," . //金額
"\"product_code\":\"PRE_AUTH_ONLINE\"," . //銷售產品碼 固定值PRE_AUTH_ONLINE
"\"payee_logon_id\":\"[email protected]\"," . //收款方支付寶賬號 郵箱或手機號
"\"payee_user_id\":2088***********," . //支付寶用戶id 與上方參數任選其一
"\"pay_timeout\":\"90m\"," . //最晚付款時間 90m表示90分鐘後
"\"scene_code\":\"ONLINE_AUTH_COMMON_SCENE\"," . //業務場景
"\"trans_currency\":\"CNY\",". //標價幣種 CNY表示人民幣
"\"settle_currency\":\"CNY\",". //結算幣種
"\"enable_pay_channels\":\"[{\\\"payChannelType\\\":\\\"PCREDIT_PAY\\\"},{\\\"payChannelType\\\":\\\"MONEY_FUND\\\"}]\"" . //指定支付渠道 花唄 餘額寶
" }");
$request->setNotifyUrl(''); //請求成功後的回調地址
$result = $aop->sdkexecute ( $request);
return json_encode($result);
}
}
上面的方法返回一個字符串,將字符串傳到前端,前端用這個字符串來喚起支付頁面,在支付寶app執行資金凍結
小程序前端官方文檔
小程序代碼
aliget() {
my.request({
url: '', //請求資金預授權接口 返回一個長字符串
data:{id:9},
method: 'GET',
success: function (res) {
my.tradePay({
// 調用資金凍結接口(alipay.fund.auth.order.app.freeze),獲取資金授權參數
orderStr: res.data,
success: (res) => {
my.request({
url: '', //我是在這裏做的回調 官方的回調不知道爲什麼一直沒有執行
data:{data:res.result}, //將支付寶返回的數據傳到後臺
type:"post",
success:function(res){
//授權成功
}
})
console.log(res);
},
fail: (res) => {
my.alert({
content: JSON.stringify(res),
});
}
})
},
// 調用失敗的回調函數
fail: function (res) {
my.alert({ content: 'fail' });
},
});
},
在回調中保存支付寶授權號,流水號等,別的接口能用到
後臺回調代碼
public function ordercreate()
{
$res = json_decode(input('data'));
$order = AliOrder::where('order_no',$res->alipay_fund_auth_order_app_freeze_response->out_order_no)->find();
$order->auth_no = $res->alipay_fund_auth_order_app_freeze_response->auth_no;
$order->user_id = $res->alipay_fund_auth_order_app_freeze_response->payer_user_id;
$order->ali_liushui = $res->alipay_fund_auth_order_app_freeze_response->operation_id;
$order->status = 1;
$order->save();
}