伤处多余文件

This commit is contained in:
liaofei 2019-05-16 14:31:56 +08:00
parent e41e19571f
commit dafac2cbb2
12 changed files with 0 additions and 1698 deletions

View File

@ -1,24 +0,0 @@
<?php
/**
*
* @author: xaboy<365615158@qq.com>
* @day: 2018/01/15
*/
namespace service;
use app\admin\model\system\SystemGroupData;
class GroupDataService
{
public static function getGroupData($config_name,$limit = 0)
{
return SystemGroupData::getGroupData($config_name,$limit);
}
public static function getData($config_name,$limit = 0)
{
return SystemGroupData::getAllValue($config_name,$limit);
}
}

View File

@ -1,36 +0,0 @@
<?php
/**
*
* @author: xaboy<365615158@qq.com>
* @day: 2017/10/24
*/
namespace service;
use app\admin\model\wechat\WechatQrcode as QrcodeModel;
class QrcodeService
{
/**
* 获取临时二维码 单个
* */
public static function getTemporaryQrcode($type,$id){
return QrcodeModel::getTemporaryQrcode($type,$id)->toArray();
}/**
* 获取永久二维码 单个
* */
public static function getForeverQrcode($type,$id){
return QrcodeModel::getForeverQrcode($type,$id)->toArray();
}
public static function getQrcode($id,$type = 'id')
{
return QrcodeModel::getQrcode($id,$type);
}
public static function scanQrcode($id,$type = 'id')
{
return QrcodeModel::scanQrcode($id,$type);
}
}

View File

@ -1,57 +0,0 @@
<?php
/**
*
* @author: xaboy<365615158@qq.com>
* @day: 2017/12/07
*/
class ResultService
{
const SUCCESSFUL_CODE = 200;
const FAILED_CODE = 400;
protected static function getStd()
{
return new \StdClass();
}
/**
* 成功结果
* @param string $msg
* @param array $data
* @param string $defaultMsg
* @return StdClass
*/
public static function successful($msg = 'ok', $data = [], $defaultMsg = 'ok')
{
if(is_array($msg)){
$data = $msg;
$msg = $defaultMsg;
}
if(is_callable($data)) $data = $data();
$result = self::getStd();
$result->code = self::SUCCESSFUL_CODE;
$result->meg = $msg;
$result->data = $data;
return $result;
}
/**
* 失败结果
* @param $msg
* @param array $data
* @return StdClass
*/
public static function failed($msg, $data = [])
{
$result = self::getStd();
if(is_callable($data)) $data = $data();
$result->code = self::FAILED_CODE;
$result->meg = $msg;
$result->data = $data;
return $result;
}
}

View File

@ -1,58 +0,0 @@
<?php
namespace service;
/**
* 小程序支付异步通知
* Class RoutineNotify
* @package service
*/
class RoutineNotify
{
public static function options(){
$payment = SystemConfigService::more(['routine_appId','routine_appsecret','pay_routine_mchid','pay_routine_key']);
return $payment;
}
public static function notify()
{
$config = self::options();
$postStr = file_get_contents('php://input');
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
if ($postObj === false) die('parse xml error');
if ($postObj->return_code != 'SUCCESS') die($postObj->return_msg);
if ($postObj->result_code != 'SUCCESS') die($postObj->err_code);
$arr = (array)$postObj;
unset($arr['sign']);
if (self::getSign($arr, $config['pay_routine_key']) == $postObj->sign) {
echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
return $arr;
}
}
/**
* 获取签名
*/
public static function getSign($params, $key)
{
ksort($params, SORT_STRING);
$unSignParaString = self::formatQueryParaMap($params, false);
$signStr = strtoupper(md5($unSignParaString . "&key=" . $key));
return $signStr;
}
protected static function formatQueryParaMap($paraMap, $urlEncode = false)
{
$buff = "";
ksort($paraMap);
foreach ($paraMap as $k => $v) {
if (null != $v && "null" != $v) {
if ($urlEncode) {
$v = urlencode($v);
}
$buff .= $k . "=" . $v . "&";
}
}
$reqPar = '';
if (strlen($buff) > 0) {
$reqPar = substr($buff, 0, strlen($buff) - 1);
}
return $reqPar;
}
}

View File

