WxpayServiceNotify.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace service;
  3. /**
  4. * 微信扫码支付回调
  5. * Class WxpayServiceNotify
  6. * @package service
  7. *
  8. * 调用实例
  9. *
  10. * $mchid = SystemConfig::getValue('pay_weixin_mchid'); //微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送
  11. $appid = SystemConfig::getValue('pay_weixin_appid'); //公众号APPID 通过微信支付商户资料审核后邮件发送
  12. $apiKey = SystemConfig::getValue('pay_weixin_key'); //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥
  13. $wxPay = new WxpayServiceNotify($mchid,$appid,$apiKey);
  14. $result = $wxPay->notify();
  15. if($result){
  16. $data['is_pay'] = 1;
  17. $data['pay_time'] = time();
  18. $res = ThemeEnlistModel::edit($data,$result['out_trade_no'],'order_id');
  19. if($res)
  20. echo 'success';
  21. //完成你的逻辑
  22. //例如连接数据库,获取付款金额$result['cash_fee'],获取订单号$result['out_trade_no'],修改数据库中的订单状态等;
  23. }else{
  24. echo 'pay error';
  25. }
  26. */
  27. class WxpayServiceNotify
  28. {
  29. protected $mchid;
  30. protected $appid;
  31. protected $apiKey;
  32. public function __construct($mchid, $appid, $key)
  33. {
  34. $this->mchid = $mchid;
  35. $this->appid = $appid;
  36. $this->apiKey = $key;
  37. }
  38. public function notify()
  39. {
  40. $config = array(
  41. 'mch_id' => $this->mchid,
  42. 'appid' => $this->appid,
  43. 'key' => $this->apiKey,
  44. );
  45. $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
  46. $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  47. if ($postObj === false) {
  48. die('parse xml error');
  49. }
  50. if ($postObj->return_code != 'SUCCESS') {
  51. die($postObj->return_msg);
  52. }
  53. if ($postObj->result_code != 'SUCCESS') {
  54. die($postObj->err_code);
  55. }
  56. $arr = (array)$postObj;
  57. unset($arr['sign']);
  58. if (self::getSign($arr, $config['key']) == $postObj->sign) {
  59. echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
  60. return $arr;
  61. }
  62. }
  63. /**
  64. * 获取签名
  65. */
  66. public static function getSign($params, $key)
  67. {
  68. ksort($params, SORT_STRING);
  69. $unSignParaString = self::formatQueryParaMap($params, false);
  70. $signStr = strtoupper(md5($unSignParaString . "&key=" . $key));
  71. return $signStr;
  72. }
  73. protected static function formatQueryParaMap($paraMap, $urlEncode = false)
  74. {
  75. $buff = "";
  76. ksort($paraMap);
  77. foreach ($paraMap as $k => $v) {
  78. if (null != $v && "null" != $v) {
  79. if ($urlEncode) {
  80. $v = urlencode($v);
  81. }
  82. $buff .= $k . "=" . $v . "&";
  83. }
  84. }
  85. $reqPar = '';
  86. if (strlen($buff) > 0) {
  87. $reqPar = substr($buff, 0, strlen($buff) - 1);
  88. }
  89. return $reqPar;
  90. }
  91. }