Files
heping-api/app/controller/Wechat.php
2022-09-15 16:57:56 +08:00

173 lines
5.1 KiB
PHP

<?php
namespace app\controller;
use app\model\AppUser;
use app\model\Payment;
use EasyWeChat\Factory;
use EasyWeChat\OfficialAccount\Application;
use think\facade\Config;
use think\facade\Db;
use think\facade\Request;
use think\facade\Route;
use think\facade\View;
use think\response\Json;
class Wechat
{
private Application $app;
/**
* Notes : 初始化微信
*
* @Date : 2022/9/9 11:30
* @Author : <Jason.C>
*/
private function initWechat()
{
$this->app = Factory::officialAccount(Config::get('wechat'));
}
/**
* Notes : 获取微信授权的地址并跳转
*
* @Date : 2022/9/9 11:29
* @Author : <Jason.C>
*/
public function url(): Json
{
$url = $GLOBALS['data']['data']['url'];
$redirect = Route::buildUrl('wechat/code', ['callback' => $url])
->suffix(false)
->domain(true);
$this->initWechat();
return show(SUCCESS_MESSAGE, SUCCESS_CODE, $this->app->oauth->scopes(['snsapi_userinfo'])->redirect($redirect));
}
/**
* Notes : 微信授权回调地址,获取到用户信息后,自行保存
*
* @Date : 2022/9/9 11:29
* @Author : <Jason.C>
*/
public function code()
{
$this->initWechat();
$code = Request::get('code');
$wechatUser = $this->app->oauth->userFromCode($code);
$callback = Request::get('callback');
$user = AppUser::where('openid', $wechatUser->getId())->find();
if (! $user) {
$user = AppUser::create([
'nickname' => $wechatUser->getNickname(),
'avatar' => $wechatUser->getAvatar(),
'identity' => 0,
'openid' => $wechatUser->getId(),
]);
}
$tokenData = ['userid' => $user->id, 'loginTime' => time(), 'rankStr' => strRand(5)];
$token = authcode(json_encode($tokenData), 'ENCODE');
$sep = str_contains($callback, '?') ? '&' : '?';
return redirect($callback.$sep.'token='.$token);
}
/**
* Notes : 显示支付的页面,支付逻辑
*
* @Date : 2022/9/9 11:32
* @Author : <Jason.C>
*/
public function payment()
{
$clientToken = Request::get('token');
$orderId = Request::get('order_id');
if ($clientToken) {
$tk = json_decode(authcode($clientToken), true);
$userId = $tk['userid'];
}
$user = AppUser::findOrEmpty($userId);
if (! $user) {
exit('NO USER');
}
$order = \app\model\Order::find($orderId);
if (empty($order)) {
exit('订单信息不存在');
}
if (\app\model\Order::where([
"user_id" => $order['user_id'],
"student_id" => $order['student_id'],
"status" => 1,
])->find()) {
exit('已经为该孩子助力过了');
}
$notifyUrl = Route::buildUrl('wechat/paid')
->suffix(false)
->domain(true)
->build();
$outTradeNo = time().rand(100000, 999999);
Payment::create([
'trade_no' => $outTradeNo,
'order_id' => $order->id,
]);
$config = Config::get('wechat.payment');
$payment = Factory::payment($config);
$unify = $payment->order->unify([
'body' => '商品订单',
'out_trade_no' => $outTradeNo,
'total_fee' => $order->amount * 100,
'notify_url' => $notifyUrl,
'trade_type' => 'JSAPI',
'openid' => $user->openid,
]);
if ($unify['result_code'] == 'FAIL') {
exit($unify['err_code_des']);
}
$prepayId = $unify['prepay_id'];
$jssdk = $payment->jssdk->bridgeConfig($prepayId, false);
return View::fetch('', ['jssdk' => $jssdk]);
}
/**
* Notes : 支付完成回调
*
* @Date : 2022/9/9 11:33
* @Author : <Jason.C>
*/
public function paid()
{
$config = Config::get('wechat.payment');
$payment = Factory::payment($config);
return $payment->handlePaidNotify(function ($message, $fail) {
$order = Payment::where('trade_no', $message['out_trade_no'])->find();
if (! $order || $order->paid_at) {
return true;
}
if (key_exists('result_code', $message) && $message['result_code'] === 'SUCCESS') {
$order->paid();
//订单支付成功。查询用户信息
$order_detail = \app\model\Order::where("id", $order->order_id)->find();
//为用户增加助力值
$zhuLi = env("ZHULI_VALUE") ?? 150;
Db::name("student")->inc("hot", $zhuLi)->where("id", $order_detail->id)->update();
Db::name("student")->inc("hot_count", 1)->where("id", $order_detail->id)->update();
return true;
}
return $fail('Order not exists.');
});
}
}