basePath . "/utils/Alipay/alipaySdk/aop/AopClient.php";;
class AlipayCallbackController extends Controller
{
/**
* 支付宝第三方应用授权回调
*/
public function actionIndex()
{
$app_id = get_params('app_id');
$app_auth_code = get_params('app_auth_code');
$store_id = get_params('state');
$store = Store::findOne(['is_delete' => 0, 'id' => $store_id]);
if (!$store || empty($app_id) || empty($app_auth_code)) {
\Yii::error('<====================> 支付宝第三方应用授权回调 参数错误, 参数为:' . json_encode([
'app_auth_code' => $app_auth_code,
'store_id' => $store_id,
'app_id' => $app_id
]));
echo '授权失败,参数错误';
exit;
}
// 拿app_auth_code换取app_auth_token
$res = AlipayProfit::token($app_auth_code);
if ($res['code'] != 0) {
\Yii::error('<====================> token解析失败, 参数为:' . json_encode([
'app_auth_code' => $app_auth_code,
'store_id' => $store_id,
'app_id' => $app_id,
'res' => $res['res']
]));
echo '授权失败,token解析失败,错误信息:' . $res['msg'];
exit;
}
$store->app_auth_token = $res['data'];
if (!$store->save()) {
\Yii::error('<====================> 入库失败, 参数为:' . json_encode([
'app_auth_code' => $app_auth_code,
'store_id' => $store_id,
'app_id' => $app_id,
]));
echo '授权失败,入库失败,错误信息:' . $store->errors[0];
exit;
}
echo '授权成功!';
exit;
}
public function actionSpi()
{
/**
$_GET = [
'sign' => 'drbisEtHBiDpTnQrc8a3eCPq3YWZG1I5oLXoi1kyIGcpnaSvS5ecXc5GO3lbfwqCkUN9pPtmEOnnof169NcTB1U8BX8rVU3AvAzAWzi2fbnhX9Z8PrlhdlxKOXjLrUw0arwo+RUkCyr6gQDvwzGgoUzqyhaqPkk8HM922P3/rSOmy2q5Pi6Qi5Cqb+iJMhn31tSQqDnRJL+4l2Nm8EDkpTTbyKVzJMbAHrOUVlvkQnc7ifkIOTnpTtjoysP6hIjuD8ToB9MIFEl/AHq1ZTBFKcmOblPrBydiOuAuw5KekV+1znDjlU+94sJVi6n1Dl1FG1BPoBfRBD/xLttpCmne7g=='
'method' => 'spi.alipay.user.opencard.get'
'charset' => 'UTF-8'
'version' => '1.0'
'utc_timestamp' => '1672819815'
'sign_type' => 'RSA2'
]
*
*/
\Yii::error([__METHOD__, all_params()]);
$method = $_GET['method'];
$action = str_replace('.', '_', $method);
$res = $this->$action();
return $this->asJson($res);
}
public function spi_alipay_user_opencard_get() {
/**
$_POST = [
'user_id' => '2088902351536970'
'user_info' => '[{\'OPEN_FORM_FIELD_GENDER\':\'男\'},{\'OPEN_FORM_FIELD_MOBILE\':\'13888888888\'},{\'OPEN_FORM_FIELD_NAME\':\'李四\'}]'
'out_serial_no' => '1621923366000'
'biz_card_no' => '000001'
'template_id' => '20200312000000000414103000300846'
'out_string' => 'test'
]
*
*/
$card = new Card();
$res = $card->spi_alipay_user_opencard_get($_POST);
return $res;
}
/**
* 支付宝审核结果通知回调
*/
public function actionAliNotice()
{
try {
$file_name = \Yii::$app->runtimePath . '/logs/app_ali.log';
file_put_contents($file_name, "\r\n" . '[支付宝回调信息][' . date('Y-m-d H:i:s') . ']' . json_encode(post_params()), FILE_APPEND);
\Yii::error("支付宝审核结果通知回调post\n" . json_encode(post_params()));
if (empty(post_params('notify_type')) && empty(post_params('msg_method'))) {
$aop = new AopClient();
$aop->postCharset="GBK";
$aop->rsaPrivateKey = Option::get("alipay_app_private_key",0,'saas')['value'];
$aop->alipayrsaPublicKey=Option::get("alipay_public_key",0,'saas')['value'];
$res = $aop->rsaCheckV2(post_params(),NULL,"RSA2");
if ($res) {
$response_xml = "true" . $aop->alipayrsaPublicKey . "";
} else {
$response_xml = "falseVERIFY_FAILED" . $aop->alipayrsaPublicKey . "";
}
$mysign = $aop->alonersaSign($response_xml, $aop->rsaPrivateKey, "RSA2");
$return_xml = "" . $response_xml . "" . $mysign . "RSA2";
\Yii::error("response_xml: " . $return_xml);
echo $return_xml;
exit ();
}
$biz_content = post_params('biz_content');
$biz_content = json_decode($biz_content, true);
if (post_params('notify_type') === "open_app_auth_notify") {
$detail = $biz_content['detail'];
// $notify_context = $biz_content['notify_context'];
// $trigger_context = $notify_context['trigger_context'];
// $out_biz_no = $trigger_context['out_biz_no'];
$mini = StoreAliMini::find()->where(['auth_app_id' => post_params('auth_app_id')])->one();
if (!$mini && $biz_content['notify_context']['trigger_context']['out_biz_no']) {
$mini = StoreAliMini::findOne(['order_no' => $biz_content['notify_context']['trigger_context']['out_biz_no']]);
}
$mini->auth_app_id = post_params("auth_app_id");
$mini->auth_token = $detail['app_auth_token'];
$mini->userid = $detail['user_id'];
$mini->refresh_token = json_encode([
'app_refresh_token' => $detail['app_refresh_token'],
'end_time' => time() + $detail['re_expires_in'],
]);
$mini->auth_code = $detail['app_auth_code'];
$res = $mini->save();
if ($res) {
$form = new AlipayThirdForm();
// 保存小程序资料
$form->aesAuth(0, $mini->id);
$res = $form->updateMiniVersion($mini->id);
if ($res['code'] === 0) {
echo "success";
exit();
} else {
\Yii::error("支付宝审核结果通知回调" . $res['msg']);
throw new \Exception($res['msg']);
}
}
} elseif (post_params('msg_method') === "alipay.open.mini.merchant.confirmed") {
$mini = StoreAliMini::find()->where(['or', ['order_no' => $biz_content['out_order_no']], ['order_no' => $biz_content['order_no']]])->one();
$mini->auth_app_id = $biz_content['min_app_id'];
$order_cancel = $biz_content['status'];
if ($order_cancel === "REJECTED" || $order_cancel === "TIMEOUT") {
$mini->order_cancel = 1;
}
$res = $mini->save();
\app\modules\alliance\models\store\SalesmanNewStoreForm::aliPush($biz_content, $mini);
if ($res) {
echo "success";
exit();
} else {
throw new \Exception(json_encode($mini->errors));
}
} elseif (post_params('msg_method') === "alipay.open.auth.appauth.cancelled") {
$mini = StoreAliMini::find()->where(['auth_app_id' => $biz_content['auth_app_id']])->one();
$mini->is_cancel = 1;
$res = $mini->save();
if ($res) {
echo "success";
exit();
} else {
throw new \Exception(json_encode($mini->errors));
}
} elseif (post_params('msg_method') === "alipay.open.app.api.field.changed") {
$mini = StoreAliMini::find()->where(['auth_app_id' => $biz_content['user_app_id']])->one();
$mini->is_get_phone = 1;
if ($biz_content['status'] === "AGREE") {
$mini->is_get_phone = 2;
} else {
$mini->is_get_phone = 3;
$mini->apply_phone_fail = $biz_content['reason'];
}
$res = $mini->save();
if ($res) {
echo "success";
exit();
} else {
throw new \Exception(json_encode($mini->errors));
}
} elseif (post_params('msg_method') === "ant.merchant.expand.shop.save.rejected") {
//创建门店审核失败
$mini_shop = StoreAliShop::findone(['shop_order_id' => $biz_content['order_id']]);
$mini_shop->status = -1;
$mini_shop->fail_reason = $biz_content['reason'];
$res = $mini_shop->save();
if ($res) {
$mini = StoreAliMini::findOne($mini_shop->mini_id);
$mini->shop_status = 3;
if (!$mini->save()) {
throw new \Exception(json_encode($mini->errors));
} else {
echo "success";
exit();
}
} else {
throw new \Exception(json_encode($mini_shop->errors));
}
} elseif (post_params('msg_method') === "ant.merchant.expand.shop.save.passed") {
//创建门店审核通过
$mini_shop = StoreAliShop::findone(['shop_order_id' => $biz_content['order_id']]);
$mini_shop->status = 2;
$res = $mini_shop->save();
if ($res) {
$mini = StoreAliMini::findOne($mini_shop->mini_id);
$mini->shop_status = 2;
if (!$mini->save()) {
throw new \Exception(json_encode($mini->errors));
} else {
echo "success";
exit();
}
} else {
throw new \Exception(json_encode($mini_shop->errors));
}
} elseif (post_params('msg_method') === "alipay.marketing.activity.delivery.changed") {
//推广计划审核通知
$activityDelivery = AlipayActivityDelivery::findOne(['delivery_id' => $biz_content['delivery_id']]);
$fail_reason = '';
switch ($biz_content['delivery_status']) {
case "ACTIVE":
$status = 1;
break;
case "INACTIVE":
$status = 2;
break;
case "AUDIT_NO_PASS":
$status = 3;
$fail_reason = $biz_content['delivery_error_msg'];
break;
default:
$status = 0;
break;
}
$activityDelivery->status = $status;
$activityDelivery->fail_reason = $fail_reason;
$activityDelivery->delivery_booth_code = 1;
if ($biz_content['delivery_booth_code'] === 'PAYMENT_RESULT') {
$activityDelivery->delivery_booth_code = 2;
}
$res = $activityDelivery->save();
if ($res) {
echo "success";
exit();
} else {
throw new \Exception(json_encode($activityDelivery->errors));
}
} elseif (post_params('msg_method') === "alipay.marketing.activity.message.received") {
$order_voucher = ActivityOrdervoucher::findOne(['alipay_activity_id' => $biz_content['activity_id']]);
$voucher_code = AlipayVoucherCode::findOne(['voucher_code' => $biz_content['voucher_code'], 'activity_ordervoucher_id' => $order_voucher->id]);
$user = User::findOne(['alipay_open_id' => $biz_content['receive_user_id']]);
$has = UserCoupon::findOne(['voucher_code_id' => $voucher_code->id]);
if($has){
return;
}
$coupon = new UserCoupon();
$coupon->user_id = $user ? $user->id : 0;
$coupon->alipay_open_id = $biz_content['receive_user_id'];
$coupon->store_id = $order_voucher->store_id;
$coupon->coupon_id = $order_voucher->coupon_id;
$coupon->coupon_auto_send_id = 0;
$coupon->type = 1;
$coupon->is_use = 0;
$coupon->is_expire = 0;
$coupon->is_delete = 0;
$coupon->created_at = time();
$coupon->begin_time = $order_voucher->publish_start_time ? strtotime($order_voucher->publish_start_time) : 0;
$coupon->end_time = $order_voucher->publish_end_time ? strtotime($order_voucher->publish_end_time) : 0;
$coupon->voucher_code_id = $voucher_code->id;
$coupon->save();
} elseif (post_params('msg_method') === "alipay.marketing.activity.message.used") {
AlipayAcitvityVoucherOrder::usedNotify($biz_content);
} elseif (post_params('msg_method') === "alipay.commerce.logistics.waybill.istdstatus.changed") {
ADelivery::alipayCommerceLogisticsWaybillIstdstatusChanged($biz_content);
} else {
$version = $biz_content['mini_app_version'] ?? "";
$mini = StoreAliMini::find()->where(['auth_app_id' => $biz_content['mini_app_id'], 'is_cancel' => 0])->one();
$storeVersion = StoreAliMiniVersion::find()->where(['template_version' => $version, 'mini_id' => $mini->id])->one();
if (!empty($mini)) {
$storeVersion->is_submit = 2;
if (!empty($biz_content['audit_reason'])) {
$storeVersion->is_submit = 3;
$storeVersion->fail_reason = $biz_content['audit_reason'];
}
$storeVersion->fail_time = time();
if (post_params('msg_method') === "alipay.open.mini.merchant.confirmed") {
$storeVersion->is_submit = 0;
}
$res = $storeVersion->save();
if ($res) {
echo "success";
exit();
} else {
throw new \Exception($storeVersion->errors);
}
}
}
if (empty(post_params())) {
echo "fail";
exit();
}
} catch (\Exception $e) {
$file_name = \Yii::$app->runtimePath . '/logs/app_ali.log';
file_put_contents($file_name, "\r\n" . '[支付宝回调信息处理结果][' . date('Y-m-d H:i:s') . ']' . json_encode($e->getMEssage()), FILE_APPEND);
\Yii::error("支付宝审核结果通知回调" . $e->getMessage() . $e->getLine());
}
}
public function actionGetToken(){
try {
$state = get_params('state');
$auth_code = get_params('app_auth_code');
$state = explode('_', base64_decode($state));
$store_id = $state[0];
if (!empty($state[1]) && $store_id) {
$form = new AlipayThirdForm();
$form->auth_code = $auth_code;
$form->store_id = $store_id;
$res = $form->setAuthCode();
throw new \Exception(json_encode($res));
}
$log = StoreMiniToken::findOne(['store_id' => $store_id]);
//设置基础请求数据
$aop = new AopClient();
//设置appid
$aop->appId = Option::get("alipay_appid", 0, 'saas')['value'];
//设置私钥
$aop->rsaPrivateKey = Option::get("alipay_app_private_key", 0, 'saas')['value'];
//设置公钥
$aop->alipayrsaPublicKey = Option::get("alipay_public_key", 0, 'saas')['value'];
//设置ase_key,加签方式
$aop->encryptKey = Option::get("alipay_aes_key", 0, 'saas')['value'];
//设置加解密方式
$aop->signType = "RSA2";
$param = json_encode([
"grant_type" => "authorization_code",
"code" => $auth_code
]);
$request = new AlipayOpenAuthTokenAppRequest();
$request->setBizContent($param);
$result = $aop->execute($request);
//请求后的数据处理
$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
$result = $result->$responseNode;
if (!empty($result->code) && $result->code == 10000) {
$token = $result->tokens[0];
$log->app_auth_token = $token->app_auth_token;
$log->update_at = time();
$log->status = 1;
$res = $log->save();
if (!$res) {
throw new \Exception($log->errors);
}
echo "
您已完成授权,请告知操作员
";exit();
}
throw new \Exception($result->sub_msg);
} catch (\Exception $e) {
$file_name = \Yii::$app->runtimePath . '/logs/app_ali_token.log';
file_put_contents($file_name, "\r\n" . '[token返回值][' . date('Y-m-d H:i:s') . ']' . json_encode($e->getMessage()), FILE_APPEND);
}
}
}