Merge branch 'dev' of wmtx/sdk into master

易宝 行为日志 贝塔版美国IP
master
张谷诚 5 years ago committed by Gogs
commit 0e1453961c

@ -372,6 +372,18 @@ class UserModel extends Model{
*user表加game_id
*/
public function sdk_register_($account,$password,$register_way,$register_type,$promote_id=0,$promote_account="",$phone="",$game_id="",$game_name="",$sdk_version="",$device_type="",$unique_code=""){
/* // 找该设备绑定的上级推广员 优先找这个表的
if ($unique_code) {
$deviceInfo = M('device_promote', 'tab_')->where(array(
'device_number' => $unique_code
))->order('id asc')->find();
if ($deviceInfo) {
$promote_id = $deviceInfo['promote_id'];
$promote_account = $deviceInfo['promote_account'];
}
} */
$data = array(
'account' => $account,
'password' => $password,
@ -411,6 +423,18 @@ class UserModel extends Model{
/* 添加用户 */
if($this->create($data)){
$uid = $this->add();
/* // 找该设备绑定的上级推广员 优先找这个表的
if ($unique_code) {
M('device_promote', 'tab_')->add(array(
'user_id' => $uid,
'promote_id' => $promote_id,
'promote_account' => $promote_account,
'device_number' => $unique_code,
'create_time' => time(),
));
} */
$u_user['uid']=$uid;
$u_user['account']=$account;
$u_user['password']=think_encrypt($password);

@ -856,5 +856,51 @@ class NotifyController extends BaseController
return true;
}
}
// 易宝支付通知
public function yeepay_callback() {
require_once("ThinkPHP/Library/Org/YeepaySDK/lib/Util/YopSignUtils.php");
Log::write(serialize($_REQUEST), Log::DEBUG);
$yop_public_key = C('yeepay.yop_public_key');
$private_key = C('yeepay.private_key');
$source = $_REQUEST['response'];
$sourceData = \YopSignUtils::decrypt($source, $private_key, $yop_public_key);
$sourceData = json_decode($sourceData, true);
if ($sourceData['status'] != 'SUCCESS') {
$this->record_logs("sourceData返回数据错误");
exit();
} else {
$pay_where = substr($sourceData['orderId'], 0, 2);
$data['trade_no'] = $sourceData['uniqueOrderNo']; // 易宝流水号
$data['out_trade_no'] = $sourceData['orderId']; // 平台生成的订单号SP
$data['money'] = $sourceData['payAmount'];
switch ($pay_where) {
case 'SP'://充值游戏
if ($this->recharge_is_exist($sourceData['out_trade_no'])) {
echo "SUCCESS";
exit();
}
$result = $this->set_spend($data);
echo "SUCCESS";
break;
case 'PF'://充值平台币
if ($this->deposit_is_exist($sourceData["out_trade_no"])) {
echo "SUCCESS";
exit();
}
$result = $this->set_deposit($data);
echo "SUCCESS";
break;
default:
$this->record_logs("易宝订单号{$sourceData['orderId']}错误!!");
break;
}
}
echo "SUCCESS";
}
}

@ -1189,7 +1189,7 @@ function age_verify($cardno, $name, $user_id = '')
$arr['create_time'] = time();
$arr['info'] = $info;
if ($date['status'] == '01') {
if ($date['status'] == '01') { // 验证成功
$arr['status'] = 1;
M('idcard_log', 'tab_')->data($arr)->add();
$age = floor((time() - strtotime($date['birthday'])) / (60 * 60 * 24 * 365));
@ -1198,11 +1198,11 @@ function age_verify($cardno, $name, $user_id = '')
} else {
return 2;
}
} elseif (isset($date['status']) && $date['status'] != '01') {
} elseif (isset($date['status']) && $date['status'] != '01') { // 验证错误 身份证和姓名不匹配
$arr['status'] = 0;
M('idcard_log', 'tab_')->data($arr)->add();
return 0;
} elseif(!isset($date['status']) && $date == 0) {
} elseif(!isset($date['status']) && $date == 0) {
$arr['status'] = 0;
M('idcard_log', 'tab_')->data($arr)->add();
return 0;

@ -1,5 +1,6 @@
<?php
use Sdk\Controller\BaseController;
use Think\Log;
// +----------------------------------------------------------------------
// | 徐州梦创信息科技有限公司—专业的游戏运营,推广解决方案.
@ -312,18 +313,50 @@ function jsonOutput($status=0, $msg='', $data=[]) {
* @param $ip
* @return bool
*/
function ip_is_country($ip, $country_id=['US'])
function ip_is_country($ip, $country_id=['US'], $country=['美国'])
{
$url = "http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
$url = "http://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query={$ip}&co=&resource_id=6006";
$url2 = "http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
$res = file_get_contents($url);
if (!empty($res)) {
$ipData = json_decode($res,true);
if ($ipData['code']==0 && in_array($ipData['data']['country_id'],$country_id)) {
if (!$res) { // 走淘宝
$res = file_get_contents($url2);
Log::write("taobao:".serialize($res));
if (!empty($res)) {
$ipData = json_decode($res,true);
if ($ipData['code']==0 && in_array($ipData['data']['country_id'],$country_id)) {
return true;
}
if ($ipData['code']==0 && in_array($ipData['data']['country'],$country)) {
return true;
}
}
} else {
$res= iconv('GB2312', 'UTF-8', $res);
$ipData = json_decode($res, true);
Log::write("sina:".serialize($res));
if ($ipData['status']==0 && substr($ipData['data'][0]['location'], 0, strlen($country[0])) == $country[0]) {
return true;
}
}
return false;
}
/*
* 记录行为日志
* @param [type] $log [description]
* @return [type] [description]
*/
function log_action($log) {
if(!empty($log['uid'])) {
$log['account'] = M('user', 'tab_')->where(['id' => $log['uid']])->getField('account');
}
if(!empty($log['game_id'])) {
$log['game_name'] = M('game', 'tab_')->where(['id' => $log['game_id']])->getField('game_name');
}
$log['ip'] = get_client_ip();
$log['create_time'] = time();
M('user_action_log', 'tab_')->data($log)->add();
}

@ -113,6 +113,7 @@ $config = array(
'SQ_UNION' => 10,
'SQ_SHORTCUT' => 15,
'SQ_SMALL_PROGRAM' => 16, //双乾 小程序
'YEEPAY' => 17, // 易宝支付
),
'ADMIN_DOMAIN' => 'https://dl.wmtxkj.com/', // 'http://10.0.1.75:8089/',//

@ -93,6 +93,7 @@ class ExchangeController extends BaseController{
$prefix = $request['code'] == 1 ? "SP_" : "PF_";
$out_trade_no = $prefix.date('Ymd').date('His').sp_random_string(4);
if (C('PAY_TEST')) $out_trade_no = $out_trade_no."_test";
$request['pay_order_number'] = $out_trade_no;
$user_entity = get_user_entity($request['user_id']);
@ -195,10 +196,16 @@ class ExchangeController extends BaseController{
// 是否是beta版苹果内购
$isBeta = false;
$isUSBeta = false;
if (isset($request['app_type']) && $request['app_type'] == 2) {
$isBeta = true;
// 美国IP 贝塔版
$ip = get_client_ip();
$isUSBeta = ip_is_country($ip, ['xx']);
}
if (get_game_appstatus2($request['game_id']) || $istest || !$isBeta/* &&$request['is_create_ordernumer']!=1 */){ /* 第三方支付 */
$isUSBeta = ip_is_country($ip);
// 美国IP的贝塔包 不管游戏设置怎么设置 都走苹果支付
if (!$isUSBeta && (get_game_appstatus2($request['game_id']) || $istest || !$isBeta/* &&$request['is_create_ordernumer']!=1 */)){ /* 第三方支付 */
$prefix = $request['code'] == 1 ? "SP_" : "PF_"; // SP
$out_trade_no = $prefix.date('Ymd').date('His').sp_random_string(4);
$request['pay_order_number'] = $out_trade_no;
@ -209,7 +216,7 @@ class ExchangeController extends BaseController{
$url = C('PAY_DOMAIN') . '/sdk.php?s=/Spend/'.$payPage.'&user_id='.$request['user_id'].'&game_id='.$request['game_id'].'&type=1'.'&user_token='.$userToken.'&action=pay'.'&extend='.urlencode($request['extend']);
echo base64_encode(json_encode(array('status'=>200,'out_trade_no'=>$out_trade_no,'img'=>$url)));exit;
// 只走第三方支付 不走苹果支付
} elseif(!get_game_appstatus2($request['game_id'] && $isBeta)/* &&$request['is_create_ordernumer']==1 */){ /* 废弃 苹果支付 */
} elseif ($isUSBeta || (!get_game_appstatus2($request['game_id'] && $isBeta))/* &&$request['is_create_ordernumer']==1 */){ /* 废弃 苹果支付 */
#获取订单信息
$prefix = $request['code'] == 1 ? "SP_" : "PF_";

@ -154,6 +154,10 @@ class GameController extends BaseController{
// $data['sdk_version'] = 2;
// }
// 美国IP 贝塔版
$ip = get_client_ip();
$isUSIP = ip_is_country($ip);
// var_dump($isUSIP);
if(empty($data['user_id'])) {
re_msg(1004, 'fail', '用户不存在');
}
@ -166,7 +170,9 @@ class GameController extends BaseController{
$sdkMenus = M('tool','tab_')->where(['name' => 'sdk_menu'])->find();
$menus = json_decode($sdkMenus['config'],true);
$rmenus = array();
foreach($menus as $k => $v) {
if(!empty($v['menu_version']) && $data['sdk_version'] != 0 && $v['menu_version'] != $data['sdk_version']){
unset($menus[$k]);
continue;
@ -192,12 +198,20 @@ class GameController extends BaseController{
continue;
}
}
// var_dump($isUSIP);
if (/* isset($data['app_type']) && $data['app_type'] == 2 && */$isUSIP) {
if($v['name'] == 'gift' || $v['name'] == 'suppersign') {
unset($menus[$k]);
continue;
}
}
//测试账号苹果审核
$menus[$k]['icon'] = (substr($v['icon'], 0, 7) == "http://" || substr($v['icon'], 0, 8) == "https://" ) ? $v['icon'] :
C('ADMIN_DOMAIN') . $v['icon'];
// die;
if($v['type'] != 3){
if($v['type'] != 3){ //
if (substr($menus[$k]['url'], 0, 7) == "http://" || substr($menus[$k]['url'], 0, 8) == "https://") {
$menus[$k]['url'] = $menus[$k]['url'] . '/user_token/' . $user['user_token']."/game_id/".$data['game_id'].'/sdk_version/'.$data['sdk_version'].'/api_ver/2';
} else {
@ -215,6 +229,7 @@ class GameController extends BaseController{
if ($data['sdk_version'] == 1 && $menus[$k]['name'] == 'suppersign'){
unset($menus[$k]);
continue;
}elseif($data['sdk_version'] != 1 && $v['name'] == 'suppersign'){
// $menus[$k]['url'] = $v['url'] . '/user_token/' . $user['user_token'] . "/game_id/". $data['game_id'];
$menus[$k]['ios_url'] = $v['ios_url'] . '/user_token/' . $user['user_token'] . '/user_id/' . $data['user_id'] . '/game_id/' . $data['game_id'] . '.html?action=openurl';
@ -224,6 +239,7 @@ class GameController extends BaseController{
}
}
$personalMenu = M('tool','tab_')->where(['name' => 'personal_menu'])->getField('config');
$personalMenu = json_decode($personalMenu, true);
foreach($personalMenu as $k => $v) {
@ -250,6 +266,14 @@ class GameController extends BaseController{
continue;
}
}
if (/* isset($data['app_type']) && $data['app_type'] == 2 && */$isUSIP) {
if($v['name'] == 'gift' || $v['name'] == 'balance') {
unset($personalMenu[$k]);
continue;
}
}
//测试账号苹果审核
$personalMenu[$k]['icon'] = (substr($v['icon'], 0, 7) == "http://" || substr($v['icon'], 0, 8) == "https://" ) ? $v['icon'] :
C('ADMIN_DOMAIN') . $v['icon'];
@ -282,7 +306,7 @@ class GameController extends BaseController{
}
// 2456623.96
array_multisort(array_column($menus,'sort'),SORT_ASC,$menus);
array_multisort(array_column($menus,'sort'), SORT_ASC, $menus);
array_multisort(array_column($personalMenu,'sort'),SORT_ASC,$personalMenu);
$menusArr = [];

@ -5,6 +5,7 @@ use Common\Api\GameApi;
use Org\SqpaySDK\Sqpay;
use Qiniu\json_decode;
use Think\Log;
use Org\YeepaySDK\Yeepay;
class ShortcutController extends BaseController{
// 签约处理
@ -346,7 +347,7 @@ class ShortcutController extends BaseController{
if (!$is_platform) {
$request['extend'] = I('request.extend');
$extend_data = M('spend','tab_')->where(array('extend'=>$request['extend'],'game_id'=>$request['game_id'],'pay_status'=>1))->find();
$extend_data = M('spend','tab_')->where(array('extend'=>$request['extend'],'game_id'=>$request['game_id']))->find();
if($extend_data){
redirect(U('Spend/notice',array('user_id'=>$user_id,'game_id'=>$game_id,'is_platform'=> $is_platform,'msg'=>$request['game_id'].'订单号重复,请关闭支付页面重新支付'.$request['extend'], 'user_token' => $userToken)));exit;
}
@ -437,4 +438,167 @@ class ShortcutController extends BaseController{
}
// 快捷---易宝支付
public function yee_pay($user_id,$game_id) {
$is_platform = 0;
if (I('request.code') == 0 && I('request.type') == 'platform') {
$is_platform = 1; // 平台币充值
}
$request['game_id'] = I('request.game_id');
$game_id = $request['game_id'];
$request['user_id'] = I('request.user_id');
$user_id = $request['user_id'];
$request['code'] = I('request.code');
$payInfo = M('pay_info', 'tab_')->where([
'user_id' => I('request.user_id'),
'game_id' => I('request.game_id'),
'extend' => I('request.extend', ''),
])->order('id desc')->find();
$request['price'] = $payInfo['price'];
$userToken = I('request.user_token');
if (empty($request)) {
echo json_encode(['code'=>0, 'msg'=> '登录数据不能为空']);
exit;
}
// 支付验证 是否让支付
$payCheck = pay_check($request['user_id']);
if (!$payCheck['code']) {
echo json_encode(['code'=>0, 'msg'=> $payCheck['msg']]);
exit;
}
$game = M('Game','tab_')->where(['id'=>$request['game_id']])->field('pay_status')->find();
if($game['pay_status'] == 0){
echo json_encode(['code'=>0, 'msg'=> "该游戏暂时无法充值,请联系客服!"]);
exit;
}
if($request['price']*1<=0){
echo json_encode(['code'=>0, 'msg'=> "充值金额有误"]);
exit;
}
C(api('Config/lists'));
if (!$is_platform) {
$request['extend'] = I('request.extend');
$extend_data = M('spend','tab_')->where(array('extend'=>$request['extend'],'game_id'=>$request['game_id']))->find();
if($extend_data){
echo json_encode(['code'=>0, 'msg'=> "订单号重复,请关闭支付页面重新支付."]);
exit;
}
}
//折扣
$user = get_user_entity($request['user_id']);
$discount = $this->get_discount($request['game_id'],$user['promote_id'],$request['user_id']);
$discount = $discount['discount'];
$pay_amount = $discount * $request['price'] / 10;
if ($pay_amount < 0.01) {
echo json_encode(['code'=>0, 'msg'=> "充值金额有误."]);
exit;
}
if (!$is_platform) {
$this->other_price($request, $request['price']-$pay_amount);
}
// 平台币充值
if ($is_platform) {
$request['code'] = 0;
$request['user_id'] = I('request.user_id');
$request['price'] = intval(I('request.price'));
$request['game_id'] = I('request.game_id');
$request['pay_way'] = C("PAY_WAY.YEEPAY"); // 支付方式(-1绑币 0:平台币,1:支付宝,2:微信(扫码)3微信app 4 威富通 5聚宝云 6竣付通 7苹果支付8金猪支付 9双乾支付-支付宝 10双乾支付-银联 15双乾支付-快捷
$request['pay_status'] = 0;
$request['spend_ip'] = get_client_ip();
$payInfo = M('pay_info', 'tab_')->where([
'user_id' => I('request.user_id'),
'game_id' => I('request.game_id'),
'extend' => I('request.extend', ''),
])->order('id desc')->find();
$request['pay_order_number'] = $payInfo['order_id'];
if (!$payInfo) {
return ;
}
} else { // 游戏充值
$request['code'] = 1;
$payInfo = M('pay_info', 'tab_')->where([
'user_id' => I('request.user_id'),
'game_id' => I('request.game_id'),
'extend' => I('request.extend'),
])->order('id desc')->find();
if ($payInfo) {
$info = json_decode($payInfo['info'], true);
$info['deduction_amount'] = $request['deduction_amount'];
$info['actual_amount'] = $request['actual_amount'];
$info['discount_amount'] = $request['discount_amount'];
$info['price'] = $request['price'];
$infosave = json_encode($info);
M('pay_info', 'tab_')->where([
'id' => $payInfo['id']
])->save([
'type' => 'yee_shortcut', // 游戏充值
//'order_id' => $request['pay_order_number'],
//'price' => $request['actual_amount'] ? $request['actual_amount'] : $request['price'],
'info' => $infosave
]);
$info['code'] = $request['code'];
$info['pay_order_number'] = $request['pay_order_number'];
$request = $info;
$request['pay_way'] = C("PAY_WAY.YEEPAY");
$request['pay_status'] = 0;
$request['spend_ip'] = get_client_ip();
$request['pay_order_number'] = $payInfo['order_id'];
}
}
$yeepay = new Yeepay();
$data['appKey'] = C('yeepay.key');
$data['privateKey'] = C('yeepay.private_key');
$data['parentMerchantNo'] = C('yeepay.parent_merchant');
$data['merchantNo'] = C('yeepay.partner');
$data['orderId'] = $request['pay_order_number'];
$data['orderAmount'] = $request['price'];
$data['notifyUrl'] = C('PAY_DOMAIN')."/callback.php/Notify/yeepay_callback";
$data['goodsParamExt'] = '{"goodsName":"游戏充值","goodsDesc":"充值"}';
$data['memo'] = "游戏充值-{$request['pay_order_number']}";
if ($is_platform) {
$data['redirectUrl'] = C('PAY_DOMAIN').U('Spend/shortcut_payed',array('status'=> 1, 'orderno' => $payInfo['order_id'], 'user_id'=>I('user_id'),'game_id'=>I('game_id'), 'user_token' => I('request.user_token')));
} else {
$data['redirectUrl'] = C('PAY_DOMAIN').U('Spend/shortcut_notice',array('status'=> 1, 'orderno' => $payInfo['order_id'], 'user_id'=>I('user_id'),'game_id'=>I('game_id'), 'user_token' => I('request.user_token')));
}
/* $bankCardNo = I('bankCardNo', '');
$idCardNo = I('idCardNo', '');
$cardName = I('cardName', '');
if (!$bankCardNo || !$idCardNo || !$cardName) {
echo json_encode(['code'=>0,'msg'=> '参数有误']);
exit;
}
$data['paymentParamExt'] = '{"bankCardNo":"'.$bankCardNo.'","idCardNo":"'.$idCardNo.'","cardName":"'.$cardName.'"}';
*/
$data['paymentParamExt'] = '{}';
$yeeData = $yeepay->yee_pay($data);
// var_dump($yeeData);//die;
if ($yeeData['data']['result']['code'] != 'OPR00000') {
echo json_encode(['code'=>0, 'msg'=> '支付参数有误,请重试'.$yeeData['data']['result']['code']]);
exit;
}
$request['pay_url'] = $yeeData['url'];
if($request['code']==1){
$this->add_spend($request,1);
}else{
$this->add_deposit($request,1);
}
$returl = html_entity_decode($yeeData['url']);
echo json_encode(['code'=>200, 'url'=> $returl]);
return ;
}
}

@ -67,13 +67,11 @@ class SpendController extends Controller {
'game_id' => $game_id
])->order("id desc")->find();
$request = json_decode($pay_info['info'], true);
/* $file = file_get_contents ( "./Application/Sdk/OrderNo/" . $user_id . "-" . $game_id . ".txt" );
$request = json_decode ( think_decrypt ( $file ), true ); */
$data = array(
'coin' => $request ['body'],
'price' => $request ['price'],
'price' => $request ['price'] + $request['deduction_amount'],
'game_name' => $request ['game_name'],
'code' => $request ['code']
);
@ -461,4 +459,75 @@ ADD COLUMN `pay_url` varchar(255) NOT NULL DEFAULT '' AFTER `check_sign`;
$this->display();
}
// 易宝快捷支付 通知页面
public function shortcut_payed() {
$userToken = I('user_token');
$orderno = I('request.orderno');
if (!$orderno) $orderno = I('request.out_trade_no');
// $orderno = $_GET['orderno'] == "" ? $_GET ['out_trade_no'] : $_GET ['orderno'];
$pay_where = substr($orderno, 0, 2);
// $Scheme = file_get_contents("./Application/Sdk/Scheme/" . $_GET ['game_id'] . ".txt");
$gameId = $_GET ['game_id'];
$Scheme = "txgame".$gameId;
$map ['pay_order_number'] = $orderno;
$paytype = I('request.paytype', 0); // 支付方式 weixinpay alipay
$gopay = I('request.gopay');
switch ($pay_where) {
case 'SP' :
$result = M('Spend', 'tab_')->field ("*")->where ($map)->find();
break;
case 'PF' :
$result = M('deposit', 'tab_')->field ('*')->where ($map)->find();
break;
case 'TB' :
$result = M('balance', 'tab_')->field ('*')->where ($map)->find();
break;
case 'BR' :
$result = M('bind_recharge', 'tab_')->field ('*')->where ($map)->find();
break;
}
// 支付成功跳转页面
if ($result['pay_status'] == 1) {
// $this->success("支付成功", U("userH/get_user_money", ['user_token' => $userToken]));
}
// 微信 支付宝 快捷
if ($pay_where == "SP") {
$gopayUrl = $result['pay_url'];
}
if ($pay_where == "PF") {
$gopayUrl = $result['pay_url'];
}
// 如果是json格式 且是alipay 则 alipay app
if (json_decode($gopayUrl) && $paytype == 'alipay') {
$this->assign("aliapp", 1);
} else {
$this->assign("aliapp", 0);
}
if(get_zfb_type() == 2) {
$this->assign("sqzfb", 1);
} else {
$this->assign("sqzfb", 0);
}
// pp($orderno);
// $this->assign('payway', $payway);
$this->assign("orderno", $orderno);
$this->assign("paytype", $paytype);
$this->assign("price", $result['pay_amount']);
$this->assign ('pay_url', $result['pay_url']);
$this->assign("sdk_version", $result['sdk_version']?:0);
$this->assign ('Scheme', $Scheme);
$this->assign ('gopay', $gopay);
$this->assign ('user_token', $userToken);
$this->assign ('game_id', $gameId);
$this->assign ('gopay_url', $gopayUrl);
$this->assign ('paystatus', $result ['pay_status']);
$this->display ();
}
}

@ -29,11 +29,17 @@ class UserController extends BaseController
$this -> set_message(1001, "fail", "登录数据不能为空");
}
$log['uid'] = 0;
$log['game_id'] = $user['game_id'];
$log['type'] = 3;
$log['action'] = json_encode($user); // 请求参数
$ip = get_client_ip();
$device_bans_ip = M('device_bans','tab_')->where(['tag' => $ip,'type' => 2])->find();
$device_bans_num = M('device_bans','tab_')->where(['tag' => $user['unique_code'],'type' => 1])->find();
if(!empty($device_bans_ip) || !empty($device_bans_num)){
$log['remarks'] = '设备已被禁用';
log_action($log);
$this->set_message(1004, "fail", "设备已被禁用");
}
@ -52,9 +58,13 @@ class UserController extends BaseController
$res_msg = array();
switch ($result) {
case - 1:
$log['remarks'] = '用户不存在或被禁用';
log_action($log);
$this -> set_message(1004, "fail", "用户不存在或被禁用");
break;
case - 2:
$log['remarks'] = '密码错误';
log_action($log);
$this -> set_message(1005, "fail", "密码错误");
break;
default:
@ -95,10 +105,13 @@ class UserController extends BaseController
'notice_count' => $notice_count,
);
} else {
$log['remarks'] = '未知错误';
log_action($log);
$this -> set_message(1028, "fail", "未知错误");
}
break;
}
log_action($log);
echo base64_encode(json_encode($res_msg));
die;
@ -125,9 +138,13 @@ class UserController extends BaseController
$res_msg = array();
switch ($result) {
case - 1:
$log['remarks'] = '用户不存在或被禁用';
log_action($log);
$this -> set_message(1004, "fail", "用户不存在或被禁用");
break;
case - 2:
$log['remarks'] = '密码错误';
log_action($log);
$this -> set_message(1005, "fail", "密码错误");
break;
default:
@ -178,14 +195,19 @@ class UserController extends BaseController
'request_count' => $buddies_request,
);
} else {
$log['remarks'] = '未知错误';
log_action($log);
$this -> set_message(1028, "fail", "未知错误");
}
break;
}
log_action($log);
echo base64_encode(json_encode($res_msg));
die;
} else {
$log['remarks'] = '账号已存在';
log_action($log);
$this -> set_message(1004, "账号已存在");
}
@ -197,9 +219,13 @@ class UserController extends BaseController
$res_msg = array();
switch ($result) {
case - 1:
$log['remarks'] = '用户不存在或被禁用';
log_action($log);
$this -> set_message(1004, "fail", "用户不存在或被禁用");
break;
case - 2:
$log['remarks'] = '密码错误';
log_action($log);
$this -> set_message(1005, "fail", "密码错误");
break;
default:
@ -248,18 +274,24 @@ class UserController extends BaseController
'request_count' => $buddies_request,
);
} else {
$log['remarks'] = '未知错误';
$log['uid'] = $user["user_id"];
log_action($log);
$this -> set_message(1028, "fail", "未知错误");
}
break;
}
//同步ucenter注册
cus_uc_register($username, $password, $username . '@vlcms.com');
log_action($log);
echo base64_encode(json_encode($res_msg));
die;
} elseif ($uc_uid == - 2) {
//密码错误
$log['remarks'] = '密码错误';
log_action($log);
$this -> set_message(1005, "fail", "密码错误");
} else {
//登录失败
@ -272,14 +304,17 @@ class UserController extends BaseController
switch ($result) {
case - 1:
$log['remarks'] = '扶持号被禁用';
log_action($log);
$this -> set_message(1005, "fail", "密码错误");
break;
case - 2:
$log['remarks'] = '密码错误';
log_action($log);
$this -> set_message(1005, "fail", "密码错误");
break;
default:
if (is_array($result)) {
$user["user_id"] = $result['user_id'];
$user['puid'] = 0;
$this -> add_user_play($user);
@ -331,6 +366,63 @@ class UserController extends BaseController
'notice_count' => $notice_count,
'request_count' => $buddies_request,
);
/* // 仅对3月1日之后注册的用户有效。登入时 该会员如果没绑定 优先找设备绑定表
$registerTimeLimit = strtotime("2020-03-01");
if ($user_res['register_time'] > $registerTimeLimit && $user['unique_code']) {
// 1 看自己的推广员是否绑定了设备 绑定过得不修改
// 2 没有推广员的以设备为准 没有设备以包为准
$changeFlag = false; // 是否修改推广员
$changePromoteId = $user_res['promote_id'];
$changePromoteAccount = $user_res['promote_account'];
$deviceInfoByDevice = M('device_promote', 'tab_')->where(array(
'device_number' => $user['unique_code']
))->order('id asc')->find();
if ($user_res['promote_id'] > 0) { // 已存在推广员 修改推广员的情况 设备被其他推广绑定
$deviceInfoByUID = M('device_promote', 'tab_')->where(array(
'user_id' => $user_res['id']
))->find();
if (!$deviceInfoByUID) {
if ($deviceInfoByDevice) {
$changeFlag = true;
$changePromoteId = $deviceInfoByDevice['promote_id'];
$changePromoteAccount = get_promote_account($changePromoteId);
}
}
} else { // 没有推广员的情况下直接绑定这个设备
if ($deviceInfoByDevice) { // 这个设备绑定过推官员的修改成改推广员
$changeFlag = true;
$changePromoteId = $deviceInfoByDevice['promote_id'];
$changePromoteAccount = get_promote_account($changePromoteId);
}
}
$userPromote = M('device_promote', 'tab_')->where(array(
'user_id' => $user_res['id'],
'device_number' => $user['unique_code'],
))->find();
if (!$userPromote && $changePromoteId > 0) {
M('device_promote', 'tab_')->add(array(
'user_id' => $user_res['id'],
'promote_id' => $changePromoteId,
'promote_account' => get_promote_account($changePromoteId),
'device_number' => $user['unique_code'],
'create_time' => time(),
));
}
// pp(M('device_promote', 'tab_')->_sql());
if ($changeFlag) {
M('user', 'tab_')->where(array('id' => $user_res['id']))->save(array(
'promote_id' => $changePromoteId,
'promote_account' => $changePromoteAccount,
));
$log['type'] = 11; // 修改绑定上级推广员
log_action($log);
}
} */
// 通知后台 TASK_URLhttp://47.111.118.107:9501
$url = C('TASK_URL')."/game-event/login";
@ -347,13 +439,16 @@ class UserController extends BaseController
}
} else {
$log['remarks'] = '未知错误';
log_action($log);
$this -> set_message(1028, "fail", "未知错误");
}
break;
}
$log['uid'] = $user['user_id'];
log_action($log);
echo base64_encode(json_encode($res_msg));
@ -934,18 +1029,26 @@ class UserController extends BaseController
#实例化用户接口
$data['id'] = $user['user_id'];
$userApi = new MemberApi();
$log['uid'] = $user['user_id'];
$log['game_id'] = $user['game_id'];
$log['action'] = json_encode($user);
switch ($user['code']) {
case 'phone':
$log['type'] = 1;
//对于手机号 加上是否重复的验证过程 和 是否预计绑定的验证过程
$where['id'] = $data['id'];
$getphone = M('User', 'tab_') -> where($where) -> getField('phone');
if (!empty($getphone)) {
$log['remarks'] = '该用户已经绑定过手机号,请解绑后再来';
log_action($log);
$this -> new_set_message(1125, '该用户已经绑定过手机号,请解绑后再来');
}
$tt['phone'] = $user['phone'];
$getuser = M('User', 'tab_') -> where($tt) -> field('id') -> find();
if ($getuser) {
$log['remarks'] = '该手机号已被绑定';
log_action($log);
$this -> new_set_message(1098, '该手机号已被绑定');
}
#验证短信验证码
@ -969,14 +1072,19 @@ class UserController extends BaseController
$data['nickname'] = $user['nickname'];
break;
case 'pwd':
$log['type'] = 0;
/* if(!preg_match('/^(?![^a-zA-Z]+$)(?!\D+$).{6,15}$/', $user['password'])){
$this -> new_set_message(1027, "密码必须6-15位字母和数字组合");
} */
if(!preg_match('/^[0-9a-zA-Z]{6,15}$/', $user['password'])){
$log['remarks'] = '密码6-15位字母或数字';
log_action($log);
$this -> new_set_message(1027, "fail", "密码6-15位字母或数字");
}
if ($user['old_password'] == $user['password']) {
$log['remarks'] = '新密码与原始密码不能相同';
log_action($log);
$this -> new_set_message(1126, '新密码与原始密码不能相同');
}
$data['old_password'] = $user['old_password'];
@ -1025,7 +1133,8 @@ class UserController extends BaseController
}
$result = $userApi -> updateUser($data);
if ($result == - 2) {
$log['remarks'] = '旧密码输入不正确';
log_action($log);
$this -> new_set_message(1006, "旧密码输入不正确");
} else if ($result !== false) {
@ -1039,10 +1148,13 @@ class UserController extends BaseController
$user_res = M('User', 'tab_') -> where(['id' => $user['user_id']]) -> find();
$data = ['user_account' => $user_res['nickname'], 'update_time' => time(), 'head_img' => $user_res['head_img']];
M('nearby', 'tab_') -> where(['user_id' => $user['user_id']]) -> save($data);
$log['remarks'] = '修改成功';
log_action($log);
$this -> new_set_message(200, "修改成功");
} else {
$log['remarks'] = '修改失败';
log_action($log);
$this -> new_set_message(1012, "修改失败");
}
@ -1129,6 +1241,9 @@ class UserController extends BaseController
{
$user = json_decode(base64_decode(file_get_contents("php://input")), true);
$log['game_id'] = $user['game_id'];
$log['type'] = 0;
$log['action'] = json_encode($user);
$userApi = new MemberApi();
#验证短信验证码
if ($user['code_type'] != 2) {
@ -1138,16 +1253,20 @@ class UserController extends BaseController
// $this -> set_message(1027, "fail", "密码必须6-15位字母和数字组合");
// }
if(!preg_match('/^[0-9a-zA-Z]{6,12}$/', $user['password'])){
$log['remarks'] = '密码长度为6-12位';
log_action($log);
$this -> set_message(1027, "fail", "密码长度为6-12位");
}
$result = $userApi -> updatePassword($user['user_id'], $user['password']);
if ($result == true) {
$log['remarks'] = '修改成功';
log_action($log);
$this -> set_message(200, "success", "修改成功");
} else {
$log['remarks'] = '修改失败';
log_action($log);
$this -> set_message(1012, "fail", "修改失败");
}
@ -1289,7 +1408,12 @@ class UserController extends BaseController
$data['pipuid'] = $user_data['puid'];
Log::write('save_user_play_info:' . date('Y-m-d H:i:s') . ' ---- ' . json_encode($data), 'INFO');
$log['uid'] = $user_id;
$log['game_id'] = $request['game_id'];
$log['action'] = json_encode($request);
$log['type'] = 5;
$log['remarks'] = json_encode($data);
log_action($log);
if ($res['id']>0) {
$user_play->save($data);
$this->updateLoginRecord($data);
@ -2154,6 +2278,10 @@ class UserController extends BaseController
{
C(api('Config/lists'));
$user = json_decode(base64_decode(file_get_contents("php://input")), true);
$log['uid'] = $user['user_id'];
$log['game_id'] = $user['game_id'];
$log['type'] = 2;
$log['action'] = json_encode($user);
if (empty($user['user_id']) || empty($user['idcard']) || empty($user['real_name'])) {
$this -> set_message(1066, "fail", "用户数据异常");
@ -2163,11 +2291,15 @@ class UserController extends BaseController
$data['real_name'] = $user['real_name'];
if (isset($data['idcard'])) {
if (substr($data['idcard'], - 1) === 'X') {
$log['remarks'] = '身份证不正确,字母请小写';
log_action($log);
$this -> set_message(1086, "fail", "身份证不正确,字母请小写");
}
$checkidcard = new \Think\Checkidcard();
$invidcard = $checkidcard -> checkIdentity($data['idcard']);
if (!$invidcard) {
$log['remarks'] = '身份证号码填写不正确!';
log_action($log);
$this -> set_message(1086, "fail", "身份证号码填写不正确!");
}
@ -2199,6 +2331,8 @@ class UserController extends BaseController
if($model['status'] == 1) {
$data['age_status'] = is_adult($data['idcard']) ? 2 : 3;
} elseif ($model['status'] == 0) {
$log['remarks'] = '用户数据不匹配';
log_action($log);
$this -> set_message(1069, "fail", "用户数据不匹配");
}
} else {
@ -2216,12 +2350,18 @@ class UserController extends BaseController
switch ($re) {
case - 1:
$log['remarks'] = '数量已经使用完!';
log_action($log);
$this -> set_message(1067, "fail", "数量已经使用完!");
break;
case - 2:
$log['remarks'] = '连接接口失败';
log_action($log);
$this -> set_message(1068, "fail", "连接接口失败");
break;
case 0:
$log['remarks'] = '用户数据不匹配';
log_action($log);
$this -> set_message(1069, "fail", "用户数据不匹配");
break;
case 1://成年
@ -2239,8 +2379,12 @@ class UserController extends BaseController
$return = M('User', 'tab_') -> where($map) -> save($data);
if ($return === false) {
$log['remarks'] = '用户数据更新失败';
log_action($log);
$this -> set_message(1070, "fail", "用户数据更新失败");
}
$log['remarks'] = '修改成功';
log_action($log);
$data['status'] = 200;
echo base64_encode(json_encode($data));
@ -2298,6 +2442,8 @@ class UserController extends BaseController
$this -> set_message(0, "fail", "找不到该用户!");
}
$request['user_id'] = (!empty($user['id'])) ? $user['id'] : 0;
$da = array(
'user_id' => $user['id'],
'user_account' => $user['account'],
@ -2313,6 +2459,13 @@ class UserController extends BaseController
'promote_id' => $request['promote_id'],
'lpuid' => $user['puid'],
);
$log['uid'] = $user['id'];
$log['game_id'] = $request['game_id'];
$log['action'] = json_encode($request);
$log['type'] = 4;
log_action($log);
// $return = M('UserLoginRecord', 'tab_') -> add($da);
$model = M('UserLoginRecord', 'tab_')->where(['user_id' => $user['id'],'game_id' => $request['game_id']])->order('id DESC')->find();
M('UserLoginRecord', 'tab_')->where(['id' => $model['id']])->setField(['down_time' => NOW_TIME]);
@ -2657,6 +2810,8 @@ class UserController extends BaseController
}
}
$request['user_id'] = (!empty($request['user_id'])) ? $request['user_id'] : 0;
$data = array(
'create_time' => $now,
'version' => $request['sdk_version'],

@ -82,6 +82,16 @@
<img src="__IMG__/pay_way/dagou1.png" alt="">
</div>
</if>
<if condition="C('yeepay.status') eq 1 and C('yeepay.shortcut') eq 1">
<div class="payment_rest_way way_btn" data-type="shorcut" data-url="{:U('Shortcut/yee_pay', array('user_id'=>I('user_id'),'game_id'=>I('game_id'),'user_token'=>I('user_token'),'code'=>1,'extend'=>I('extend'),'api_ver'=>2))}">
<div>
<img src="__IMG__/pay_way/xianshang.png" alt="">
<span>快捷易宝支付</span>
</div>
<img src="__IMG__/pay_way/dagou1.png" alt="">
</div>
</if>
</div>
</div>
<!-- <div class="payment_rest_btn">其他支付方式</div> -->
@ -174,6 +184,16 @@
<img src="__IMG__/pay_way/dagou1.png" alt="">
</div>
</if>
<if condition="C('yeepay.status') eq 1 and C('yeepay.shortcut') eq 1">
<div class="payment_rest_way way_btn" data-type="shorcut" data-url="{:U('Shortcut/yee_pay', array('user_id'=>I('user_id'),'game_id'=>I('game_id'),'user_token'=>I('user_token'),'code'=>1,'extend'=>I('extend'),'api_ver'=>2))}">
<div>
<img src="__IMG__/pay_way/xianshang.png" alt="">
<span>快捷易宝支付</span>
</div>
<img src="__IMG__/pay_way/dagou1.png" alt="">
</div>
</if>
</div>
</div>
<!-- 供上下滑动延长 -->
@ -352,7 +372,30 @@
}
//快捷支付
function shorcut(){
window.location.href =payurl;
var url = payurl;
$.ajax({
type:'post',
dataType:'json',
data:{},
url:url,
success:function(result) {
if(result.code==200) {
window.location.href = result.url;
} else {
flag=false;
$(".tipmsg").html(result.msg);
$(".msgdialog").show();
}
},
error:function(){
flag=false;
$(".tipmsg").html("接口请求错误");
$(".msgdialog").show();
}
});
return false;
// window.location.href =payurl;
}
//平台币支付
function platform_pay(){

@ -0,0 +1,243 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="stylesheet" href="__CSS__/weui.mim.css">
<link rel="stylesheet" href="__CSS__/sdkptbpay.css">
<script src="__JS__/resize.js" type=""></script>
<title>支付结果</title>
</head>
<body>
<div class="callback-box" style="padding-top: 100px;box-sizing: border-box;">
<input type="hidden" name="pay_order_number" class="orderno" value="{$orderno}">
<input type="hidden" name="Scheme" class="Scheme" value="{$Scheme}">
<input type="hidden" name="sdk_version" id="sdk_version" class="sdk_version" value="{$sdk_version}">
<input type="hidden" name="at_once" class="at_once" value="{$at_once}">
<input type="hidden" name="gopay_url" class="gopay_url" value='{$gopay_url}'>
<input type="hidden" name="gopay" class="gopay" value="{$gopay}">
<input type="hidden" name="aliapp" class="aliapp" value="{$aliapp}">
<input type="hidden" name="sqzfb" class="sqzfb" value="{$sqzfb}">
<input type="hidden" name="user_token" class="user_token" value="{$user_token}">
<input type="hidden" name="game_id" class="game_id" value="{$game_id}">
<!-- <div class="close" onclick="javascript:history.go(-1);">
<a href="javascript:">
<img src="__IMG__/callback/close.png">
</a>
</div> -->
<div id="toast" style="display: none;">
<div class="weui-mask_transparent"></div>
<div class="weui-toast" style="min-height: 0px;">
<!-- <i class="weui-icon-success-no-circle weui-icon_toast"></i> -->
<p class="weui-toast__content" style="margin:15px;"><span id="paytype">支付成功</span><br/><span style="font-size: .24rem;">2秒后将自动跳转</span></p>
</div>
</div>
<div class="wxicon" style="display: flex;flex-direction: column;justify-content: center; align-items: center;">
<img src="__IMG__/shortcut_payed.png">
<span style="font-size: 0.28rem; color:#FEB957;margin-top:0.3rem;">支付成功</span>
</div>
<div class="paydesc" style="margin-bottom: 2.4rem;">
<div>
<p id ="testn" style="text-align: center; font-size: 0.28rem;color:rgba(0,0,0,1);">您已充值平台币:</p>
<p style="text-align: center;font-size: 0.8rem; font-weight:500;font-family:PingFang SC;color:rgba(0,0,0,1);">¥{$price}</p>
<br/><br/>
<p/><br/>
</div>
</div>
<div class="btn2">
<a id="payed" data-order="{$pay_order_number}" href="javascript:" style="background:url('__IMG__/callback/btn2.png') no-repeat center center/100% 100%;background-color: #21B1EB; border-radius: 0.35rem; color: white;">
已完成付款
</a>
</div>
<!-- <div class="btn2">
<a id="payed1" data-order="{$pay_order_number}" href="javascript:" style="background:url('__IMG__/callback/btn2.png') no-repeat center center/100% 100%;">
跳成功
</a>
</div>
<div class="btn2">
<a id="payed2" data-order="{$pay_order_number}" href="javascript:" style="background:url('__IMG__/callback/btn2.png') no-repeat center center/100% 100%;">
跳失败
</a>
</div> -->
<div class="whitesc"></div>
</div>
</body>
<script src="__JS__/jquery.min.js"></script>
<script>
function paycallback() {
$("#payed").click();
}
$(function() {
$(window).load( function(){
if ($(".gopay").val() == 1) {
if ($(".aliapp").val() == 1) {
var url = $(".gopay_url").val();
if ($('#sdk_version').val() == 0) {
var u = navigator.userAgent;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
if (isAndroid) {
window.txyxsdk.getZFBPay(url);
} else {
window.webkit.messageHandlers.noticeAppResult.postMessage(url);
}
} else if ($('#sdk_version').val() == 1) {
window.txyxsdk.getZFBPay(url);
} else {
window.webkit.messageHandlers.noticeAppResult.postMessage(url);
}
} else {
if ($(".gopay_url").val()) {
window.location.href = $(".gopay_url").val();
}
}
}
});
/* $("#payed1").click(function(){
var Scheme=$('.Scheme').val();
window.location.href = Scheme+"://1&back";
});
$("#payed2").click(function(){
var Scheme=$('.Scheme').val();
window.location.href = Scheme+"://0&back";
}); */
$("#payed").click(function() {
var orderno=$('.orderno').val();
var device=$('.device').val();
var Scheme=$('.Scheme').val();
var user_token = $('.user_token').val();
var game_id = $('.game_id').val();
$.ajax({
type: "post",
url: "/sdk.php/Spend/order_status",
dataType: "json",
data: {
'orderno' : orderno,
'user_token' : user_token,
'game_id' : game_id,
},
success: function(r) {
var u = navigator.userAgent;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
var isSafari = u.indexOf('Safari') > -1 || u.indexOf('safari') > -1; //android终端
if (r.type == "deposit") {
if (r.payStatus == '1') {
// 提示支付成功
$("#paytype").html("支付成功");
if (!isAndroid) {
if (isSafari) {
window.location.href = Scheme+"://1";
} else {
$("#toast").show();
setTimeout(function(){
window.location.href = r.url;
},2000)
}
/* try {
window.webkit.messageHandlers.exchangeResult.postMessage(1);
} catch(err) {
window.location.href = Scheme+"://1";
} */
}
} else {
// 提示支付失败
$("#paytype").html("支付失败");
if (!isAndroid) {
if (isSafari) {
window.location.href = Scheme+"://0";
} else {
$("#toast").show();
setTimeout(function(){
window.location.href = r.url;
},2000)
}
/* try {
window.webkit.messageHandlers.exchangeResult.postMessage(0);
// window.location.href = r.url;
} catch(err) {
window.location.href = Scheme+"://0";
} */
}
}
if (isAndroid) {
$("#toast").show();
setTimeout(function(){
window.location.href = r.url;
},2000)
}
}
if (r.type == "spend") {
if (r.payStatus == '1') {
if (isAndroid) {
window.txyxsdk.getPayResult('succeed');
} else {
try {
window.webkit.messageHandlers.exchangeResult.postMessage(1);
} catch(err) {
window.location.href = Scheme+"://1&back";
}
}
} else {
if (isAndroid) {
window.txyxsdk.getPayResult('fail');
} else {
try {
window.webkit.messageHandlers.exchangeResult.postMessage(0);
} catch(err) {
window.location.href = Scheme+"://0&back";
}
}
}
}
}
});
});
$('#alipay').on('click',function() {
var that = $(this);
var url = $.trim(that.attr('data-url'));
if ($(".aliapp").val() == 1) {
if ($('#sdk_version').val() == 0) {
var u = navigator.userAgent;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
if (isAndroid) {
window.txyxsdk.getZFBPay(url);
} else {
window.webkit.messageHandlers.noticeAppResult.postMessage(url);
}
} else if ($('#sdk_version').val() == 1) {
window.txyxsdk.getZFBPay(url);
} else {
window.webkit.messageHandlers.noticeAppResult.postMessage(url);
}
} else {
window.location.href = url;
}
return false;
});
});
</script>
</html>

@ -76,6 +76,17 @@
<img src="__IMG__/pay_way/dagou1.png" alt="">
</div>
</if>
<if condition="C('yeepay.status') eq 1 and C('yeepay.shortcut') eq 1">
</if>
<div class="payment_rest_way way_btn" data-type="shorcut" data-url="{:U('Shortcut/yee_pay', array('user_id'=>$user_id,'game_id'=>I('game_id'),'user_token'=>I('user_token'),'code'=>0,'type'=>'platform', 'price' => $money, 'api_ver' => 2))}">
<div>
<img src="__IMG__/pay_way/xianshang.png" alt="">
<span>易宝支付</span>
</div>
<img src="__IMG__/pay_way/dagou1.png" alt="">
</div>
</div>
</div>
<!-- <div class="payment_rest_btn">其他支付方式</div> -->
@ -161,6 +172,17 @@
<img src="__IMG__/pay_way/dagou1.png" alt="">
</div>
</if>
<if condition="C('yeepay.status') eq 1 and C('yeepay.shortcut') eq 1">
</if>
<div class="payment_rest_way way_btn" data-type="shorcut" data-url="{:U('Shortcut/yee_pay', array('user_id'=>$user_id,'game_id'=>I('game_id'),'user_token'=>I('user_token'),'code'=>0,'type'=>'platform', 'price' => $money, 'api_ver' => 2))}">
<div>
<img src="__IMG__/pay_way/xianshang.png" alt="">
<span>易宝支付</span>
</div>
<img src="__IMG__/pay_way/dagou1.png" alt="">
</div>
</div>
</div>
<!-- 供上下滑动延长 -->
@ -288,8 +310,27 @@
}
//快捷支付
function shorcut(){
flag = false;
window.location.href =payurl;
$.ajax({
type: "GET",
dataType: "json",
url: payurl,
data: {
},
success: function (r) {
flag = false;
if (r.code == 200) {
window.location.href = r.url;
} else {
$(".tipmsg").html(result.msg);
$(".msgdialog").show();
}
}
});
// flag = false;
// window.location.href =payurl;
}
$(".payment_rest_btn").click(function(){
$(".payment_rest_btn").hide();

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

@ -0,0 +1,146 @@
<?php
namespace Org\YeepaySDK;
require_once("lib/YopRequest.php");
require_once("lib/YopClient3.php");
require_once("lib/Util/YopSignUtils.php");
use Think\Exception;
use Qiniu\json_decode;
use Think\Log;
class Yeepay
{
public function yee_pay($data) {
if (!$data['orderId'] || !$data['orderAmount'] || !$data['notifyUrl'] || !$data['goodsParamExt'] || !$data['paymentParamExt']) {
return -2; // 必传参数有误
}
include 'conf.php';
$appKey = $data['appKey'];
$privateKey = $data['privateKey'];
$parentMerchantNo = $data['parentMerchantNo'];
$merchantNo = $data['merchantNo'];
$request = new \YopRequest($appKey, $privateKey);
$request->addParam("parentMerchantNo", $parentMerchantNo);
$request->addParam("merchantNo", $merchantNo);
$request->addParam("orderId", $data['orderId']);
$request->addParam("orderAmount", $data['orderAmount']);
$request->addParam("timeoutExpress", $data['timeoutExpress'] ?? '');
$request->addParam("requestDate", $data['requestDate'] ?? date('Y-m-d H:i:s'));
$request->addParam("redirectUrl", $data['redirectUrl'] ?? '');
$request->addParam("notifyUrl", $data['notifyUrl']);
$request->addParam("goodsParamExt", $data['goodsParamExt']);
$request->addParam("paymentParamExt", $data['paymentParamExt']);
$request->addParam("industryParamExt", $data['industryParamExt'] ?? '');
$request->addParam("memo", $data['memo'] ?? '');
$request->addParam("riskParamExt", $data['riskParamExt'] ?? '');
$request->addParam("csUrl", $data['csUrl'] ?? '');
$request->addParam("fundProcessType", $data['fundProcessType'] ?? 'REAL_TIME');
$request->addParam("divideDetail", $data['divideDetail'] ?? '');
$request->addParam("divideNotifyUrl", $data['divideNotifyUrl'] ?? '');
$response = \YopClient3::post("/rest/v1.0/std/trade/order", $request);
if($response->validSign != 1){
echo "签名验证失败!\n";
return -1; // 签名验证失败
}
//取得返回结果
$data = $this->object_array($response);
$token=$data['result']['token'];
$cashter = array(
"merchantNo" => $merchantNo ,
"token" => $token,
"timestamp" => time(),
"directPayType" => $data['directPayType'] ?? 'YJZF',
"cardType" => $data['cardType'] ?? '',
"userNo" => $data['userNo'] ?? '',
"userType" => $data['userType'] ?? '',
"ext" => $data['ext'] ?? '',
);
// var_dump($data);
$getUrl = $this->getUrl($cashter, $privateKey);
$getUrl=str_replace("&timestamp","&amp;timestamp",$getUrl);
$url = "https://cash.yeepay.com/cashier/std?" . $getUrl;
// echo $url;
return array('url' => $url, 'data' => $data);
}
private function getString($response){
$str="";
foreach ($response as $key => $value) {
$str .= $key . "=" . $value . "&";
}
$getSign = substr($str, 0, strlen($str) - 1);
return $getSign;
}
private function getUrl($response,$private_key)
{
$content= $this->getString($response);
$sign = \YopSignUtils::signRsa($content,$private_key);
$url=$content."&sign=".$sign;
return $url;
}
private function object_array($array) {
if(is_object($array)) {
$array = (array)$array;
} if(is_array($array)) {
foreach($array as $key=>$value) {
$array[$key] = $this->object_array($value);
}
}
return $array;
}
public function getBank($data) {
if (!$data['bankCardNo']) {
return -2; // 必传参数有误
}
include 'conf.php';
$request = new \YopRequest($appKey, $private_key);
$request->addParam("bankCardNo", $data['bankCardNo']);
$response = \YopClient3::post("/rest/v1.0/sys/merchant/query-bank-card-bin-info", $request);
if($response->validSign != 1){
echo "签名验证失败!\n";
return -1; // 签名验证失败
}
//取得返回结果
$data = $this->object_array($response);
var_dump($data);die;
$token=$data['result']['token'];
$cashter = array(
"merchantNo" => $merchantNo ,
"token" => $token,
"timestamp" => time(),
"directPayType" => $data['directPayType'] ?? '',
"cardType" => $data['cardType'] ?? '',
"userNo" => $data['userNo'] ?? '',
"userType" => $data['userType'] ?? '',
"ext" => $data['ext'] ?? '',
);
// var_dump($data);
$getUrl = $this->getUrl($cashter, $private_key);
$getUrl=str_replace("&timestamp","&amp;timestamp",$getUrl);
$url = "https://cash.yeepay.com/cashier/std?" . $getUrl;
echo $url;
return array('url' => $url, 'data' => $data);
}
}

@ -0,0 +1,10 @@
<?php
$appKey="OPR:10000466938";
$merchantNo="10000466938";
$parentMerchantNo="10000466938";
$yop_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6p0XWjscY+gsyqKRhw9MeLsEmhFdBRhT2emOck/F1Omw38ZWhJxh9kDfs5HzFJMrVozgU+SJFDONxs8UB0wMILKRmqfLcfClG9MyCNuJkkfm0HFQv1hRGdOvZPXj3Bckuwa7FrEXBRYUhK7vJ40afumspthmse6bs6mZxNn/mALZ2X07uznOrrc2rk41Y2HftduxZw6T4EmtWuN2x4CZ8gwSyPAW5ZzZJLQ6tZDojBK4GZTAGhnn3bg5bBsBlw2+FLkCQBuDsJVsFPiGh/b6K/+zGTvWyUcu+LUj2MejYQELDO3i2vQXVDk7lVi2/TcUYefvIcssnzsfCfjaorxsuwIDAQAB";
$private_key = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDKLgI+64mmJdNg1TwlCPBnNH3b3qfw2TdHVc2uDd4LTyQI8nRr0heFhhdj0OZi6agqekIyzAH/XmO9PdLrTi4YXJXOfiO/dYwKA6gSktRe6FKY4C2WzX1yA4fGfqJMV7RYVoL6In50Hur6rGnavNSQZqbiDJOgy5yokJ14Mey1iMqqqWvADtKN9SqxtbyIxYD/jj/6qLWwmu88wSwSaGdO3wNFgzajsHgRJe9G9IhD0zr5d72HvJGoedq7VaPn3jhIszcPQE6oqbXAddZRGKBehA4WSCjLEl87XH33zZPrxrQlBTHVVGzfxjbB4QvYz0hlEoWh1ntxeDHTfgyhdPQpAgMBAAECggEATmxMSLW6Xe08McpkmwT9ozq0Oy4BvKW1EIGS15nfcEmRc7sAN7Z1k0BxIDGuu91gcqGbvfJuL+0gCQ7LGqTnsmFvZnp9SU3CNTw33ISBxhKdv1jtthodN7Vw3CjQsYYvmThtc7Mfk9FOWk+4e7VVSnHW98XjGbMBIE2AF1heNgeZ40ubdgzuz9+4g4pphjWncPpwcaMfsDZm3JtFyvUp0+LME0CmUqrxvONZAkpFR/PyejGHnIh3ptHzhe/VjNcuIC4PphkCNBakCBCrtohTy0YeeWfDAUTAO4tPXF/JUhlxjPuqR6rpQY/0uQdMAtTpiWHVJar7eGdK81QnuuOFRQKBgQDrklUPM0pkvGG/wREa0bgUI+ki+1/wv7O8X94/8onomJqPpkD8z4hv/Lev/wD5gDcgmgLC36u/XDuhFfVNOmw4eUWenU6pzonroEjhi91AKcRRfzDfOfWg3wPm1J9WQOn5A033tNRydCpVcX/Ot4qDbKcAwLiPNPXXMTn4LUQE/wKBgQDbtmE0KS/kSfjscWJOqwv1XbxckipkxncqIbdiSdU+DzaLd+Vuaco7TLQJRFp7S7WJW4Tz6KBX2UiA7O7ezXY9PwlgXxXiZDDtneXNAqk7DNxmTTZHrF2C7qdU98klppCFiFx9bysGY6lFWofWmg3Pu5IiPqO3iLRPTvZgQOE+1wKBgQC9SCgmfYzyIlfcjtIinY5uSGiEnjz5od9WpiVbdpOPHEdc0zZ2rH6xlPs3ZAuxbm9dN8KuOLC0ovSau50Nv7rDKdZh234gfP9fH7xP1mUhsC25Why30MdnyqpE6GVbFe+qERitx1PI30RAwWDzhZC7hystNK1XDDPZBAnTOvPjmwKBgDFuujX7IkxRnFDOPdkHQNyGp2+Ib0NXJ85x4YmapQCeeZ4tbpBF+vsWidcf6t+crA5oaeRarWC2gUqIhEHapkSnXxuwqQLTmfKMOPzEIYEoppnZu2Gq1Ss1OK60RSxUamWwxWZvUZXRbG8vLCrLZFodkIZl433SowbI9EO5tTPnAoGAJRsy1z95Q1GPkKrFtKivkxZy1k7zJXjM0VWDc7lT9fBnoeGUyt+vuq+lC5i2aiWKJK7pe8MM9QFDGlWPnly+J8jbyMfm99k5oJtCWDfF0or1pAQ4mw0kjL9TvDVXdojgYA+rxSMQ09hwsYukQ4bblrwfBUmRjLN5WibcRzIW5ZA=";
?>

@ -0,0 +1,43 @@
<?php
/**
* Created by PhpStorm.
* User: wilson
* Date: 16/7/7
* Time: 11:07
*/
abstract class AESEncrypter{
/**
* 算法,另外还有192和256两种长度
*/
const CIPHER = MCRYPT_RIJNDAEL_128;
/**
* 模式
*/
const MODE = 'AES-128-ECB';
/**
* 加密
* @param string $str 需加密的字符串
* @param string $key 密钥
* @return type
*/
static public function encode( $str, $key){
return base64_encode(openssl_encrypt($str,self::MODE,base64_decode($key),OPENSSL_RAW_DATA));
}
/**
* 解密
* @param type $str
* @param type $key
* @return type
*/
static public function decode( $str, $key ){
return openssl_decrypt(base64_decode($str),self::MODE,base64_decode($key),OPENSSL_RAW_DATA);
}
}

@ -0,0 +1,39 @@
<?php
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2016 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
/**
* Encode and decode data into Base64 Url Safe.
*/
abstract class Base64Url
{
/**
* @param string $data The data to encode
* @param bool $use_padding If true, the "=" padding at end of the encoded value are kept, else it is removed
*
* @return string The data encoded
*/
public static function encode($data, $use_padding = false)
{
$encoded = strtr(base64_encode($data), '+/', '-_');
return true === $use_padding ? $encoded : rtrim($encoded, '=');
}
/**
* @param string $data The data to decode
*
* @return string The data decoded
*/
public static function decode($data)
{
return base64_decode(strtr($data, '-_', '+/'));
}
}

@ -0,0 +1,48 @@
<?php
/**
* Created by PhpStorm.
* User: wilson
* Date: 16/7/7
* Time: 16:21
*/
abstract class BlowfishEncrypter{
/**
* 算法,另外还有192和256两种长度
*/
const CIPHER = MCRYPT_BLOWFISH;
/**
* 模式
*/
const MODE = MCRYPT_MODE_CFB;
/**
* 加密
* @param string $str 需加密的字符串
* @param string $key 密钥
* @return type
*/
static public function encode( $str, $key){
echo $str;
echo "123456789";
echo "<br>";
echo $key;
$md5Key = md5($key);
return base64_encode(mcrypt_encrypt(self::CIPHER, substr($md5Key,0,16), $str, self::MODE, substr($md5Key,0,8)));
}
/**
* 解密
* @param type $str
* @param type $key
* @return type
*/
static public function decode( $str, $key ){
$md5Key = md5($key);
return mcrypt_decrypt(self::CIPHER, substr($md5Key,0,16),base64_decode($str), self::MODE, substr($md5Key,0,8));
}
}

@ -0,0 +1,126 @@
<?php
require_once("HttpUtils.php");
error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE);
define("LANGS", "php");
define("VERSION", "3.2.11");
define("USERAGENT", LANGS."/".VERSION."/".PHP_OS."/".$_SERVER ['SERVER_SOFTWARE']."/Zend Framework/".zend_version()."/".PHP_VERSION."/".$_SERVER['HTTP_ACCEPT_LANGUAGE']."/");
abstract class HTTPRequest{
/**
* 加密
* @param string $str 需加密的字符串
* @param string $key 密钥
* @param string $CIPHER 算法
* @param string $MODE 模式
* @return type
*/
static public function curl_request($url, $request){
$curl = curl_init();
curl_setopt($curl, CURLOPT_USERAGENT, USERAGENT);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HEADER, 1);
//curl_setopt($curl, CURLOPT_NOBODY, 0);
curl_setopt($curl, CURLOPT_TIMEOUT, $request->readTimeout);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $request->connectTimeout);
$TLS = substr($url, 0, 8) == "https://" ? true : false;
if($TLS) {
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
}
$request->encoding();
$headerArray=array();
if($request->headers!=null) {
foreach ($request->headers as $key => $value) {
array_push($headerArray, $key.":".$value);
}
}
array_push($headerArray, "x-yop-sdk-langs:".LANGS);
array_push($headerArray, "x-yop-sdk-version:".VERSION);
array_push($headerArray, "x-yop-request-id:".$request->requestId);
if($request->jsonParam!=null) {
array_push($headerArray,'Content-Type: application/json; charset=utf-8',
'Content-Length: ' . strlen($request->jsonParam));
}
curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
//curl_setopt($curl, CURLINFO_HEADER_OUT, );
//var_dump($request);
//var_dump($request->httpMethod);
if("POST"==$request->httpMethod) {
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 1);
if($request->jsonParam!=null) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $request->jsonParam);
} else {
$fields=$request->paramMap;
if($request->fileMap){
foreach($request->fileMap as $fileParam=>$fileName) {
//$file_name = str_replace("%2F", "/",$post["_file"]);
//var_dump($fileParam);
//var_dump($fileName);
//var_dump($file_name);
// 从php5.5开始,反对使用"@"前缀方式上传,可以使用CURLFile替代;
// 据说php5.6开始移除了"@"前缀上传的方式
if (class_exists('CURLFile')) {
// 禁用"@"上传方法,这样就可以安全的传输"@"开头的参数值
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
$file = new CURLFile($fileName);
} else {
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
$file = "@{$fileName}";
}
$fields [$fileParam] = $file;
}
curl_setopt($curl, CURLOPT_INFILESIZE, $request->config->maxUploadLimit);
curl_setopt($curl, CURLOPT_BUFFERSIZE, 128);
}
curl_setopt($curl, CURLOPT_POSTFIELDS, $fields);
}
} else {
curl_setopt($curl, CURLOPT_URL, $url);
}
$data = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if (curl_errno($curl)) {
return curl_error($curl);
}
$info['code'] = $httpCode;
if(true){
list($header, $body) = explode("\r\n\r\n", $data, 2);
$headers = explode("\r\n", $header);
$headList = array();
foreach ($headers as $head) {
$value = explode(':', $head);
$headList[$value[0]] = $value[1];
}
$bodys = explode("\r\n", $body);
foreach ($bodys as $body) {
$value = explode(':', $body);
$headList[$value[0]] = $value[1];
}
$info['header'] = $headList;
// print_r($headList);
// echo '----------<br>';
$info['content'] = $body;
// print_r($body);
return $info;
}else{
$info['content'] = $data;
}
curl_close($curl);
return $data;
}
}

@ -0,0 +1,72 @@
<?php
/**
* Created by PhpStorm.
* User: yp-tc-7176
* Date: 17/7/16
* Time: 20:28
*/
require_once("StringBuilder.php");
abstract class HttpUtils
{
/**
* Normalize a string for use in url path. The algorithm is:
* <p>
* <p>
* <ol>
* <li>Normalize the string</li>
* <li>replace all "%2F" with "/"</li>
* <li>replace all "//" with "/%2F"</li>
* </ol>
* <p>
* <p>
* object key can contain arbitrary characters, which may result double slash in the url path. Apache http
* client will replace "//" in the path with a single '/', which makes the object key incorrect. Thus we replace
* "//" with "/%2F" here.
*
* @param path the path string to normalize.
* @return the normalized path string.
* @see #normalize(String)
*/
public static function normalizePath($path)
{
return str_replace("%2F", "/",HttpUtils::normalize($path));
}
/**
* @param $value
* @return string
*/
public static function normalize($value)
{
return rawurlencode($value);
}
public static function startsWith($haystack, $needle) {
// search backwards starting from haystack length characters from the end
return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE;
}
public static function endsWith($haystack, $needle) {
// search forward starting from end minus needle length characters
return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== FALSE);
}
/**
* @param $path
* @return string
*/
public static function getCanonicalURIPath($path)
{
if ($path == null) {
return "/";
} else if (HttpUtils::startsWith($path,'/')) {
return HttpUtils::normalizePath($path);
} else {
return "/" + HttpUtils::normalizePath($path);
}
}
}

@ -0,0 +1,53 @@
<?php
/**
* Created by PhpStorm.
* User: yp-tc-7176
* Date: 17/7/17
* Time: 11:42
*/
class StringBuilder
{
const LINE="<br/>";
protected $list= array('');
public function __construct( $str=NULL)
{
array_push($this->list,$str);
}
public function Append($str)
{
array_push($this->list,$str);
return $this;
}
public function AppendLine($str)
{
array_push($this->list,$str.self::LINE);
return $this;
}
public function AppendFormat($str, $args)
{
array_push($this->list, sprintf($str,$args));
return $this;
}
public function ToString()
{
return implode("",$this->list);
}
public function __destruct()
{
unset($this->list);
}
}

@ -0,0 +1,23 @@
<?php
/**
* Created by PhpStorm.
* User: yp-tc-7176
* Date: 17/7/16
* Time: 20:12
*/
abstract class StringUtils
{
static function isBlank($field)
{
if ($field == '') {
return false;
} else {
return true;
}
}
}

@ -0,0 +1,216 @@
<?php
require_once("Base64Url.php");
require_once("AESEncrypter.php");
abstract class YopSignUtils{
/**
* 签名生成算法
* @param array $params API调用的请求参数集合的关联数组不包含sign参数
* @param array $ignoreParamNames 忽略的参数数组
* @param String $secret 密钥
* @param String $algName 加密算法
*
md2
md4
md5
sha1
sha256
sha384
sha512
ripemd128
ripemd160
ripemd256
ripemd320
whirlpool
*
* @return string 返回参数签名值
*/
static function sign($params, $ignoreParamNames='', $secret, $algName='sha256',$debug=false){
$str = ''; //待签名字符串
//先将参数以其参数名的字典序升序进行排序
$requestparams = $params;
ksort($requestparams);
//遍历排序后的参数数组中的每一个key/value对
foreach ($requestparams as $k => $v) {
//查看Key 是否为忽略参数
if(!in_array($k,$ignoreParamNames)){
//为key/value对生成一个keyvalue格式的字符串并拼接到待签名字符串后面
//value不为空,则进行加密
if (!($v === NULL)) {
$str .= "$k$v";
}
}
}
//将签名密钥拼接到签名字符串两头
$str = $secret.$str.$secret;
//通过指定算法生成sing
$signValue = hash($algName,$str);
if ($debug) {
print_r($YopConfig);
var_dump("algName=".$algName);
var_dump("str=".$str);
var_dump("signValue=".$signValue);
}
return $signValue;
}
/**
* 签名验证算法
* @param array $result API调用的请求参数集合的关联数组不包含sign参数
* @param String $secret 密钥
* @param String $algName 加密算法
* @param String $sign 签名值
* @return string 返回签名是否正确 0 - 如果两个字符串相等
*/
static function isValidResult($result, $secret, $algName,$sign){
// var_dump($result);
// $string=json_encode($result,true);
// $string=json_decode($string,true);
// var_dump($string);
$Str="";
foreach ($result as $k=>$v){
$Str .= strlen($Str) == 0 ? "" : "&";
$Str.=$k."=".$v;
}
$newString = $secret.$Str.$secret;
// echo $newString;
if(strcasecmp($sign,hash($algName,$newString))==0){
return true;
}else{
return false;
}
}
static function decrypt($source,$private_Key, $public_Key)
{
$private_key = "-----BEGIN RSA PRIVATE KEY-----\n" .
wordwrap($private_Key, 64, "\n", true) .
"\n-----END RSA PRIVATE KEY-----";
extension_loaded('openssl') or die('php需要openssl扩展支持');
/* 提取私钥 */
$privateKey = openssl_get_privatekey($private_key);
($privateKey) or die('密钥不可用');
//分解参数
$args = explode('$', $source);
if (count($args) != 4) {
die('source invalid : ');
}
$encryptedRandomKeyToBase64 = $args[0];
$encryptedDataToBase64 = $args[1];
$symmetricEncryptAlg = $args[2];
$digestAlg = $args[3];
//用私钥对随机密钥进行解密
openssl_private_decrypt(Base64Url::decode($encryptedRandomKeyToBase64), $randomKey, $privateKey);
openssl_free_key($privateKey);
$encryptedData = openssl_decrypt(Base64Url::decode($encryptedDataToBase64), "AES-128-ECB", $randomKey, OPENSSL_RAW_DATA);
//分解参数
$signToBase64=substr(strrchr($encryptedData,'$'),1);
$sourceData = substr($encryptedData,0,strlen($encryptedData)-strlen($signToBase64)-1);
$public_key = "-----BEGIN PUBLIC KEY-----\n" .
wordwrap($public_Key, 64, "\n", true) .
"\n-----END PUBLIC KEY-----";
$publicKey = openssl_pkey_get_public($public_key);
$res = openssl_verify($sourceData,Base64Url::decode($signToBase64), $publicKey,$digestAlg); //验证
openssl_free_key($publicKey);
//输出验证结果1验证成功0验证失败
if ($res == 1) {
return $sourceData;
} else {
Die("verifySign fail!");
}
}
static function signRsa($source,$private_Key)
{
$private_key = "-----BEGIN RSA PRIVATE KEY-----\n" .
wordwrap($private_Key, 64, "\n", true) .
"\n-----END RSA PRIVATE KEY-----";
extension_loaded('openssl') or die('php需要openssl扩展支持');
/* 提取私钥 */
$privateKey = openssl_get_privatekey($private_key);
($privateKey) or die('密钥不可用');
openssl_sign($source, $encode_data, $privateKey, "SHA256");
openssl_free_key($privateKey);
$signToBase64 = Base64Url::encode($encode_data);
$signToBase64 .= '$SHA256';
return $signToBase64;
}
static function getPrivateKey($filepath,$password)
{
//var_dump($filepath);
$pkcs12 = file_get_contents($filepath);
openssl_pkcs12_read($pkcs12, $certs, $password);
$prikeyid = $certs['pkey']; //私钥
$prikeyid = str_replace('-----BEGIN RSA PRIVATE KEY-----','',$prikeyid);
$prikeyid = str_replace('-----END RSA PRIVATE KEY-----','',$prikeyid);
$prikeyid = preg_replace("/(\r\n|\n|\r|\t)/i", '', $prikeyid);
return $prikeyid;
}
static function verifySign($source,$sign, $public_Key)
{
$content=strstr($source, '&sign', TRUE);
$public_key = "-----BEGIN PUBLIC KEY-----\n" .
wordwrap($public_Key, 64, "\n", true) .
"\n-----END PUBLIC KEY-----";
$publicKey = openssl_pkey_get_public($public_key);
$res = openssl_verify($content,Base64Url::decode($sign), $public_key,'SHA256'); //验证
openssl_free_key($publicKey);
//输出验证结果1验证成功0验证失败
if ($res == 1) {
return true;
} else {
Die("verifySign fail!");
}
}
}

@ -0,0 +1,189 @@
<?php
require_once("YopRequest.php");
require_once("YopResponse.php");
require_once("YopError.php");
require_once ("YopConfig.php");
require_once ("Util/BlowfishEncrypter.php");
require_once("Util/YopSignUtils.php");
require_once("Util/HttpRequest.php");
class YopClient{
public function __construct(){
}
public function __set($name, $value){
$this->$name = $value;
}
public function __get($name){
return $this->$name;
}
static public function get($methodOrUri, $YopRequest){
$content = self::getForString($methodOrUri, $YopRequest);
$response = self::handleResult($YopRequest, $content);
return $response;
}
static public function getForString($methodOrUri, $YopRequest){
$YopRequest->httpMethod = "GET";
$serverUrl = self::richRequest($methodOrUri, $YopRequest);
self::signAndEncrypt($YopRequest);
$serverUrl .= (strpos($serverUrl,'?') === false ?'?':'&') . $YopRequest->toQueryString();
$response = HttpRequest::curl_request($serverUrl, $YopRequest);
return $response;
}
static public function post($methodOrUri, $YopRequest){
$content = self::postForString($methodOrUri, $YopRequest);
$response = self::handleResult($YopRequest, $content);
return $response;
}
static public function postForString($methodOrUri, $YopRequest){
$YopRequest->httpMethod = "POST";
$serverUrl = self::richRequest($methodOrUri, $YopRequest);
self::signAndEncrypt($YopRequest);
$response = HttpRequest::curl_request($serverUrl, $YopRequest);
return $response;
}
static public function upload($methodOrUri, $YopRequest){
$content = self::uploadForString($methodOrUri, $YopRequest);
$response = self::handleResult($YopRequest, $content);
return $response;
}
static public function uploadForString($methodOrUri, $YopRequest){
$YopRequest->httpMethod = "POST";
$serverUrl = self::richRequest($methodOrUri, $YopRequest);
self::signAndEncrypt($YopRequest);
$response = HttpRequest::curl_request($serverUrl, $YopRequest);
return $response;
}
static public function signAndEncrypt($YopRequest){
if(empty($YopRequest->method)){
error_log("method must be specified");
}
if(empty($YopRequest->secretKey)){
error_log("secretKey must be specified");
}
$appKey =$YopRequest->appKey;
if(empty($appKey)){
$appKey = $YopRequest->config->CUSTOMER_NO;
}
if(empty($appKey)){
error_log("appKey 与 customerNo 不能同时为空");
}
$toSignParamMap = array_merge($YopRequest->paramMap,array("v"=>$YopRequest->version, "method"=>$YopRequest->method));
$signValue=YopSignUtils::sign($toSignParamMap,$YopRequest->ignoreSignParams,$YopRequest->secretKey,$YopRequest->signAlg,$YopRequest->config->debug);
date_default_timezone_set('PRC');
$dataTime = new DateTime();
$timestamp = $dataTime->format(DateTime::ISO8601); // Works the same since const ISO8601 = "Y-m-d\TH:i:sO"
$headers = array();
$headers['x-yop-appkey'] = $appKey;
$headers['x-yop-date'] = $timestamp;
$headers['Authorization'] = "YOP-HMAC-AES128 " . $signValue;
$YopRequest->headers=$headers;
if($YopRequest->encrypt) {
YopClient::encrypt($YopRequest);
}
}
#加密
static public function encrypt($YopRequest){
$builder = $YopRequest->paramMap;
// var_dump($builder);
/*foreach ($builder as $k => $v){
if($YopRequest->Config->ispublicedKey($k)){
unset($builder[$k]);
}else{
}
}*/
if(!empty($builder)){
$encryptBody="";
foreach ($builder as $k=>$v){
$encryptBody .= strlen($encryptBody) == 0 ? "" : "&";
$encryptBody .= $k."=".urlencode($v);
}
}
if(empty($encryptBody)){
$YopRequest->addParam($YopRequest->Config->ENCRYPT,true);
}else{
if(!empty($YopRequest->{$YopRequest->Config->APP_KEY})){
$encrypt = AESEncrypter::encode($encryptBody,$YopRequest->secretKey);
$YopRequest->addParam($YopRequest->Config->ENCRYPT,$encrypt);
}else{
$encrypt=BlowfishEncrypter::encode($encryptBody,$YopRequest->secretKey);
$YopRequest->addParam($YopRequest->Config->ENCRYPT,$encrypt);
}
}
}
#解密
static public function decrypt($YopRequest, $strResult){
if(!empty($strResult) && $YopRequest->{$YopRequest->Config->ENCRYPT}){
if(!empty($YopRequest->{$YopRequest->Config->APP_KEY})){
$strResult = AESEncrypter::decode($strResult, $YopRequest->secretKey);
}else{
$strResult = BlowfishEncrypter::decode($strResult, $YopRequest->secretKey);
}
}
return $strResult;
}
static public function richRequest($methodOrUri, $YopRequest){
if(strpos($methodOrUri, $YopRequest->config->serverRoot)){
$methodOrUri = substr($methodOrUri,strlen($YopRequest->config->serverRoot)+1);
}
$serverUrl = $YopRequest->serverRoot;
$serverUrl .= $methodOrUri;
preg_match('@/rest/v([^/]+)/@i', $methodOrUri, $version);
if(!empty($version)){
$version = $version[1];
if(!empty($version)){
$YopRequest->setVersion($version);
}
}
$YopRequest->setMethod($methodOrUri);
return $serverUrl;
}
static public function handleResult($YopRequest, $content){
// print_r($content);
if ($YopRequest->downRequest) {
return $content;
}
$response = new YopResponse();
$jsoncontent = json_decode($content['content']);
$response->requestId = $YopRequest->requestId;
$response->requestId = $YopRequest->requestId;
if(!empty($jsoncontent->result)){
$response->state = "SUCCESS";
$response->result = $jsoncontent->result;
$response->sign = $jsoncontent->sign;
} else {
$response->state = "FAILURE";
//$response->error = new YopError();
$response->error->code = $jsoncontent->code;
$response->error->message = $jsoncontent->message;
$response->sign = $jsoncontent->sign;
}
// $response->validSign = YopSignUtils::isValidResult($jsoncontent->result, $YopRequest->secretKey, $YopRequest->signAlg,$jsoncontent->sign);
return $response;
}
}

@ -0,0 +1,8 @@
<?php
require_once("YopRsaClient.php");
class YopClient3 extends YopRsaClient
{
}

@ -0,0 +1,86 @@
<?php
class YopConfig{
//app config
public $serverRoot = "https://openapi.yeepay.com/yop-center";
public $yosServerRoot = "https://yos.yeepay.com/yop-center";
//public $serverRoot = "http://ycetest.yeepay.com:30228/yop-center";
//public $yosServerRoot = "http://ycetest.yeepay.com:30228/yop-center";
//public $serverRoot = "http://127.0.0.1:8064/yop-center";
//public $yosServerRoot = "http://127.0.0.1:8064/yop-center";
public $appKey;
public $aesSecretKey;
public $hmacSecretKey;
public $debug=false;
public $connectTimeout=30;
public $readTimeout=60;
public $maxUploadLimit=4096000;
//签名算法
public $ALG_AES = "AES";
public $ALG_SHA = "SHA";
public $ALG_SHA1 = "SHA1";
// 保护参数
public $ENCODING = "UTF-8";
public $SUCCESS = "SUCCESS";
public $CALLBACK = "callback";
// 方法的默认参数名
public $METHOD = "method";
// 会话id默认参数名
public $SESSION_ID = "sessionId";
// 应用键的默认参数名 ;
public $APP_KEY = "appKey";
// 服务版本号的默认参数名
public $VERSION = "v";
// 签名的默认参数名
public $SIGN = "sign";
// 加密报文key
public $ENCRYPT = "encrypt";
// 商户编号
public $CUSTOMER_NO = "customerNo";
// 返回结果是否签名
public $SIGN_RETURN = "signRet";
// 时间戳
public $TIMESTAMP = "ts";
public $publicED_KEY=array();
public $publickey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6p0XWjscY+gsyqKRhw9MeLsEmhFdBRhT2emOck/F1Omw38ZWhJxh9kDfs5HzFJMrVozgU+SJFDONxs8UB0wMILKRmqfLcfClG9MyCNuJkkfm0HFQv1hRGdOvZPXj3Bckuwa7FrEXBRYUhK7vJ40afumspthmse6bs6mZxNn/mALZ2X07uznOrrc2rk41Y2HftduxZw6T4EmtWuN2x4CZ8gwSyPAW5ZzZJLQ6tZDojBK4GZTAGhnn3bg5bBsBlw2+FLkCQBuDsJVsFPiGh/b6K/+zGTvWyUcu+LUj2MejYQELDO3i2vQXVDk7lVi2/TcUYefvIcssnzsfCfjaorxsuwIDAQAB";
public function __construct(){
array_push($this->publicED_KEY,$this->APP_KEY, $this->VERSION, $this->SIGN, $this->METHOD, $this->SESSION_ID, $this->CUSTOMER_NO,$this->ENCRYPT, "", false);
}
public function __set($name, $value){
$this->$name = $value;
}
public function __get($name){
return $this->$name;
}
public function getSecret(){
if(!empty($this->appKey) && strlen($this->appKey) > 0){
return $this->aesSecretKey;
}else{
return $this->hmacSecretKey;
}
}
public function ispublicedKey($key){
if(in_array($key,$this->publicED_KEY)){
return true;
}
return false;
}
}

@ -0,0 +1,17 @@
<?php
class YopError {
public $code;
public $message;
public $subCode;
public $subMessage;
public function __set($name, $value){
$this->$name = $value;
}
public function __get($name){
return $this->$name;
}
}

@ -0,0 +1,198 @@
<?php
require_once("YopConfig.php");
class YopRequest {
public $config;
public $httpMethod;
public $method;
public $version = "2.0";
public $signAlg = "sha256";
/**
* 商户编号,易宝商户可不注册开放应用(获取appKey)也可直接调用API
*/
public $customerNo;
public $headers = array();
public $paramMap = array();
public $fileMap = array();
public $jsonParam;
public $ignoreSignParams = array('sign');
public $requestId;
/**
* 连接超时时间
*/
public $connectTimeout = 30000;
/**
* 读取返回结果超时
*/
public $readTimeout = 60000;
/**
* 可支持不同请求使用不同的appKey及secretKey
*/
public $appKey;
/**
* 报文是否加密,如果请求加密,则响应也加密,需做解密处理
*/
public $encrypt = false;
/**
* 可支持不同请求使用不同的appKey及secretKey,secretKey只用于本地签名不会被提交
*/
public $secretKey;
/**
* 可支持不同请求使用不同的appKey及secretKey、serverRoot,secretKey只用于本地签名不会被提交
*/
public $yopPublicKey;
/**
* 业务结果是否签名,默认不签名
*/
public $signRet = false;
/**
/**
* 可支持不同请求使用不同的appKey及secretKey、serverRoot,secretKey只用于本地签名不会被提交
*/
public $serverRoot;
public $downrequest;
public function __set($name, $value){
$this->$name = $value;
}
public function __get($name){
return $this->$name;
}
public function setSignRet($signRet) {
$signRetStr = $signRet?'true':'false';
$this->signRet = $signRet;
$this->addParam($this->Config->SIGN_RETURN, $signRetStr);
}
public function setSignAlg($signAlg) {
$this->signAlg = $signAlg;
}
public function setEncrypt($encrypt) {
$this->encrypt = $encrypt;
}
public function setVersion($version) {
$this->version = $version;
}
public function setMethod($method) {
$this->method = $method;
}
public function __construct($appKey='', $secretKey=null, $yopPublicKey=null,$serverRoot=null) { //定义构造函数
$this->config = new YopConfig();
$this->requestId = YopRequest::uuid();
if(!empty($appKey)){
$this->appKey = $appKey;
}
else{
$this->appKey = $this->config->appKey;
}
if(!empty($secretKey)){
$this->secretKey = $secretKey;
}
else{
$this->secretKey = $this->config->getSecret();
}
if(!empty($yopPublicKey)){
$this->yopPublicKey = $yopPublicKey;
}
else{
$this->yopPublicKey = $this->config->publickey;
}
if(!empty($serverRoot)){
$this->serverRoot = $serverRoot;
}
else{
$this->serverRoot = $this->config->serverRoot;
}
}
public function addParam($key,$values){
if ("_file"==$key) {
YopRequest::addFile($key,$values);
} else {
$addParam = array($key=>$values);
$this->paramMap = array_merge($this->paramMap,$addParam);
}
}
public function addFile($key,$values){
$this->ignoreSignParams = array_push($this->ignoreSignParams,$key);
$addFile = array($key=>$values);
$this->fileMap = array_merge($this->fileMap,$addFile);
}
public function removeParam($key){
foreach ($this->paramMap as $k => $v){
if($key == $k){
unset($this->paramMap[$k]);
}
}
}
public function getParam($key){
return $this->paramMap[$key];
}
public function setJsonParam($jsonParam){
$this->jsonParam = $jsonParam;
}
public function getJsonParam(){
return $this->jsonParam;
}
public function encoding(){
foreach ($this->paramMap as $k=>$v){
$this->paramMap[$k] = urlencode($v);
}
}
/**
* 将参数转换成k=v拼接的形式
*/
public function toQueryString(){
$StrQuery="";
foreach ($this->paramMap as $k=>$v){
$StrQuery .= strlen($StrQuery) == 0 ? "" : "&";
$StrQuery.=$k."=".urlencode($v);
}
return $StrQuery;
}
private function uuid($namespace = '') {
static $guid = '';
$uid = uniqid("", true);
$data = $_SERVER['REQUEST_TIME'];
$hash = hash('ripemd128', $uid . $data);
$guid = $namespace .
substr($uid, 0, 14) .
substr($uid, 15, 24) .
substr($hash, 0, 10) .
'';
return $guid;
}
}

@ -0,0 +1,36 @@
<?php
class YopResponse{
/**
* 状态(SUCCESS/FAILURE)
*/
public $state;
/**
* 业务结果非简单类型解析后为LinkedHashMap
*/
public $result;
/**
* 结果签名签名算法为Request指定算法示例SHA(<secret>stringResult<secret>)
*/
public $sign;
/**
* 错误信息
*/
public $error;
public $requestId;
public function __set($name, $value){
$this->$name = $value;
}
public function __get($name){
return $this->$name;
}
}

@ -0,0 +1,387 @@
<?php
require_once("YopRequest.php");
require_once("YopResponse.php");
require_once("YopError.php");
require_once("Util/HttpRequest.php");
require_once("Util/StringUtils.php");
require_once("Util/HttpUtils.php");
require_once("Util/Base64Url.php");
class YopRsaClient
{
public function __construct()
{
}
/**
* @param $methodOrUri
* @param $YopRequest
* @param $encode_data
* @return array
*/
public static function SignRsaParameter($methodOrUri, $YopRequest)
{
$appKey = $YopRequest->{$YopRequest->config->APP_KEY};
if (empty($appKey)) {
$appKey = $YopRequest->config->CUSTOMER_NO;
$YopRequest->removeParam($YopRequest->config->APP_KEY);
}
if (empty($appKey)) {
error_log("appKey 与 customerNo 不能同时为空");
}
date_default_timezone_set('PRC');
$dataTime = new DateTime();
$timestamp = $dataTime->format(DateTime::ISO8601); // Works the same since const ISO8601 = "Y-m-d\TH:i:sO"
$headers = array();
$headers['x-yop-appkey'] = $YopRequest->appKey;
$headers['x-yop-request-id'] = $YopRequest->requestId;
$protocolVersion = "yop-auth-v2";
$EXPIRED_SECONDS = "1800";
$authString = $protocolVersion . "/" . $appKey . "/" . $timestamp . "/" . $EXPIRED_SECONDS;
$headersToSignSet = array();
array_push($headersToSignSet, "x-yop-request-id");
$appKey = $YopRequest->{$YopRequest->config->APP_KEY};
if (!StringUtils::isBlank($YopRequest->config->CUSTOMER_NO)) {
$headers['x-yop-customerid'] = $appKey;
array_push($headersToSignSet, "x-yop-customerid");
}
// Formatting the URL with signing protocol.
$canonicalURI = HttpUtils::getCanonicalURIPath($methodOrUri);
// Formatting the query string with signing protocol.
$canonicalQueryString = YopRsaClient::getCanonicalQueryString($YopRequest, true);
// Sorted the headers should be signed from the request.
$headersToSign = YopRsaClient::getHeadersToSign($headers, $headersToSignSet);
// Formatting the headers from the request based on signing protocol.
$canonicalHeader = YopRsaClient::getCanonicalHeaders($headersToSign);
$signedHeaders = "";
if ($headersToSignSet != null) {
foreach ($headersToSign as $key => $value) {
$signedHeaders .= strlen($signedHeaders) == 0 ? "" : ";";
$signedHeaders .= $key;
}
$signedHeaders = strtolower($signedHeaders);
}
$canonicalRequest = $authString . "\n" . $YopRequest->httpMethod . "\n" . $canonicalURI . "\n" . $canonicalQueryString . "\n" . $canonicalHeader;
// Signing the canonical request using key with sha-256 algorithm.
if (empty($YopRequest->secretKey)) {
error_log("secretKey must be specified");
}
extension_loaded('openssl') or die('php需要openssl扩展支持');
$private_key = $YopRequest->secretKey;
$private_key = "-----BEGIN RSA PRIVATE KEY-----\n" .
wordwrap($private_key, 64, "\n", true) .
"\n-----END RSA PRIVATE KEY-----";
$privateKey = openssl_pkey_get_private($private_key);// 提取私钥
($privateKey) or die('密钥不可用');
$signToBase64 = "";
// echo "tyuiop".$canonicalRequest;
openssl_sign($canonicalRequest, $encode_data, $privateKey, "SHA256");
openssl_free_key($privateKey);
$signToBase64 = Base64Url::encode($encode_data);
$signToBase64 .= '$SHA256';
$headers['Authorization'] = "YOP-RSA2048-SHA256 " . $protocolVersion . "/" . $appKey . "/" . $timestamp . "/" . $EXPIRED_SECONDS . "/" . $signedHeaders . "/" . $signToBase64;
if ($YopRequest->config->debug) {
var_dump("authString=" . $authString);
var_dump("canonicalURI=" . $canonicalURI);
var_dump("canonicalQueryString=" . $canonicalQueryString);
var_dump("canonicalHeader=" . $canonicalHeader);
var_dump("canonicalRequest=" . $canonicalRequest);
var_dump("signToBase64=" . $signToBase64);
}
$YopRequest->headers = $headers;
}
public function __set($name, $value)
{
$this->$name = $value;
}
public function __get($name)
{
return $this->$name;
}
public static function get($methodOrUri, $YopRequest)
{
$content = YopRsaClient::getForString($methodOrUri, $YopRequest);
$response = YopRsaClient::handleRsaResult($YopRequest, $content);
return $response;
}
public static function getForString($methodOrUri, $YopRequest)
{
$YopRequest->httpMethod = "GET";
$serverUrl = YopRsaClient::richRequest($methodOrUri, $YopRequest);
$serverUrl .= (strpos($serverUrl, '?') === false ? '?' : '&') . $YopRequest->toQueryString();
self::SignRsaParameter($methodOrUri, $YopRequest);
$response = HttpRequest::curl_request($serverUrl, $YopRequest);
return $response;
}
public static function post($methodOrUri, $YopRequest)
{
$content = YopRsaClient::postString($methodOrUri, $YopRequest);
$response = YopRsaClient::handleRsaResult($YopRequest, $content);
return $response;
}
/**
* @param $methodOrUri
* @param $YopRequest
* @return type
*/
public static function postString($methodOrUri, $YopRequest)
{
$YopRequest->httpMethod = "POST";
$serverUrl = YopRsaClient::richRequest($methodOrUri, $YopRequest);
self::SignRsaParameter($methodOrUri, $YopRequest);
$response = HttpRequest::curl_request($serverUrl, $YopRequest);
return $response;
}
/**
* @param $YopRequest
* @param $forSignature
* @return string
*/
public static function getCanonicalQueryString($YopRequest, $forSignature)
{
if (!empty($YopRequest->jsonParam)) {
return "";
}
$ArrayList = array();
$StrQuery = "";
foreach ($YopRequest->paramMap as $k => $v) {
if ($forSignature && strcasecmp($k, "Authorization") == 0) {
continue;
}
array_push($ArrayList, $k . "=" . rawurlencode($v));
}
sort($ArrayList);
foreach ($ArrayList as $kv) {
$StrQuery .= strlen($StrQuery) == 0 ? "" : "&";
$StrQuery .= $kv;
}
return $StrQuery;
}
/**
* @param $headers
* @param $headersToSign
* @return arry
*/
public static function getHeadersToSign($headers, $headersToSign)
{
$ret = array();
if ($headersToSign != null) {
$tempSet = array();
foreach ($headersToSign as $header) {
array_push($tempSet, strtolower(trim($header)));
}
$headersToSign = $tempSet;
}
foreach ($headers as $key => $value) {
if ($value != null && !empty($value)) {
if (($headersToSign == null && isDefaultHeaderToSign($key)) || ($headersToSign != null && in_array(strtolower($key), $headersToSign) && $key != "Authorization")) {
$ret[$key] = $value;
}
}
}
ksort($ret);
return $ret;
}
/**
* @param $header
* @return bool
*/
public static function isDefaultHeaderToSign($header)
{
$header = strtolower(trim($header));
$defaultHeadersToSign = array();
array_push($defaultHeadersToSign, "host");
array_push($defaultHeadersToSign, "content-type");
return strpos($header, "x-yop-") == 0 || in_array($defaultHeadersToSign, $header);
}
/**
* @param $headers
* @return string
*/
public static function getCanonicalHeaders($headers)
{
if (empty($headers)) {
return "";
}
$headerStrings = array();
foreach ($headers as $key => $value) {
if ($key == null) {
continue;
}
if ($value == null) {
$value = "";
}
$key = HttpUtils::normalize(strtolower(trim($key)));
$value = HttpUtils::normalize(trim($value));
array_push($headerStrings, $key . ':' . $value);
}
sort($headerStrings);
$StrQuery = "";
foreach ($headerStrings as $kv) {
$StrQuery .= strlen($StrQuery) == 0 ? "" : "\n";
$StrQuery .= $kv;
}
return $StrQuery;
}
/**
* @param $methodOrUri
* @param $YopRequest
* @return YopResponse
*/
public static function upload($methodOrUri, $YopRequest)
{
$content = self::uploadForString($methodOrUri, $YopRequest);
$response = self::handleRsaResult($YopRequest, $content);
return $response;
}
public static function uploadForString($methodOrUri, $YopRequest)
{
$YopRequest->httpMethod = "POST";
$serverUrl = self::richRequest($methodOrUri, $YopRequest);
self::SignRsaParameter($methodOrUri, $YopRequest);
$response = HttpRequest::curl_request($serverUrl, $YopRequest);
return $response;
}
static public function richRequest($methodOrUri, $YopRequest)
{
if (strpos($methodOrUri, $YopRequest->config->serverRoot)) {
$methodOrUri = substr($methodOrUri, strlen($YopRequest->config->serverRoot) + 1);
}
$serverUrl = $YopRequest->serverRoot;
$serverUrl .= $methodOrUri;
preg_match('@/rest/v([^/]+)/@i', $methodOrUri, $version);
if (!empty($version)) {
$version = $version[1];
if (!empty($version)) {
$YopRequest->setVersion($version);
}
}
$YopRequest->setMethod($methodOrUri);
return $serverUrl;
}
static public function handleRsaResult($YopRequest, $content)
{
$sign = trim($content['header']['x-yop-sign']);
$signStr = $content['content'];
$signStr = self::trimall($signStr);
$response = new YopResponse();
$jsoncontent = json_decode($content['content']);
if(empty($sign)){
return $content['content'];
}
if (!empty($jsoncontent->result)) {
$response->state = "SUCCESS";
$response->result = $jsoncontent->result;
$response->requestId = $YopRequest->requestId;
// $signStr=$jsoncontent->result;
} else {
$response->state = "FAILURE";
$response->requestId = $jsoncontent->requestId;
$response->error->code = $jsoncontent->code;
$response->error->message = $jsoncontent->message;
$response->error->subCode = $jsoncontent->subCode;
$response->error->subMessage = $jsoncontent->subMessage;
// $signStr = $content['content'];
}
$response->validSign = YopRsaClient::isValidRsaResult($signStr, $sign, $YopRequest->yopPublicKey);
return $response;
}
//去空格换行符
static public function trimall($str){
$qian=array(" "," ","\t","\n","\r");
return str_replace($qian, '', $str);
}
#header sign 验签
public static function isValidRsaResult($result, $sign, $public_key)
{
// $result=json_encode($result,320);
$str = "";
if ($result == null || empty($result)) {
$str = "";
} else {
$str .= trim($result);
}
;
$public_key = "-----BEGIN PUBLIC KEY-----\n" .
wordwrap($public_key, 64, "\n", true) .
"\n-----END PUBLIC KEY-----";
$pu_key = openssl_pkey_get_public($public_key);
// $str=str_replace("\\","",str_replace("\\n","",$str));
$str= self::trimall($str);
$str= trim($str, '"');
$res = openssl_verify($str,Base64Url::decode($sign), $pu_key,"SHA256"); //验证
openssl_free_key($pu_key);
if ($res == 1) {
// echo "验签成功";
return true;
} else {
echo "验签失败";
return false;
}
}
}
Loading…
Cancel
Save