@ -1,158 +0,0 @@
<?php
namespace service;
/**
* 小程序退款
* Class RoutineRefund
* @package service
*/
class RoutineRefund
{
public static function options(){
$config = SystemConfigService::more(['pay_routine_appid','pay_routine_appsecret','pay_routine_mchid','pay_routine_key','pay_routine_client_cert','pay_routine_client_key']);
return $config;
}
/**
* 退款
* @param float $totalFee 订单金额 单位元
* @param float $refundFee 退款金额 单位元
* @param string $refundNo 退款单号
* @param string $wxOrderNo 微信订单号
* @param string $orderNo 商户订单号
* @param string $refundDesc 退款原因
* @return string
*/
public static function doRefund($totalFee, $refundFee, $refundNo, $wxOrderNo='',$orderNo='',$refundDesc = '')
{
$config = array(
'mch_id' => self::options()['pay_routine_mchid'],
'appid' => self::options()['pay_routine_appid'],
'key' => self::options()['pay_routine_key'],
);
$unified = array(
'appid' => $config['appid'],
'mch_id' => $config['mch_id'],
'nonce_str' => self::createNonceStr(),
'total_fee' => intval($totalFee * 100), //订单金额 单位 转为分
'refund_fee' => intval($refundFee * 100), //退款金额 单位 转为分
'sign_type' => 'MD5', //签名类型 支持HMAC-SHA256和MD5默认为MD5
'transaction_id'=>$wxOrderNo, //微信订单号
'out_trade_no'=>$orderNo, //商户订单号
'out_refund_no'=>$refundNo, //商户退款单号
'refund_desc'=>$refundDesc, //退款原因(选填)
);
$unified['sign'] = self::getSign($unified, $config['key']);
$responseXml = self::curlPost('https://api.mch.weixin.qq.com/secapi/pay/refund', self::arrayToXml($unified));
$unifiedOrder = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
if ($unifiedOrder === false) {
die('parse xml error');
}
if ($unifiedOrder->return_code != 'SUCCESS') {
die($unifiedOrder->return_msg);
}
if ($unifiedOrder->result_code != 'SUCCESS') {
die($unifiedOrder->err_code);
}
return true;
}
public static function curlGet($url = '', $options = array())
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
if (!empty($options)) {
curl_setopt_array($ch, $options);
}
//https请求 不验证证书和host
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
public static function curlPost($url = '', $postData = '', $options = array())
{
if (is_array($postData)) {
$postData = http_build_query($postData);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
if (!empty($options)) {
curl_setopt_array($ch, $options);
}
//https请求 不验证证书和host
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//第一种方法cert 与 key 分别属于两个.pem文件
//默认格式为PEM可以注释
curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
// curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/cert/apiclient_cert.pem');
curl_setopt($ch,CURLOPT_SSLCERT,realpath('.'.self::options()['pay_routine_client_cert']));
//默认格式为PEM可以注释
curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
// curl_setopt($ch,CURLOPT_SSLKEY,getcwd().'/cert/apiclient_key.pem');
curl_setopt($ch,CURLOPT_SSLKEY,realpath('.'.self::options()['pay_routine_client_key']));
//第二种方式,两个文件合成一个.pem文件
// curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/all.pem');
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
public static function createNonceStr($length = 16)
{
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$str = '';
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}
public static function arrayToXml($arr)
{
$xml = "<xml>";
foreach ($arr as $key => $val) {
if (is_numeric($val)) {
$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
} else
$xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
}
$xml .= "</xml>";
return $xml;
}
public static function getSign($params, $key)
{
ksort($params, SORT_STRING);
$unSignParaString = self::formatQueryParaMap($params, false);
$signStr = strtoupper(md5($unSignParaString . "&key=" . $key));
return $signStr;
}
protected static function formatQueryParaMap($paraMap, $urlEncode = false)
{
$buff = "";
ksort($paraMap);
foreach ($paraMap as $k => $v) {
if (null != $v && "null" != $v) {
if ($urlEncode) {
$v = urlencode($v);
}
$buff .= $k . "=" . $v . "&";
}
}
$reqPar = '';
if (strlen($buff) > 0) {
$reqPar = substr($buff, 0, strlen($buff) - 1);
}
return $reqPar;
}
}
?>

View File

@ -1,170 +0,0 @@
<?php
namespace service;
use think\Url;
/**
* 小程序支付
* Created by PhpStorm.
* User: Administrator
* Date: 2018/5/29 0029
* Time: 上午 10:10
*/
class RoutineService{
public static function options(){
$payment = SystemConfigService::more(['site_url','routine_appId','routine_appsecret','pay_routine_mchid','pay_routine_client_cert','pay_routine_client_key','pay_routine_key','pay_weixin_open']);
return $payment;
}
/**
* @param $openid $openid 用户openid
* @param $fee $fee 金额
* @param $out_trade_no $out_trade_no 订单号
* @param $body $body 提示
* @return mixed
*/
public static function payRoutine($openid,$out_trade_no,$fee,$attach,$body){
$appid = self::options()['routine_appId'] ? self::options()['routine_appId'] : '';//如果是公众号 就是公众号的appid
$mch_id = self::options()['pay_routine_mchid'] ? self::options()['pay_routine_mchid'] : '';
$nonce_str = self::nonce_str();//随机字符串
$spbill_create_ip = self::get_server_ip();
$total_fee = $fee*100;//因为充值金额最小是1 而且单位为分 如果是充值1元所以这里需要*100
$trade_type = 'JSAPI';//交易类型 默认
$notify_url = SystemConfigService::get('site_url').Url::build('routine/Routine/notify');
$post['appid'] = $appid;
$post['attach'] = $attach;
$post['body'] = $body;
$post['mch_id'] = $mch_id;
$post['nonce_str'] = $nonce_str;//随机字符串
$post['notify_url'] = $notify_url;
$post['openid'] = $openid;
$post['out_trade_no'] = $out_trade_no;
$post['spbill_create_ip'] = $spbill_create_ip;//终端的ip
$post['total_fee'] = $total_fee;//总金额
$post['trade_type'] = $trade_type;
$sign = self::sign($post);//签名
$post_xml = '<xml>
<appid>'.$appid.'</appid>
<attach>'.$attach.'</attach>
<body>'.$body.'</body>
<mch_id>'.$mch_id.'</mch_id>
<nonce_str>'.$nonce_str.'</nonce_str>
<notify_url>'.$notify_url.'</notify_url>
<openid>'.$openid.'</openid>
<out_trade_no>'.$out_trade_no.'</out_trade_no>
<spbill_create_ip>'.$spbill_create_ip.'</spbill_create_ip>
<total_fee>'.$total_fee.'</total_fee>
<trade_type>'.$trade_type.'</trade_type>
<sign>'.$sign.'</sign>
</xml> ';
// dump($post_xml);
//统一接口prepay_id
$url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
$xml = self::http_request($url,$post_xml);
$array = self::xml($xml);//全要大写
if($array['RETURN_CODE'] == 'SUCCESS' && $array['RESULT_CODE'] == 'SUCCESS'){
$time = time();
$tmp='';//临时数组用于签名
$tmp['appId'] = $appid;
$tmp['nonceStr'] = $nonce_str;
$tmp['package'] = 'prepay_id='.$array['PREPAY_ID'];
$tmp['signType'] = 'MD5';
$tmp['timeStamp'] = "$time";
$data['state'] = 1;
$data['timeStamp'] = "$time";//时间戳
$data['nonceStr'] = $nonce_str;//随机字符串
$data['signType'] = 'MD5';//签名算法,暂支持 MD5
$data['package'] = 'prepay_id='.$array['PREPAY_ID'];//统一下单接口返回的 prepay_id 参数值提交格式如prepay_id=*
$data['paySign'] = self::sign($tmp);//签名,具体签名方案参见微信公众号支付帮助文档;
$data['out_trade_no'] = $out_trade_no;
}else{
$data['state'] = 0;
$data['text'] = "错误";
$data['RETURN_CODE'] = $array['RETURN_CODE'];
$data['RETURN_MSG'] = $array['RETURN_MSG'];
}
return $data;
}
//随机32位字符串
public static function nonce_str(){
$result = '';
$str = 'QWERTYUIOPASDFGHJKLZXVBNMqwertyuioplkjhgfdsamnbvcxz';
for ($i=0;$i<32;$i++){
$result .= $str[rand(0,48)];
}
return $result;
}
public static function order_number($openid){
return md5($openid.time().rand(10,99));//32位
}
//签名 $data要先排好顺序
public static function sign($data){
$stringA = '';
foreach ($data as $key=>$value){
if(!$value) continue;
if($stringA) $stringA .= '&'.$key."=".$value;
else $stringA = $key."=".$value;
}
$wx_key = self::options()['pay_routine_key'] ? self::options()['pay_routine_key'] : '';//申请支付后有给予一个商户账号和密码登陆后自己设置key
$stringSignTemp = $stringA.'&key='.$wx_key;//申请支付后有给予一个商户账号和密码登陆后自己设置key
// dump($stringSignTemp);
return strtoupper(md5($stringSignTemp));
}
//curl请求
public static function http_request($url,$data = null,$headers=array())
{
$curl = curl_init();
if( count($headers) >= 1 ){
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
}
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
//获取xml
public static function xml($xml){
$p = xml_parser_create();
xml_parse_into_struct($p, $xml, $vals, $index);
xml_parser_free($p);
$data = "";
foreach ($index as $key=>$value) {
if($key == 'xml' || $key == 'XML') continue;
$tag = $vals[$value[0]]['tag'];
$value = $vals[$value[0]]['value'];
$data[$tag] = $value;
}
return $data;
}
public static function get_server_ip() {
if (isset($_SERVER)) {
if($_SERVER['SERVER_ADDR']) {
$server_ip = $_SERVER['SERVER_ADDR'];
}
else {
$server_ip = $_SERVER['LOCAL_ADDR'];
}
}
else {
$server_ip = getenv('SERVER_ADDR');
}
return $server_ip;
}
}

View File

@ -1,118 +0,0 @@
<?php
namespace service;
use app\routine\model\routine\RoutineServer;
use think\Db;
/**
* 小程序模板消息
* Class RoutineTemplate
* @package app\routine\model\routine
*/
class RoutineTemplateService{
//订单支付成功
const ORDER_PAY_SUCCESS = 'AT0009';
//砍价成功
const BARGAIN_SUCCESS = 'AT1173';
//申请退款通知
const ORDER_REFUND_STATUS = 'AT0036';
//退款成功
const ORDER_REFUND_SUCCESS = 'AT0787';
//订单发货提醒(快递)
const ORDER_POSTAGE_SUCCESS = 'AT0007';
//订单发货提醒(送货)
const ORDER_DELIVER_SUCCESS = 'AT0177';
/**
* 根据模板编号获取模板ID
* @param string $tempKey
* @return mixed|string
*/
public static function setTemplateId($tempKey = ''){
if($tempKey == '')return '';
return Db::name('RoutineTemplate')->where('tempkey',$tempKey)->where('status',1)->value('tempid');
}
/**
* 获取小程序模板库所有标题列表
* @param string $accessToken
* @param int $offset
* @param int $count
* @return mixed
*/
public static function getTemplateListAll($offset = 0,$count = 20){
$accessToken = RoutineServer::get_access_token();
$url = "https://api.weixin.qq.com/cgi-bin/wxopen/template/library/list?access_token=".$accessToken;
$data['access_token'] = $accessToken;
$data['offset'] = $offset;
$data['count'] = $count;
return json_decode(RoutineServer::curlPost($url,json_encode($data)),true);
}
/**
* 获取模板库某个模板标题下关键词库
* @param string $templateId 模板ID 未添加之前的ID
* @return mixed
*/
public static function getTemplateKeyword($templateId = 'AT0005'){
$accessToken = RoutineServer::get_access_token();
$url = "https://api.weixin.qq.com/cgi-bin/wxopen/template/library/get?access_token=".$accessToken;
$data['access_token'] = $accessToken;
$data['id'] = $templateId;
return json_decode(RoutineServer::curlPost($url,json_encode($data)),true);
}
/**
* 获取小程序模板库申请的标题列表
* @param int $offset
* @param int $count
* @return mixed
*/
public static function getTemplateList($offset = 0,$count = 20){
$accessToken = RoutineServer::get_access_token();
$url = "https://api.weixin.qq.com/cgi-bin/wxopen/template/list?access_token=".$accessToken;
$data['access_token'] = $accessToken;
$data['offset'] = $offset;
$data['count'] = $count;
return json_decode(RoutineServer::curlPost($url,json_encode($data)),true);
}
/**
* 删除小程序中的某个模板消息
* @param string $templateId
* @return bool|mixed
*/
public static function delTemplate($templateId = ''){
if($templateId == '') return false;
$accessToken = RoutineServer::get_access_token();
$url = "https://api.weixin.qq.com/cgi-bin/wxopen/template/del?access_token=".$accessToken;
$data['access_token'] = $accessToken;
$data['template_id'] = $templateId;
return json_decode(RoutineServer::curlPost($url,json_encode($data)),true);
}
/**
* 发送模板消息
* @param string $openId 接收者(用户)的 openid
* @param string $templateId 所需下发的模板消息的id
* @param string $link 点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,示例index?foo=bar。该字段不填则模板无跳转。
* @param string $formId 表单提交场景下,为 submit 事件带上的 formId支付场景下为本次支付的 prepay_id
* @param array $dataKey 模板内容,不填则下发空模板
* @param string $emphasisKeyword 模板需要放大的关键词,不填则默认无放大
* @return bool|mixed
*/
public static function sendTemplate($openId = '',$templateId = '',$link = '',$dataKey = array(),$formId = '',$emphasisKeyword = ''){
if($openId == '' || $templateId == '' || $formId == '') return false;
$accessToken = RoutineServer::get_access_token();
$url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=".$accessToken;
$data['touser'] = $openId;//接收者(用户)的 openid
$data['template_id'] = $templateId; //所需下发的模板消息的id
$data['page'] = $link; //点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,示例index?foo=bar。该字段不填则模板无跳转。
$data['form_id'] = $formId; // 表单提交场景下,为 submit 事件带上的 formId支付场景下为本次支付的 prepay_id
$data['data'] = $dataKey; //模板内容,不填则下发空模板
$data['emphasis_keyword'] = $emphasisKeyword; //模板需要放大的关键词,不填则默认无放大
return json_decode(RoutineServer::curlPost($url,json_encode($data)),true);
}
}

View File

@ -1,38 +0,0 @@
<?php
/**
*
* @author: xaboy<365615158@qq.com>
* @day: 2017/11/23
*/
namespace service;
use app\admin\model\system\SystemConfig;
class SystemConfigService
{
protected static $configList = null;
public static function config($key)
{
if(self::$configList === null) self::$configList = self::getAll();
return isset(self::$configList[$key]) ? self::$configList[$key] : null;
}
public static function get($key)
{
return SystemConfig::getValue($key);
}
public static function more($keys)
{
return SystemConfig::getMore($keys);
}
public static function getAll()
{
return SystemConfig::getAllConfig()?:[];
}
}

View File

@ -1,556 +0,0 @@
<?php
/**
*
* @author: xaboy<365615158@qq.com>
* @day: 2017/11/23
*/
namespace service;
use app\admin\model\wechat\WechatMessage;
use behavior\wechat\MessageBehavior;
use behavior\wechat\PaymentBehavior;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Message\Article;
use EasyWeChat\Message\Image;
use EasyWeChat\Message\Material;
use EasyWeChat\Message\News;
use EasyWeChat\Message\Text;
use EasyWeChat\Message\Video;
use EasyWeChat\Message\Voice;
use EasyWeChat\Payment\Order;
use EasyWeChat\Server\Guard;
use EasyWeChat\Support\XML;
use think\Url;
class WechatService
{
private static $instance = null;
public static function options()
{
$wechat = SystemConfigService::more(['wechat_appid','wechat_appsecret','wechat_token','wechat_encodingaeskey','wechat_encode']);
$payment = SystemConfigService::more(['pay_weixin_mchid','pay_weixin_client_cert','pay_weixin_client_key','pay_weixin_key','pay_weixin_open']);
$config = [
'app_id'=>isset($wechat['wechat_appid']) ? $wechat['wechat_appid']:'',
'secret'=>isset($wechat['wechat_appsecret']) ? $wechat['wechat_appsecret']:'',
'token'=>isset($wechat['wechat_token']) ? $wechat['wechat_token']:'',
'guzzle' => [
'timeout' => 10.0, // 超时时间(秒)
],
];
if((int)$wechat['wechat_encode']>0 && isset($wechat['wechat_encodingaeskey']) && !empty($wechat['wechat_encodingaeskey']))
$config['aes_key'] = $wechat['wechat_encodingaeskey'];
if(isset($payment['pay_weixin_open']) && $payment['pay_weixin_open'] == 1){
$config['payment'] = [
'merchant_id'=>$payment['pay_weixin_mchid'],
'key'=>$payment['pay_weixin_key'],
'cert_path'=>realpath('.'.$payment['pay_weixin_client_cert']),
'key_path'=>realpath('.'.$payment['pay_weixin_client_key']),
'notify_url'=>SystemConfigService::get('site_url').Url::build('wap/Wechat/notify')
];
}
return $config;
}
public static function application($cache = false)
{
(self::$instance === null || $cache === true) && (self::$instance = new Application(self::options()));
return self::$instance;
}
public static function serve()
{
$wechat = self::application(true);
$server = $wechat->server;
self::hook($server);
$response = $server->serve();
exit($response->getContent());
}
/**
* 监听行为
* @param Guard $server
*/
private static function hook($server)
{
$server->setMessageHandler(function($message){
$behavior = MessageBehavior::class;
HookService::beforeListen('wechat_message',$message,null,true,$behavior);
switch ($message->MsgType){
case 'event':
switch (strtolower($message->Event)){
case 'subscribe':
if(isset($message->EventKey)){
$response = HookService::resultListen('wechat_event_scan_subscribe',$message,$message->EventKey,true,$behavior);
}else{
$response = HookService::resultListen('wechat_event_subscribe',$message,null,true,$behavior);
}
break;
case 'unsubscribe':
$response = HookService::resultListen('wechat_event_unsubscribe',$message,null,true,$behavior);
break;
case 'scan':
$response = HookService::resultListen('wechat_event_scan',$message,$message->EventKey,true,$behavior);
break;
case 'location':
$response = HookService::resultListen('wechat_event_location',$message,null,true,$behavior);
break;
case 'click':
$response = HookService::resultListen('wechat_event_click',$message,null,true,$behavior);
break;
case 'view':
$response = HookService::resultListen('wechat_event_view',$message,null,true,$behavior);
break;
}
break;
case 'text':
$response = HookService::resultListen('wechat_message_text',$message,null,true,$behavior);
break;
case 'image':
$response = HookService::resultListen('wechat_message_image',$message,null,true,$behavior);
break;
case 'voice':
$response = HookService::resultListen('wechat_message_voice',$message,null,true,$behavior);
break;
case 'video':
$response = HookService::resultListen('wechat_message_video',$message,null,true,$behavior);
break;
case 'location':
$response = HookService::resultListen('wechat_message_location',$message,null,true,$behavior);
break;
case 'link':
$response = HookService::resultListen('wechat_message_link',$message,null,true,$behavior);
break;
// ... 其它消息
default:
$response = HookService::resultListen('wechat_message_other',$message,null,true,$behavior);
break;
}
return $response;
});
}
/**
* 多客服消息转发
* @param string $account
* @return \EasyWeChat\Message\Transfer
*/
public static function transfer($account = '')
{
$transfer = new \EasyWeChat\Message\Transfer();
return empty($account) ? $transfer : $transfer->to($account);
}
/**
* 上传永久素材接口
* @return \EasyWeChat\Material\Material
*/
public static function materialService()
{
return self::application()->material;
}
/**
* 上传临时素材接口
* @return \EasyWeChat\Material\Temporary
*/
public static function materialTemporaryService()
{
return self::application()->material_temporary;
}
/**
* 用户接口
* @return \EasyWeChat\User\User
*/
public static function userService()
{
return self::application()->user;
}
/**
* 客服消息接口
* @param null $to
* @param null $message
*/
public static function staffService()
{
return self::application()->staff;
}
/**
* 微信公众号菜单接口
* @return \EasyWeChat\Menu\Menu
*/
public static function menuService()
{
return self::application()->menu;
}
/**
* 微信二维码生成接口
* @return \EasyWeChat\QRCode\QRCode
*/
public static function qrcodeService()
{
return self::application()->qrcode;
}
/**
* 短链接生成接口
* @return \EasyWeChat\Url\Url
*/
public static function urlService()
{
return self::application()->url;
}
/**
* 用户授权
* @return \Overtrue\Socialite\Providers\WeChatProvider
*/
public static function oauthService()
{
return self::application()->oauth;
}
/**
* 模板消息接口
* @return \EasyWeChat\Notice\Notice
*/
public static function noticeService()
{
return self::application()->notice;
}
public static function sendTemplate($openid,$templateId,array $data,$url = null,$defaultColor = null)
{
$notice = self::noticeService()->to($openid)->template($templateId)->andData($data);
if($url !== null) $notice->url($url);
if($defaultColor !== null) $notice->defaultColor($defaultColor);
return $notice->send();
}
/**
* 支付
* @return \EasyWeChat\Payment\Payment
*/
public static function paymentService()
{
return self::application()->payment;
}
public static function downloadBill($day,$type = 'ALL')
{
// $payment = self::paymentService();
// $merchant = $payment->getMerchant();
// $params = [
// 'appid' => $merchant->app_id,
// 'bill_date'=>$day,
// 'bill_type'=>strtoupper($type),
// 'mch_id'=> $merchant->merchant_id,
// 'nonce_str' => uniqid()
// ];
// $params['sign'] = \EasyWeChat\Payment\generate_sign($params, $merchant->key, 'md5');
// $xml = XML::build($params);
// dump(self::paymentService()->downloadBill($day)->getContents());
// dump($payment->getHttp()->request('https://api.mch.weixin.qq.com/pay/downloadbill','POST',[
// 'body' => $xml,
// 'stream'=>true
// ])->getBody()->getContents());
}
public static function userTagService()
{
return self::application()->user_tag;
}
public static function userGroupService()
{
return self::application()->user_group;
}
/**
* 生成支付订单对象
* @param $openid
* @param $out_trade_no
* @param $total_fee
* @param $attach
* @param $body
* @param string $detail
* @param string $trade_type
* @param array $options
* @return Order
*/
protected static function paymentOrder($openid,$out_trade_no,$total_fee,$attach,$body,$detail='',$trade_type='JSAPI',$options = [])
{
$total_fee = bcmul($total_fee,100,0);
$order = array_merge(compact('openid','out_trade_no','total_fee','attach','body','detail','trade_type'),$options);
if($order['detail'] == '') unset($order['detail']);
return new Order($order);
}
/**
* 获得下单ID
* @param $openid
* @param $out_trade_no
* @param $total_fee
* @param $attach
* @param $body
* @param string $detail
* @param string $trade_type
* @param array $options
* @return mixed
*/
public static function paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail='', $trade_type='JSAPI', $options = [])
{
$order = self::paymentOrder($openid,$out_trade_no,$total_fee,$attach,$body,$detail,$trade_type,$options);
$result = self::paymentService()->prepare($order);
if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
try{
HookService::listen('wechat_payment_prepare',$order,$result->prepay_id,false,PaymentBehavior::class);
}catch (\Exception $e){}
return $result->prepay_id;
}else{
if($result->return_code == 'FAIL'){
exception('微信支付错误返回:'.$result->return_msg);
}else if(isset($result->err_code)){
exception('微信支付错误返回:'.$result->err_code_des);
}else{
exception('没有获取微信支付的预支付ID请重新发起支付!');
}
exit;
}
}
/**
* 获得jsSdk支付参数
* @param $openid
* @param $out_trade_no
* @param $total_fee
* @param $attach
* @param $body
* @param string $detail
* @param string $trade_type
* @param array $options
* @return array|string
*/
public static function jsPay($openid, $out_trade_no, $total_fee, $attach, $body, $detail='', $trade_type='JSAPI', $options = [])
{
return self::paymentService()->configForJSSDKPayment(self::paymentPrepare($openid,$out_trade_no,$total_fee,$attach,$body,$detail,$trade_type,$options));
}
/**
* 使用商户订单号退款
* @param $orderNo
* @param $refundNo
* @param $totalFee
* @param null $refundFee
* @param null $opUserId
* @param string $refundReason
* @param string $type
* @param string $refundAccount
*/
public static function refund($orderNo, $refundNo, $totalFee, $refundFee = null, $opUserId = null, $refundReason = '' , $type = 'out_trade_no', $refundAccount = 'REFUND_SOURCE_UNSETTLED_FUNDS')
{
$totalFee = floatval($totalFee);
$refundFee = floatval($refundFee);
return self::paymentService()->refund($orderNo,$refundNo,$totalFee,$refundFee,$opUserId,$type,$refundAccount,$refundReason);
}
public static function payOrderRefund($orderNo, array $opt)
{
if(!isset($opt['pay_price'])) exception('缺少pay_price');
$totalFee = floatval(bcmul($opt['pay_price'],100,0));
$refundFee = isset($opt['refund_price']) ? floatval(bcmul($opt['refund_price'],100,0)) : null;
$refundReason = isset($opt['desc']) ? $opt['desc'] : '';
$refundNo = isset($opt['refund_id']) ? $opt['refund_id'] : $orderNo;
$opUserId = isset($opt['op_user_id']) ? $opt['op_user_id'] : null;
$type = isset($opt['type']) ? $opt['type'] : 'out_trade_no';
/*仅针对老资金流商户使用
REFUND_SOURCE_UNSETTLED_FUNDS---未结算资金退款(默认使用未结算资金退款)
REFUND_SOURCE_RECHARGE_FUNDS---可用余额退款*/
$refundAccount = isset($opt['refund_account']) ? $opt['refund_account'] : 'REFUND_SOURCE_UNSETTLED_FUNDS';
try{
$res = (self::refund($orderNo,$refundNo,$totalFee,$refundFee,$opUserId,$refundReason,$type,$refundAccount));
if($res->return_code == 'FAIL') exception('退款失败:'.$res->return_msg);
if(isset($res->err_code)) exception('退款失败:'.$res->err_code_des);
}catch (\Exception $e){
exception($e->getMessage());
}
return true;
}
/**
* 微信支付成功回调接口
*/
public static function handleNotify()
{
self::paymentService()->handleNotify(function($notify, $successful){
if($successful && isset($notify->out_trade_no)){
WechatMessage::setOnceMessage($notify,$notify->openid,'payment_success',$notify->out_trade_no);
return HookService::listen('wechat_pay_success',$notify,null,true,PaymentBehavior::class);
}
});
}
/**
* jsSdk
* @return \EasyWeChat\Js\Js
*/
public static function jsService()
{
return self::application()->js;
}
public static function jsSdk($url = '')
{
$apiList = ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone', 'startRecord', 'stopRecord', 'onVoiceRecordEnd', 'playVoice', 'pauseVoice', 'stopVoice', 'onVoicePlayEnd', 'uploadVoice', 'downloadVoice', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'translateVoice', 'getNetworkType', 'openLocation', 'getLocation', 'hideOptionMenu', 'showOptionMenu', 'hideMenuItems', 'showMenuItems', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem', 'closeWindow', 'scanQRCode', 'chooseWXPay', 'openProductSpecificView', 'addCard', 'chooseCard', 'openCard'];
$jsService = self::jsService();
if($url) $jsService->setUrl($url);
try{
return $jsService->config($apiList);
}catch (\Exception $e){
return '{}';
}
}
/**
* 回复文本消息
* @param string $content 文本内容
* @return Text
*/
public static function textMessage($content)
{
return new Text(compact('content'));
}
/**
* 回复图片消息
* @param string $media_id 媒体资源 ID
* @return Image
*/
public static function imageMessage($media_id)
{
return new Image(compact('media_id'));
}
/**
* 回复视频消息
* @param string $media_id 媒体资源 ID
* @param string $title 标题
* @param string $description 描述
* @param null $thumb_media_id 封面资源 ID
* @return Video
*/
public static function videoMessage($media_id, $title = '', $description = '...', $thumb_media_id = null)
{
return new Video(compact('media_id','title','description','thumb_media_id'));
}
/**
* 回复声音消息
* @param string $media_id 媒体资源 ID
* @return Voice
*/
public static function voiceMessage($media_id)
{
return new Voice(compact('media_id'));
}
/**
* 回复图文消息
* @param string|array $title 标题
* @param string $description 描述
* @param string $url URL
* @param string $image 图片链接
*/
public static function newsMessage($title, $description = '...', $url = '', $image = '')
{
if(is_array($title)){
if(isset($title[0]) && is_array($title[0])){
$newsList = [];
foreach ($title as $news){
$newsList[] = self::newsMessage($news);
}
return $newsList;
}else{
$data = $title;
}
}else{
$data = compact('title','description','url','image');
}
return new News($data);
}
/**
* 回复文章消息
* @param string|array $title 标题
* @param string $thumb_media_id 图文消息的封面图片素材id必须是永久 media_ID
* @param string $source_url 图文消息的原文地址即点击“阅读原文”后的URL
* @param string $content 图文消息的具体内容支持HTML标签必须少于2万字符小于1M且此处会去除JS
* @param string $author 作者
* @param string $digest 图文消息的摘要,仅有单图文消息才有摘要,多图文此处为空
* @param int $show_cover_pic 是否显示封面0为false即不显示1为true即显示
* @param int $need_open_comment 是否打开评论0不打开1打开
* @param int $only_fans_can_comment 是否粉丝才可评论0所有人可评论1粉丝才可评论
* @return Article
*/
public static function articleMessage($title, $thumb_media_id, $source_url, $content = '', $author = '', $digest = '', $show_cover_pic = 0, $need_open_comment = 0, $only_fans_can_comment = 1)
{
$data = is_array($title) ? $title : compact('title','thumb_media_id','source_url','content','author','digest','show_cover_pic','need_open_comment','only_fans_can_comment');
return new Article($data);
}
/**
* 回复素材消息
* @param string $type [mpnews、 mpvideo、voice、image]
* @param string $media_id 素材 ID
* @return Material
*/
public static function materialMessage($type, $media_id)
{
return new Material($type,$media_id);
}
/**
* 作为客服消息发送
* @param $to
* @param $message
* @return bool
*/
public static function staffTo($to, $message)
{
$staff = self::staffService();
$staff = is_callable($message) ? $staff->message($message()) : $staff->message($message);
$res = $staff->to($to)->send();
HookService::afterListen('wechat_staff_to',compact('to','message'),$res);
return $res;
}
/**
* 获得用户信息
* @param array|string $openid
* @return \EasyWeChat\Support\Collection
*/
public static function getUserInfo($openid)
{
$userService = self::userService();
$userInfo = is_array($openid) ? $userService->batchGet($openid) : $userService->get($openid);
return $userInfo;
}
}

