Wechat.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. <?php namespace Pay\Lib;
  2. use Dever;
  3. Dever::apply('sdk/wechat', 'pay');
  4. class Wechat extends Core
  5. {
  6. public function __construct($config)
  7. {
  8. $project = Dever::project('pay');
  9. $this->channel_id = $config['channel_id'];
  10. $this->system_source = $config['system_source'];
  11. $this->config = new \WxPayConfig();
  12. # 通知接口
  13. $config['notify'] = $this->url($config['type'], $config['id']);
  14. # 证书
  15. $config['ssl'] = array
  16. (
  17. 'cert' => Dever::local($config['file_cert']),
  18. 'key' => Dever::local($config['file_key']),
  19. );
  20. $config['ip'] = (isset($config['ip']) && $config['ip']) ? $config['ip'] : Dever::ip();
  21. $this->config->set($config['appid'], $config['appsecret'], $config['mchid'], $config['notify'], $config['key'], $config['ssl'], $config['type'], $config['timeout'], $config['ip']);
  22. }
  23. /**
  24. * 通知
  25. */
  26. public function notify()
  27. {
  28. $this->log('支付回调-初始化', file_get_contents("php://input"));
  29. $callback = new Callback();
  30. $result = $callback->Handle($this->config, false);
  31. }
  32. # 查询订单
  33. public function search($order_id)
  34. {
  35. $info = Dever::db('pay/order')->one(array('order_id' => $order_id, 'status' => 2));
  36. if ($info) {
  37. $this->updateOrder($info['order_id'], 1);
  38. return $info;
  39. } else {
  40. $input = new \WxPayOrderQuery();
  41. $input->SetOut_trade_no($order_id);
  42. $result = \WxPayApi::orderQuery($this->config, $input);
  43. if (isset($result['transaction_id']) && isset($result['out_trade_no']) && isset($result['trade_state_desc'])) {
  44. $this->updateOrder($result['out_trade_no'], $result['cash_fee']);
  45. }
  46. return $result;
  47. }
  48. }
  49. # 退款
  50. public function refund($order_id, $cash, $order, $refund_order_id = false)
  51. {
  52. $out_trade_no = $order_id;
  53. $cash = $cash * 100;
  54. $total_fee = $cash;
  55. $refund_fee = $cash;
  56. $input = new \WxPayRefund();
  57. $input->SetOut_trade_no($out_trade_no);
  58. $input->SetTotal_fee($total_fee);
  59. $input->SetRefund_fee($refund_fee);
  60. $input->SetOut_refund_no($out_trade_no . '_' . time());
  61. $input->SetOp_user_id($this->config->GetMerchantId());
  62. $result = \WxPayApi::refund($this->config, $input);
  63. return $result;
  64. }
  65. /**
  66. * 获取统一下单的基本信息
  67. */
  68. public function order($account_id, $project_id, $uid, $username, $product_id, $name, $cash, $openid = false, $type = 1, $order_id = false, $other = false)
  69. {
  70. $trade_type = $this->getType($type);
  71. $order_id = $this->createOrder($uid, $username, $account_id, $project_id, $product_id, $name, $cash, $this->config->GetType(), $order_id);
  72. $tools = new \JsApiPay($this->config);
  73. $input = new \WxPayUnifiedOrder();
  74. $input->SetBody($name);
  75. $input->SetAttach($name);
  76. $input->SetOut_trade_no($order_id);
  77. $input->SetTotal_fee($cash * 100);
  78. $input->SetTime_start(date("YmdHis"));
  79. $input->SetTime_expire(date("YmdHis", time() + $this->config->GetTimeOut()));
  80. //$input->SetGoods_tag($name);
  81. $input->SetNotify_url($this->config->GetNotifyUrl());
  82. $input->SetTrade_type($trade_type);
  83. $input->SetProduct_id($product_id);
  84. if ($type == 1 && $openid != -1) {
  85. if (!$openid && Dever::project('passport')) {
  86. $where = array();
  87. $where['uid'] = $uid;
  88. $where['system_source'] = $this->system_source;
  89. $where['system_id'] = $this->channel_id;
  90. $wechat = Dever::db('passport/wechat')->one($where);
  91. if ($wechat) {
  92. $openid = $wechat['openid'];
  93. }
  94. }
  95. $openid = $openid ? $openid : $tools->GetOpenid();
  96. $input->SetOpenid($openid);
  97. }
  98. if ($type == 2) {
  99. # 下单信息
  100. $this->updateOrderParam($order_id, $input);
  101. return $input;
  102. } else {
  103. $order = \WxPayApi::unifiedOrder($this->config, $input);
  104. # 下单信息
  105. $order['time'] = '' . time() . '';
  106. $order['order_id'] = $order_id;
  107. $order['sign_type'] = $this->config->GetSignType();
  108. unset($order['mch_id']);
  109. $this->updateOrderParam($order_id, $order);
  110. return $order;
  111. }
  112. }
  113. /**
  114. * 获取二维码支付
  115. */
  116. public function qrcode($order, $refer)
  117. {
  118. $notify = new \NativePay($this->config);
  119. $result = $notify->GetPayUrl($order);
  120. if (isset($result['code_url'])) {
  121. $url = $result['code_url'];
  122. return $url;
  123. }
  124. return '';
  125. }
  126. /**
  127. * 获取小程序支付
  128. */
  129. public function applet($order)
  130. {
  131. if (isset($order['prepay_id'])) {
  132. $string = 'appId='.$this->config->GetAppId().'&nonceStr='.$order['nonce_str'].'&package=prepay_id='.$order['prepay_id'].'&signType='.$order['sign_type'].'&timeStamp='.$order['time'].'&key='.$this->config->GetKey();
  133. $this->log('支付签名-applet', $string);
  134. if($order['sign_type'] == "MD5"){
  135. $string = md5($string);
  136. } else {
  137. $string = hash_hmac("sha256", $string, $this->config->GetKey());
  138. }
  139. $order['sign'] = $string;
  140. }
  141. return $order;
  142. }
  143. /**
  144. * 获取app支付
  145. */
  146. public function app($order)
  147. {
  148. if (isset($order['prepay_id'])) {
  149. $order['partnerid'] = $this->config->GetMerchantId();
  150. $order['package_string'] = 'Sign=WXPay';
  151. $string = array();
  152. $string['appid'] = $this->config->GetAppId();
  153. $string['partnerid'] = $order['partnerid'];
  154. $string['prepayid'] = $order['prepay_id'];
  155. $string['package'] = $order['package_string'];
  156. $string['noncestr'] = $order['nonce_str'];
  157. $string['timestamp'] = $order['time'];
  158. ksort($string);
  159. $string = str_replace('%3D', '=', http_build_query($string));
  160. $string .= '&key=' . $this->config->GetKey();
  161. $this->log('支付签名-app', $string);
  162. if($order['sign_type'] == "MD5"){
  163. $string = md5($string);
  164. } else {
  165. $string = hash_hmac("sha256", $string, $this->config->GetKey());
  166. }
  167. $order['sign'] = $string;
  168. }
  169. return $order;
  170. }
  171. /**
  172. * 获取页面支付
  173. */
  174. public function page($order, $refer)
  175. {
  176. if (isset($order['mweb_url'])) {
  177. $url = $order['mweb_url'] . '&redirect_url=' . $refer;
  178. if (!$url) {
  179. $location = 'window.open("' . $url . '")';
  180. } else {
  181. $location = 'location.href="' . $url . '"';
  182. }
  183. return '<script type="text/javascript">'.$location.'</script>';
  184. }
  185. $refer = urldecode($refer);
  186. if (strstr($refer, 'callback.')) {
  187. $callback = str_replace('callback.', '', $refer);
  188. $callback = $callback . '()';
  189. } else {
  190. $callback = 'location.href = "'.$refer.'";';
  191. }
  192. $tools = new \JsApiPay($this->config);
  193. $info = $tools->GetJsApiParameters($order);
  194. if ($refer == 'param') {
  195. return json_decode($info, true);
  196. }
  197. $html = '<script type="text/javascript">
  198. function jsApiCall()
  199. {
  200. WeixinJSBridge.invoke(
  201. "getBrandWCPayRequest",
  202. '.$info.',
  203. function(res){
  204. //WeixinJSBridge.log(res.err_msg);
  205. if(res.err_msg == "get_brand_wcpay_request:ok")
  206. {
  207. '.$callback.'
  208. } else {
  209. alert("支付失败");
  210. //alert(res.err_code+res.err_desc+res.err_msg);
  211. }
  212. }
  213. );
  214. }
  215. function callpay()
  216. {
  217. if (typeof WeixinJSBridge == "undefined"){
  218. if( document.addEventListener ){
  219. document.addEventListener("WeixinJSBridgeReady", jsApiCall, false);
  220. }else if (document.attachEvent){
  221. document.attachEvent("WeixinJSBridgeReady", jsApiCall);
  222. document.attachEvent("onWeixinJSBridgeReady", jsApiCall);
  223. }
  224. }else{
  225. jsApiCall();
  226. }
  227. }
  228. callpay();
  229. </script>';
  230. return $html;
  231. }
  232. private function getType($type)
  233. {
  234. switch ($type) {
  235. case 1:
  236. $type = 'JSAPI';
  237. break;
  238. case 2:
  239. $type = 'NATIVE';
  240. break;
  241. case 3:
  242. $type = 'APP';
  243. break;
  244. case 4:
  245. $type = 'MWEB';
  246. break;
  247. }
  248. return $type;
  249. }
  250. }
  251. class Callback extends \WxPayNotify
  252. {
  253. public function NotifyProcess($objData, $config, &$msg)
  254. {
  255. $data = $objData->GetValues();
  256. $obj = Dever::load('pay/lib/core');
  257. $obj->log('支付回调-获取数据', $data);
  258. $callback = function($msg = '') use ($obj, $data) {
  259. if ($msg) {
  260. $msg = $data['transaction_id'] . ':' . $msg;
  261. }
  262. $obj->updateOrder($data['out_trade_no'], $data['cash_fee'], $msg);
  263. };
  264. if(!array_key_exists("transaction_id", $data)){
  265. $msg = '输入参数不正确';
  266. $callback($msg);
  267. return false;
  268. }
  269. # 参数校验
  270. if(!array_key_exists("return_code", $data)
  271. ||(array_key_exists("return_code", $data) && $data['return_code'] != "SUCCESS")) {
  272. $msg = $data['return_code'] . '(异常)';
  273. $callback($msg);
  274. return false;
  275. }
  276. # 进行签名验证
  277. try {
  278. $checkResult = $objData->CheckSign($config);
  279. if($checkResult == false){
  280. $msg = '签名错误';
  281. $callback($msg);
  282. return false;
  283. }
  284. } catch(Exception $e) {
  285. $msg = '签名异常';
  286. $callback($msg);
  287. return false;
  288. }
  289. # 查询订单,判断订单真实性
  290. /*
  291. if(!$this->Queryorder($data["transaction_id"])){
  292. $msg = '订单查询失败';
  293. $callback($msg);
  294. return false;
  295. }
  296. */
  297. # 处理业务逻辑
  298. $callback();
  299. return true;
  300. }
  301. }