MiniProgramService.php 10 KB

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