View File

@ -1,182 +0,0 @@
<?php
/**
*
* @author: xaboy<365615158@qq.com>
* @day: 2018/01/06
*/
namespace service;
use app\wap\model\user\WechatUser;
use app\admin\model\wechat\WechatTemplate as WechatTemplateModel;
use app\admin\model\wechat\StoreService as ServiceModel;
class WechatTemplateService
{
/**
* 主营行业IT科技 互联网|电子商务
* 副营行业IT科技 IT软件与服务
*/
//订单生成通知
const ORDER_CREATE = 'OPENTM205213550';
//订单支付成功
const ORDER_PAY_SUCCESS = 'OPENTM207791277';
//订单发货提醒(快递)
const ORDER_POSTAGE_SUCCESS = 'OPENTM200565259';
//订单发货提醒(送货)
const ORDER_DELIVER_SUCCESS = 'OPENTM207707249';
//订单收货通知
const ORDER_TAKE_SUCCESS = 'OPENTM413386489';
//退款进度通知
const ORDER_REFUND_STATUS = 'OPENTM410119152';
//帐户资金变动提醒
const USER_BALANCE_CHANGE = 'OPENTM405847076';
//客服通知提醒
const SERVICE_NOTICE = 'OPENTM204431262';
//服务进度提醒
const ADMIN_NOTICE = 'OPENTM408237350';
//拼团成功通知
const ORDER_USER_GROUPS_SUCCESS = 'OPENTM407456411';
//拼团失败通知
const ORDER_USER_GROUPS_LOSE = 'OPENTM401113750';
public static function sendTemplate($openid,$templateId,array $data,$url = null,$defaultColor = '')
{
$tempid = WechatTemplateModel::where('tempkey',$templateId)->where('status',1)->value('tempid');
if(!$tempid) return false;
try{
return WechatService::sendTemplate($openid,$tempid,$data,$url,$defaultColor);
}catch (\Exception $e){
return false;
}
}
/**服务进度通知
* @param array $data
* @param null $url
* @param string $defaultColor
* @return bool
*/
public static function sendAdminNoticeTemplate(array $data,$url = null,$defaultColor = '')
{
$adminIds = explode(',',trim(SystemConfigService::get('site_store_admin_uids')));
$kefuIds = ServiceModel::where('notify',1)->column('uid');
if(empty($adminIds[0])){
$adminList = array_unique($kefuIds);
}else{
$adminList = array_unique(array_merge($adminIds,$kefuIds));
}
if(!is_array($adminList) || empty($adminList)) return false;
foreach ($adminList as $uid){
try{
$openid = WechatUser::uidToOpenid($uid);
}catch (\Exception $e){
continue;
}
self::sendTemplate($openid,self::ADMIN_NOTICE,$data,$url,$defaultColor);
}
}
/**
* 返回所有支持的行业列表
* @return \EasyWeChat\Support\Collection
*/
public static function getIndustry()
{
return WechatService::noticeService()->getIndustry();
}
/**
* 修改账号所属行业
* 主行业 副行业 代码
* IT科技 互联网/电子商务 1
* IT科技 IT软件与服务 2
* IT科技 IT硬件与设备 3
* IT科技 电子技术 4
* IT科技 通信与运营商 5
* IT科技 网络游戏 6
* 金融业 银行 7
* 金融业 基金|理财|信托 8
* 金融业 保险 9
* 餐饮 餐饮 10
* 酒店旅游 酒店 11
* 酒店旅游 旅游 12
* 运输与仓储 快递 13
* 运输与仓储 物流 14
* 运输与仓储 仓储 15
* 教育 培训 16
* 教育 院校 17
* 政府与公共事业 学术科研 18
* 政府与公共事业 交警 19
* 政府与公共事业 博物馆 20
* 政府与公共事业 公共事业|非盈利机构 21
* 医药护理 医药医疗 22
* 医药护理 护理美容 23
* 医药护理 保健与卫生 24
* 交通工具 汽车相关 25
* 交通工具 摩托车相关 26
* 交通工具 火车相关 27
* 交通工具 飞机相关 28
* 房地产 建筑 29
* 房地产 物业 30
* 消费品 消费品 31
* 商业服务 法律 32
* 商业服务 会展 33
* 商业服务 中介服务 34
* 商业服务 认证 35
* 商业服务 审计 36
* 文体娱乐 传媒 37
* 文体娱乐 体育 38
* 文体娱乐 娱乐休闲 39
* 印刷 印刷 40
* 其它 其它 41
* @param $industryId1
* @param $industryId2
* @return \EasyWeChat\Support\Collection
*/
public static function setIndustry($industryId1, $industryId2)
{
return WechatService::noticeService()->setIndustry($industryId1, $industryId2);
}
/**
* 获取所有模板列表
* @return \EasyWeChat\Support\Collection
*/
public static function getPrivateTemplates()
{
return WechatService::noticeService()->getPrivateTemplates();
}
/**
* 删除指定ID的模板
* @param $templateId
* @return \EasyWeChat\Support\Collection
*/
public static function deletePrivateTemplate($templateId)
{
return WechatService::noticeService()->deletePrivateTemplate($templateId);
}
/**
* 添加模板并获取模板ID
* @param $shortId
* @return \EasyWeChat\Support\Collection
*/
public static function addTemplate($shortId)
{
return WechatService::noticeService()->addTemplate($shortId);
}
}

