MiniProgramService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. <?php
  2. /**
  3. *
  4. * @author: xaboy<365615158@qq.com>
  5. * @day: 2017/11/23
  6. */
  7. namespace crmeb\services;
  8. use crmeb\repositories\PaymentRepositories;
  9. use EasyWeChat\Foundation\Application;
  10. use EasyWeChat\Payment\Order;
  11. use think\facade\Route as Url;
  12. use crmeb\services\HookService;
  13. use crmeb\interfaces\ProviderInterface;
  14. use app\models\store\StoreOrder as StoreOrderRoutineModel;
  15. use app\models\user\UserRecharge;
  16. /**微信小程序接口
  17. * Class WechatMinService
  18. * @package service
  19. */
  20. class MiniProgramService implements ProviderInterface
  21. {
  22. private static $instance = null;
  23. public function register($config)
  24. {
  25. return ['mini_program',new self()];
  26. }
  27. public static function options()
  28. {
  29. $wechat = SystemConfigService::more(['site_url','routine_appId','routine_appsecret']);
  30. $payment = SystemConfigService::more(['pay_routine_mchid','pay_routine_key','pay_routine_client_cert','pay_routine_client_key','pay_weixin_open']);
  31. $config = [];
  32. $config['mini_program'] = [
  33. 'app_id'=>isset($wechat['routine_appId']) ? trim($wechat['routine_appId']):'',
  34. 'secret'=>isset($wechat['routine_appsecret']) ? trim($wechat['routine_appsecret']):'',
  35. 'token'=>isset($wechat['wechat_token']) ? trim($wechat['wechat_token']):'',
  36. 'aes_key'=> isset($wechat['wechat_encodingaeskey']) ? trim($wechat['wechat_encodingaeskey']):''
  37. ];
  38. $config['payment'] = [
  39. 'app_id'=>isset($wechat['routine_appId']) ? trim($wechat['routine_appId']) :'',
  40. 'merchant_id'=>trim($payment['pay_routine_mchid']),
  41. 'key'=>trim($payment['pay_routine_key']),
  42. 'cert_path'=>realpath('.'.$payment['pay_routine_client_cert']),
  43. 'key_path'=>realpath('.'.$payment['pay_routine_client_key']),
  44. 'notify_url'=>$wechat['site_url'].Url::buildUrl('/api/routine/notify')
  45. ];
  46. return $config;
  47. }
  48. public static function application($cache = false)
  49. {
  50. (self::$instance === null || $cache === true) && (self::$instance = new Application(self::options()));
  51. return self::$instance;
  52. }
  53. /**
  54. * 小程序接口
  55. * @return \EasyWeChat\MiniProgram\MiniProgram
  56. */
  57. public static function miniprogram()
  58. {
  59. return self::application()->mini_program;
  60. }
  61. /**
  62. * 获得用户信息 根据code 获取session_key
  63. * @param array|string $openid
  64. * @return $userInfo
  65. */
  66. public static function getUserInfo($code)
  67. {
  68. $userInfo = self::miniprogram()->sns->getSessionKey($code);
  69. return $userInfo;
  70. }
  71. /**
  72. * 加密数据解密
  73. * @param $sessionKey
  74. * @param $iv
  75. * @param $encryptData
  76. * @return $userInfo
  77. */
  78. public static function encryptor($sessionKey, $iv, $encryptData){
  79. return self::miniprogram()->encryptor->decryptData($sessionKey, $iv, $encryptData);
  80. }
  81. /**
  82. * 上传临时素材接口
  83. * @return \EasyWeChat\Material\Temporary
  84. */
  85. public static function materialTemporaryService()
  86. {
  87. return self::miniprogram()->material_temporary;
  88. }
  89. /**
  90. * 客服消息接口
  91. * @param null $to
  92. * @param null $message
  93. */
  94. public static function staffService()
  95. {
  96. return self::miniprogram()->staff;
  97. }
  98. /**
  99. * 微信小程序二维码生成接口
  100. * @return \EasyWeChat\QRCode\QRCode
  101. */
  102. public static function qrcodeService()
  103. {
  104. return self::miniprogram()->qrcode;
  105. }
  106. /**微信小程序二维码生成接口不限量永久
  107. * @param $scene
  108. * @param null $page
  109. * @param null $width
  110. * @param null $autoColor
  111. * @param array $lineColor
  112. * @return \Psr\Http\Message\StreamInterface
  113. */
  114. public static function appCodeUnlimitService($scene, $page = null, $width = 430, $autoColor = false, $lineColor = ['r' => 0, 'g' => 0, 'b' => 0])
  115. {
  116. return self::qrcodeService()->appCodeUnlimit($scene,$page,$width,$autoColor,$lineColor);
  117. }
  118. /**
  119. * 模板消息接口
  120. * @return \EasyWeChat\Notice\Notice
  121. */
  122. public static function noticeService()
  123. {
  124. return self::miniprogram()->notice;
  125. }
  126. /**发送小程序模版消息
  127. * @param $openid
  128. * @param $templateId
  129. * @param array $data
  130. * @param null $url
  131. * @param null $defaultColor
  132. * @return mixed
  133. */
  134. public static function sendTemplate($openid,$templateId,array $data,$form_id,$link = null,$defaultColor = null)
  135. {
  136. $notice = self::noticeService()->to($openid)->template($templateId)->formId($form_id)->andData($data);
  137. $message = [];
  138. if($link !== null) $message = ['page'=>$link];
  139. if($defaultColor !== null) $notice->defaultColor($defaultColor);
  140. return $notice->send($message);
  141. }
  142. /**
  143. * 支付
  144. * @return \EasyWeChat\Payment\Payment
  145. */
  146. public static function paymentService()
  147. {
  148. return self::application()->payment;
  149. }
  150. /**
  151. * 生成支付订单对象
  152. * @param $openid
  153. * @param $out_trade_no
  154. * @param $total_fee
  155. * @param $attach
  156. * @param $body
  157. * @param string $detail
  158. * @param string $trade_type
  159. * @param array $options
  160. * @return Order
  161. */
  162. protected static function paymentOrder($openid,$out_trade_no,$total_fee,$attach,$body,$detail='',$trade_type='JSAPI',$options = [])
  163. {
  164. $total_fee = bcmul($total_fee,100,0);
  165. $order = array_merge(compact('openid','out_trade_no','total_fee','attach','body','detail','trade_type'),$options);
  166. if($order['detail'] == '') unset($order['detail']);
  167. return new Order($order);
  168. }
  169. /**
  170. * 获得下单ID
  171. * @param $openid
  172. * @param $out_trade_no
  173. * @param $total_fee
  174. * @param $attach
  175. * @param $body
  176. * @param string $detail
  177. * @param string $trade_type
  178. * @param array $options
  179. * @return mixed
  180. */
  181. public static function paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail='', $trade_type='JSAPI', $options = [])
  182. {
  183. $order = self::paymentOrder($openid,$out_trade_no,$total_fee,$attach,$body,$detail,$trade_type,$options);
  184. $result = self::paymentService()->prepare($order);
  185. if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
  186. try{
  187. PaymentRepositories::wechatPaymentPrepareProgram($order, $result->prepay_id);
  188. }catch (\Exception $e){}
  189. return $result->prepay_id;
  190. }else{
  191. if($result->return_code == 'FAIL'){
  192. exception('微信支付错误返回:'.$result->return_msg);
  193. }else if(isset($result->err_code)){
  194. exception('微信支付错误返回:'.$result->err_code_des);
  195. }else{
  196. exception('没有获取微信支付的预支付ID,请重新发起支付!');
  197. }
  198. exit;
  199. }
  200. }
  201. /**
  202. * 获得jsSdk支付参数
  203. * @param $openid
  204. * @param $out_trade_no
  205. * @param $total_fee
  206. * @param $attach
  207. * @param $body
  208. * @param string $detail
  209. * @param string $trade_type
  210. * @param array $options
  211. * @return array|string
  212. */
  213. public static function jsPay($openid, $out_trade_no, $total_fee, $attach, $body, $detail='', $trade_type='JSAPI', $options = [])
  214. {
  215. return self::paymentService()->configForJSSDKPayment(self::paymentPrepare($openid,$out_trade_no,$total_fee,$attach,$body,$detail,$trade_type,$options));
  216. }
  217. /**
  218. * 使用商户订单号退款
  219. * @param $orderNo
  220. * @param $refundNo
  221. * @param $totalFee
  222. * @param null $refundFee
  223. * @param null $opUserId
  224. * @param string $refundReason
  225. * @param string $type
  226. * @param string $refundAccount
  227. */
  228. public static function refund($orderNo, $refundNo, $totalFee, $refundFee = null, $opUserId = null, $refundReason = '' , $type = 'out_trade_no', $refundAccount = 'REFUND_SOURCE_UNSETTLED_FUNDS')
  229. {
  230. $totalFee = floatval($totalFee);
  231. $refundFee = floatval($refundFee);
  232. return self::paymentService()->refund($orderNo,$refundNo,$totalFee,$refundFee,$opUserId,$type,$refundAccount,$refundReason);
  233. }
  234. /** 根据订单号退款
  235. * @param $orderNo
  236. * @param array $opt
  237. * @return bool
  238. */
  239. public static function payOrderRefund($orderNo, array $opt)
  240. {
  241. if(!isset($opt['pay_price'])) exception('缺少pay_price');
  242. $totalFee = floatval(bcmul($opt['pay_price'],100,0));
  243. $refundFee = isset($opt['refund_price']) ? floatval(bcmul($opt['refund_price'],100,0)) : null;
  244. $refundReason = isset($opt['desc']) ? $opt['desc'] : '';
  245. $refundNo = isset($opt['refund_id']) ? $opt['refund_id'] : $orderNo;
  246. $opUserId = isset($opt['op_user_id']) ? $opt['op_user_id'] : null;
  247. $type = isset($opt['type']) ? $opt['type'] : 'out_trade_no';
  248. /*仅针对老资金流商户使用
  249. REFUND_SOURCE_UNSETTLED_FUNDS---未结算资金退款(默认使用未结算资金退款)
  250. REFUND_SOURCE_RECHARGE_FUNDS---可用余额退款*/
  251. $refundAccount = isset($opt['refund_account']) ? $opt['refund_account'] : 'REFUND_SOURCE_UNSETTLED_FUNDS';
  252. try{
  253. $res = (self::refund($orderNo,$refundNo,$totalFee,$refundFee,$opUserId,$refundReason,$type,$refundAccount));
  254. if($res->return_code == 'FAIL') exception('退款失败:'.$res->return_msg);
  255. if(isset($res->err_code)) exception('退款失败:'.$res->err_code_des);
  256. }catch (\Exception $e){
  257. exception($e->getMessage());
  258. }
  259. return true;
  260. }
  261. /**
  262. * 微信支付成功回调接口
  263. */
  264. public static function handleNotify()
  265. {
  266. self::paymentService()->handleNotify(function($notify, $successful){
  267. if($successful && isset($notify->out_trade_no)){
  268. if(isset($notify->attach) && $notify->attach){
  269. if(strtolower($notify->attach) == 'productr'){//TODO 商品订单支付成功后
  270. try{
  271. if(StoreOrderRoutineModel::be(['order_id'=>$notify->out_trade_no,'paid'=>1])) return true;
  272. return StoreOrderRoutineModel::paySuccess($notify->out_trade_no);
  273. }catch (\Exception $e){
  274. return false;
  275. }
  276. }else if(strtolower($notify->attach) == 'user_recharge'){
  277. try{
  278. if(UserRecharge::be(['order_id'=>$notify->out_trade_no,'paid'=>1])) return true;
  279. return UserRecharge::rechargeSuccess($notify->out_trade_no);
  280. }catch (\Exception $e){
  281. return false;
  282. }
  283. }
  284. }
  285. return false;
  286. }
  287. });
  288. }
  289. /**
  290. * 作为客服消息发送
  291. * @param $to
  292. * @param $message
  293. * @return bool
  294. */
  295. public static function staffTo($to, $message)
  296. {
  297. $staff = self::staffService();
  298. $staff = is_callable($message) ? $staff->message($message()) : $staff->message($message);
  299. $res = $staff->to($to)->send();
  300. HookService::afterListen('wechat_staff_to',compact('to','message'),$res);
  301. return $res;
  302. }
  303. }