Exchange.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use \think\Db;
  5. /*
  6. * 收益兑换金币
  7. * */
  8. class Exchange extends Api
  9. {
  10. protected $noNeedLogin = ['*'];
  11. protected $noNeedRight = ['*'];
  12. public function _initialize()
  13. {
  14. parent::_initialize();
  15. }
  16. //兑换配置
  17. public function config(){
  18. $rs = Db::name('exchange')->order('id asc')->select();
  19. if ($rs) {
  20. foreach ($rs as &$v) {
  21. $v['money_to_gold'] = config('site.money_to_gold');
  22. }
  23. $arr = [
  24. 'id' => -1,
  25. 'money' => 0,
  26. 'gold' => 0,
  27. 'money_to_gold' => config('site.money_to_gold')
  28. ];
  29. array_push($rs, $arr);
  30. }
  31. $result = [
  32. 'config' => $rs,
  33. 'money' => model('wallet')->getWallet($this->auth->id,'money'),
  34. ];
  35. $this->success('success',$result);
  36. }
  37. //兑换金币
  38. public function exchangegold() {
  39. $id = input('id', 0, 'intval');
  40. $freemoney = input_post('free_money', 0, 'intval'); //自定义
  41. $uid = $this->auth->id;
  42. if(!$id && !$freemoney){
  43. $this->error('请选择或填写兑换金额');
  44. }
  45. if ($id) {
  46. //赋值money
  47. $exchange = Db::name('exchange')->where('id', $id)->find();
  48. if(!$exchange){
  49. $this->error('请选择或填写兑换金额');
  50. }
  51. $money = $exchange ? $exchange['money'] : 0;
  52. $gold = $exchange ? $exchange['gold'] : 0;
  53. }
  54. if ($freemoney) {
  55. $money = $freemoney;
  56. $bili = config('site.money_to_gold');
  57. $gold = bcmul($money,$bili,0);
  58. }
  59. if($money<=0) {
  60. $this->error('收益金额必须大于0');
  61. }
  62. if($money > 10000){
  63. $this->error('收益金额太大,请分批进行');
  64. }
  65. //验证余额
  66. $user_info = model('wallet')->getWallet($this->auth->id);
  67. if ($user_info['money'] < $money) {
  68. $this->success('您的余额不足', ['code' => 2]);
  69. }
  70. //开启事务
  71. Db::startTrans();
  72. //扣费
  73. $wallet_rs = model('wallet')->lockChangeAccountRemain($uid,0,'money',-$money,18,'兑换金币');
  74. if($wallet_rs['status'] === false){
  75. Db::rollback();
  76. $this->error($wallet_rs['msg']);
  77. }
  78. //赠送金币
  79. $wallet_rs = model('wallet')->lockChangeAccountRemain($uid,0,'gold',$gold,19,'获得兑换金币');
  80. if($wallet_rs['status'] === false){
  81. Db::rollback();
  82. $this->error($wallet_rs['msg']);
  83. }
  84. Db::commit();
  85. $this->success('兑换成功');
  86. }
  87. }