View File

@ -1,208 +0,0 @@
<?php
namespace service;
/**
* 微信扫码支付
* Class WxpayService
* @package service
*
* 调用实例
*
* $data['total_amount'] = $payAmount;//价格
$data['order_id'] = time().$themeEnlist['enlist_card'].mt_rand(10,99);//订单 不能超过32为
ThemeEnlistModel::edit($data,$idB);
$mchid = SystemConfig::getValue('pay_weixin_mchid'); //微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送
$appid = SystemConfig::getValue('pay_weixin_appid'); //公众号APPID 通过微信支付商户资料审核后邮件发送
$apiKey = SystemConfig::getValue('pay_weixin_key'); //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥
$wxPay = new WxpayService($mchid,$appid,$apiKey);//实例化微信扫码类
$outTradeNo = $data['order_id']; //你自己的商品订单号
$notifyUrl = SystemConfig::getValue('site_url').Url::build('index/Themeenlist/wapay_success_notify'); //付款成功后的回调地址(不要有问号)
$payTime = time(); //付款时间
$arr = $wxPay->createJsBizPackage($payAmount,$outTradeNo,$orderName,$notifyUrl,$payTime);//创建成功会微信返回的数据
$url = 'http://pan.baidu.com/share/qrcode?w=104&h=100&url='.$arr['code_url'];//生成二维码 http://pan.baidu.com/share/qrcode 百度在线生成二维码链家
*/
class WxpayService
{
protected $mchid;
protected $appid;
protected $apiKey;
public function __construct($mchid, $appid, $key)
{
$this->mchid = $mchid;
$this->appid = $appid;
$this->apiKey = $key;
}
/**
* 发起订单
* @param float $totalFee 收款总费用 单位元
* @param string $outTradeNo 唯一的订单号
* @param string $orderName 订单名称
* @param string $notifyUrl 支付结果通知url 不要有问号
* @param string $timestamp 订单发起时间
* @return array
*/
public function createJsBizPackage($totalFee, $outTradeNo, $orderName, $notifyUrl, $timestamp)
{
$config = array(
'mch_id' => $this->mchid,
'appid' => $this->appid,
'key' => $this->apiKey,
);
//$orderName = iconv('GBK','UTF-8',$orderName);
$unified = array(
'appid' => $config['appid'],
'attach' => 'pay', //商家数据包原样返回如果填写中文请注意转换为utf-8
'body' => $orderName,
'mch_id' => $config['mch_id'],
'nonce_str' => self::createNonceStr(),
'notify_url' => $notifyUrl,
'out_trade_no' => $outTradeNo,
'spbill_create_ip' => '127.0.0.1',
'total_fee' => intval($totalFee * 100), //单位 转为分
'trade_type' => 'NATIVE',
);
$unified['sign'] = self::getSign($unified, $config['key']);
$responseXml = self::curlPost('https://api.mch.weixin.qq.com/pay/unifiedorder', self::arrayToXml($unified));
$unifiedOrder = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
if ($unifiedOrder === false) {
die('parse xml error');
}
if ($unifiedOrder->return_code != 'SUCCESS') {
die($unifiedOrder->return_msg);
}
if ($unifiedOrder->result_code != 'SUCCESS') {
die($unifiedOrder->err_code);
}
$codeUrl = (array)($unifiedOrder->code_url);
if(!$codeUrl[0]) exit('get code_url error');
$arr = array(
"appId" => $config['appid'],
"timeStamp" => $timestamp,
"nonceStr" => self::createNonceStr(),
"package" => "prepay_id=" . $unifiedOrder->prepay_id,
"signType" => 'MD5',
"code_url" => $codeUrl[0],
);
$arr['paySign'] = self::getSign($arr, $config['key']);
return $arr;
}
public function notify()
{
$config = array(
'mch_id' => $this->mchid,
'appid' => $this->appid,
'key' => $this->apiKey,
);
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
if ($postObj === false) {
die('parse xml error');
}
if ($postObj->return_code != 'SUCCESS') {
die($postObj->return_msg);
}
if ($postObj->result_code != 'SUCCESS') {
die($postObj->err_code);
}
$arr = (array)$postObj;
unset($arr['sign']);
if (self::getSign($arr, $config['key']) == $postObj->sign) {
echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
return $postObj;
}
}
/**
* curl get
*
* @param string $url
* @param array $options
* @return mixed
*/
public static function curlGet($url = '', $options = array())
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
if (!empty($options)) {
curl_setopt_array($ch, $options);
}
//https请求 不验证证书和host
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
public static function curlPost($url = '', $postData = '', $options = array())
{
if (is_array($postData)) {
$postData = http_build_query($postData);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
if (!empty($options)) {
curl_setopt_array($ch, $options);
}
//https请求 不验证证书和host
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
public static function createNonceStr($length = 16)
{
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$str = '';
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}
public static function arrayToXml($arr)
{
$xml = "<xml>";
foreach ($arr as $key => $val) {
if (is_numeric($val)) {
$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
} else
$xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
}
$xml .= "</xml>";
return $xml;
}
/**
* 获取签名
*/
public static function getSign($params, $key)
{
ksort($params, SORT_STRING);
$unSignParaString = self::formatQueryParaMap($params, false);
$signStr = strtoupper(md5($unSignParaString . "&key=" . $key));
return $signStr;
}
protected static function formatQueryParaMap($paraMap, $urlEncode = false)
{
$buff = "";
ksort($paraMap);
foreach ($paraMap as $k => $v) {
if (null != $v && "null" != $v) {
if ($urlEncode) {
$v = urlencode($v);
}
$buff .= $k . "=" . $v . "&";
}
}
$reqPar = '';
if (strlen($buff) > 0) {
$reqPar = substr($buff, 0, strlen($buff) - 1);
}
return $reqPar;
}
}

View File

@ -1,93 +0,0 @@
<?php
namespace service;
/**
* 微信扫码支付回调
* Class WxpayServiceNotify
* @package service
*
* 调用实例
*
* $mchid = SystemConfig::getValue('pay_weixin_mchid'); //微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送
$appid = SystemConfig::getValue('pay_weixin_appid'); //公众号APPID 通过微信支付商户资料审核后邮件发送
$apiKey = SystemConfig::getValue('pay_weixin_key'); //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥
$wxPay = new WxpayServiceNotify($mchid,$appid,$apiKey);
$result = $wxPay->notify();
if($result){
$data['is_pay'] = 1;
$data['pay_time'] = time();
$res = ThemeEnlistModel::edit($data,$result['out_trade_no'],'order_id');
if($res)
echo 'success';
//完成你的逻辑
//例如连接数据库,获取付款金额$result['cash_fee'],获取订单号$result['out_trade_no'],修改数据库中的订单状态等;
}else{
echo 'pay error';
}
*/
class WxpayServiceNotify
{
protected $mchid;
protected $appid;
protected $apiKey;
public function __construct($mchid, $appid, $key)
{
$this->mchid = $mchid;
$this->appid = $appid;
$this->apiKey = $key;
}
public function notify()
{
$config = array(
'mch_id' => $this->mchid,
'appid' => $this->appid,
'key' => $this->apiKey,
);
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
if ($postObj === false) {
die('parse xml error');
}
if ($postObj->return_code != 'SUCCESS') {
die($postObj->return_msg);
}
if ($postObj->result_code != 'SUCCESS') {
die($postObj->err_code);
}
$arr = (array)$postObj;
unset($arr['sign']);
if (self::getSign($arr, $config['key']) == $postObj->sign) {
echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
return $arr;
}
}
/**
* 获取签名
*/
public static function getSign($params, $key)
{
ksort($params, SORT_STRING);
$unSignParaString = self::formatQueryParaMap($params, false);
$signStr = strtoupper(md5($unSignParaString . "&key=" . $key));
return $signStr;
}
protected static function formatQueryParaMap($paraMap, $urlEncode = false)
{
$buff = "";
ksort($paraMap);
foreach ($paraMap as $k => $v) {
if (null != $v && "null" != $v) {
if ($urlEncode) {
$v = urlencode($v);
}
$buff .= $k . "=" . $v . "&";
}
}
$reqPar = '';
if (strlen($buff) > 0) {
$reqPar = substr($buff, 0, strlen($buff) - 1);
}
return $reqPar;
}
}