MiniProgramService.php 10 KB

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