/var/www/hkosl.com/littleark/webadmin/models/PayEase.php


1
2
3
4
5
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
<?php

class PayEase{

    public 
$v_mid;
    protected 
$payment_method;
    protected 
$key;
    protected 
$invoice;

    protected 
$user_payment_endpoint     = array(
        
"UNIONPAY"                         => "https://pay.yizhifubj.com/prs/user_payment.checkit",
        
// "CREDITCARD"                     => "https://pay.yizhifubj.com/customer/i18n/i18n_raw_order3_0.jsp",
        // "PAYEASE"                         => "https://pay.yizhifubj.com/customer/gb/pay_bank.jsp",
        // "DOKU"                             => "https://pay.yizhifubj.com/customer/gb/pay_bank.jsp",
        // "DOKU_CREDITCARD"                => "https://pay.yizhifubj.com/customer/gb/pay_bank.jsp",
    
);

    protected 
$mer_payment_submit_utf8_sandbox_endpoint "http://210.73.90.235/merchant/virement/mer_payment_submit_utf8.jsp";
    protected 
$mer_payment_submit_utf8_production_endpoint "http://pay.yizhifubj.com/merchant/virement/mer_payment_submit_utf8.jsp";
    protected 
$mer_payment_submit_utf8_endpoint;

    protected 
$mer_payment_status_utf8_sandbox_endpoint "http://210.73.90.235/merchant/virement/mer_payment_status_utf8.jsp";
    protected 
$mer_payment_status_utf8_production_endpoint "http://pay.yizhifubj.com/merchant/virement/mer_payment_status_utf8.jsp";
    protected 
$mer_payment_status_utf8_endpoint;

    protected 
$order_ack_oid_list_endpoint "https://api.yizhifubj.com/merchant/order/order_ack_oid_list.jsp";
    protected 
$ref_ack_day_list_endpoint   "https://api.yizhifubj.com/merchant/refund/ref_ack_day_list.jsp";
    protected 
$ref_ack_oid_list_endpoint   "https://api.yizhifubj.com/merchant/refund/ref_ack_oid_list.jsp";
    protected 
$ref_ack_submit_endpoint        "https://api.yizhifubj.com/merchant/refund/ref_ack_submit.jsp";

    protected 
$ref_version "1.1";

    
// public function __construct($v_mid="7007", $key="test"){
    
public function __construct($v_mid=null$key=null){
        
$this->v_mid MasterSetting::get('PAYEASE_MID');
        
$this->key MasterSetting::get('PAYEASE_KEY');

        
$this->mer_payment_submit_utf8_endpoint $this->mer_payment_submit_utf8_production_endpoint;
        
$this->mer_payment_status_utf8_endpoint $this->mer_payment_status_utf8_production_endpoint;

        
$this->payment_currency "CNY";
    }

    public function 
sandbox(){
        
$this->v_mid "7007";
        
$this->key "test";
        
$this->mer_payment_submit_utf8_endpoint $this->mer_payment_submit_utf8_sandbox_endpoint;
        
$this->mer_payment_status_utf8_endpoint $this->mer_payment_status_utf8_sandbox_endpoint;
        return 
$this;
    }

    public function 
setInvoice(Invoice $invoice){
        
$this->invoice $invoice;
    }

    public function 
paymentParam($payment_method){
        
// vdump(__FUNCTION__);
        
global $site_info;
        
$v_moneytype get_currency_price($v_amountnull$this->payment_currency3);
        
$v_ymd date('Ymd');
        
// vdump($this->invoice->amount, $_SESSION);
        
$v_amount get_currency_price($this->invoice->amountnull$this->payment_currency3);
        
$v_rcvname $this->v_mid;
        
$v_url "{$site_info['url']}/payease/ReviewOrder.php?return=1&payment_method={$payment_method}";
        
$v_oid "{$v_ymd}-{$this->v_mid}-" date('His') . substr(sha1($this->invoice->order_id), 44);

        
$args = [
            
"v_version"        => $this->ref_version,
            
"v_mid"            => $this->v_mid,
            
"v_oid"            => $v_oid,
            
"v_rcvname"        => $v_rcvname,
            
"v_rcvaddr"        => $this->v_mid,
            
"v_rcvtel"        => $this->v_mid,
            
"v_rcvpost"        => $this->v_mid,
            
"v_amount"        => number_format($v_amount2'.'''),
            
"v_ymd"            => $v_ymd,
            
"v_orderstatus"    => 1,
            
"v_ordername"    => $this->v_mid,
            
"v_moneytype"    => self::getMoneytype($this->payment_currency),
            
"v_ordip"        => get_client_ip(),
            
// "v_ordip"        => '223.255.164.254',
            
"v_url"            => $v_url,
            
"v_producttype"    => _("Sales"),
            
"v_userref"        => _($this->invoice->customer->code),

            
"v_language"    => $_SESSION['langcode'] == "sc" "zh" "en",
            
"v_pmode"        => $pmode,

        ];

        
$args array_merge($args$this->generateCustomizedData($args$payment_method));
        
$args array_merge($args$this->generateSignature($args));

        
ApiLog::create([
            
'type' => get_class($this),
            
'endpoint' => $this->user_payment_endpoint[$payment_method],
            
'request' => $args,
        ]);

        return [
            
"action" => $this->user_payment_endpoint[$payment_method],
            
"method" => "POST",
            
"args"   => $args,
        ];
    }

    protected function 
generateCustomizedData($args$payment_method){
        
$data = [];
        switch (
strtoupper($payment_method)) {
            case 
'B2B':
            case 
'UNIONPAY':
                
// get invoice item
                
$supplierInvoices = [];
                foreach (
$this->invoice->invoiceItems as $invoiceItem) {
                    
$proProductSku $invoiceItem->invoiceable->orderItem->proProductSku;

                    
$itemunitprice number_format($invoiceItem->discounted_price $invoiceItem->invoiceable->orderItem->quantity2'.''');


                    
$supplier_payease_submerchant_number $invoiceItem->supplier->getSettlementSubmerchantNumber();
                    if (
$supplier_payease_submerchant_number) {
                        
$supplierInvoices[$invoiceItem->supplier->payease_sub_merchant_number]['code']                        = $supplierInvoices[$invoiceItem->supplier->payease_sub_merchant_number]['code'] ?: "{$this->invoice->id}{$invoiceItem->supplier->code}";
                        
$supplierInvoices[$invoiceItem->supplier->payease_sub_merchant_number]['payease_sub_merchant_number'] = $invoiceItem->supplier->payease_sub_merchant_number;
                        
$supplierInvoices[$invoiceItem->supplier->payease_sub_merchant_number]['items'][]                     = [
                            
'product_desc' => str_replace(['_''$'], '-'$proProductSku->getProductName/*$langcode*/)),
                            
// 'product_desc' => "货物贸易",
                            
'unitprice'    => get_currency_price($itemunitpricenull$this->payment_currency3),
                            
'quantity'     => $invoiceItem->invoiceable->orderItem->quantity,
                            
'total'        => get_currency_price($itemunitpricenull$this->payment_currency3) * $invoiceItem->invoiceable->orderItem->quantity,
                        ];
                    }
                }

                
/*
                子商户号,子订单编码  ,子订单金额,产品名称_产品单价_产品数量$产品名称_产品单价_产品数量||
                3       ,YYZITGQZX  ,1.50       ,%E7%94%9C%E8%AF%9D%E6%A2%85250%E5%85%8B_1.50_1||
                9       ,UMDSBAJYH  ,0.50       ,+Farinha+lactea+_0.50_1

                1,test12345,0.03,货物贸易_0.01_1\$货物贸易1_0.02_1||
                2,test00002,0.02,货物贸易2_0.01_1\$货物贸易3_0.01_1||
                3,test54321,0.01,货物贸易5_0.01_1
                 */
                
foreach ($supplierInvoices as $payease_sub_merchant_number => $supplierInvoice) {
                    
$supplierInvoiceData        = [];
                    
$supplierInvoiceTotalAmount 0;
                    foreach (
$supplierInvoice['items'] as $supplierInvoiceItem) {
                        
$supplierInvoiceTotalAmount += $supplierInvoiceItem['total'];
                        
$supplierInvoiceData[] = implode('_', [
                            
urldecode($supplierInvoiceItem['product_desc']),
                            
number_format($supplierInvoiceItem['unitprice'], 2'.'''),
                            
$supplierInvoiceItem['quantity'],
                        ]);
                    }
                    
$data['v_merdata'] .= "{$payease_sub_merchant_number},{$supplierInvoice['code']}," number_format($supplierInvoiceTotalAmount2'.''') . "," implode('$'$supplierInvoiceData) . "||";
                }

                
$data["v_merdata"] = substr_replace($data["v_merdata"], "", -2);

// TODO: delete testing data
// $data["v_merdata"] = "1,test12345,0.03,货物贸易_0.01_1\$货物贸易1_0.02_1||2,test00002,0.02,货物贸易2_0.01_1\$货物贸易3_0.01_1||3,test54321,0.01,货物贸易5_0.01_1";
// $data["v_merdata2"] = "1,test12345,26.00,货物贸易_26.00_1";
// $data["v_amount"] = "26.00";

// check v_amount = sum of number_format($supplierInvoiceTotalAmount, 2, '.', '')
$tempSupplierInvoiceCode date('His') . 'SP';
$data["v_merdata"] = "1,{$tempSupplierInvoiceCode},{$args['v_amount']},货物贸易_{$args['v_amount']}_1";

                
$customer $this->invoice->customer;
                
$data['v_idtype']    = _h("00");
                
$data['v_idnumber']  = _h("000000000000000");
                
$data['v_idname']    = _h($customer->first_name);
                
$data['v_idcountry'] = _h(self::getIdcountry($customer->country_code)) ?: "000";
                
$data['v_idaddress'] = _h($customer->addresses()->where('address_type''BILLING_ADDRESS')->first()->decrypt()->toString2());
                
// vdump($customer->country_code, $data);
                
break;

            default:
                throw new 
Exception("Error Processing Payment Type: {$payment_method}"1);
        }

        return 
$data;
    }

    protected function 
generateSignature($args){
        
// vdump(__FUNCTION__, "{$args['v_moneytype']}{$args['v_ymd']}{$args['v_amount']}{$args['v_rcvname']}{$args['v_oid']}{$args['v_mid']}{$args['v_url']}", $args['v_moneytype']); exit;
        
return [
            
"v_md5info"        => $this->_msg_sign("{$args['v_moneytype']}{$args['v_ymd']}{$args['v_amount']}{$args['v_rcvname']}{$args['v_oid']}{$args['v_mid']}{$args['v_url']}"),
            
"v_mac"         => $this->_msg_sign("{$args['v_oid']}{$args['pmode']}{$args['v_amount']}{$args['v_rcvname']}{$args['v_oid']}{$args['v_mid']}{$args['v_url']}"),
        ];
    }

    public function 
paymentVerify($v_oid$v_pmode$v_pstatus$v_pstring$v_md5info$v_amount$v_moneytype$v_md5money$v_sign, &$messages=array()){

        
$result true;
        
$messages = [];

        
// verify md5info
        
if (!$this->_msg_validate("{$v_oid}{$v_pstatus}{$v_pstring}{$v_pmode}"$v_md5info)){
            
$result false;
            
$messages[] = "INVALID MD5INFO";
        }

        if (!
$this->_msg_validate("{$v_amount}{$v_moneytype}"$v_md5money)){
            
$result false;
            
$messages[] = "INVALID MD5MONEY";
        }

        switch (
$v_pstatus) {
            case 
'1':
            case 
'11':
                
$messages[] = "PENDING";
                
// $result = true;
                
break;
            case 
'20':
                
$messages[] = "ACCEPTED";
                
// $result = true;
                
break;
            case 
'30':
            default:
                
$messages[] = "DECLINED";
                
$result false;
                break;
        }
        if(
$v_pstring){
            
$messages[] = $v_pstring;
        }

        
ApiLog::create([
            
'type' => get_class($this),
            
'endpoint' => __FUNCTION__,
            
'request' => func_get_args(),
            
'response' => json_encode($messages),
            
'status' => $v_pstatus,
            
'is_success' => $result,
        ]);

        return 
$result;
    }

    public function 
order_ack_oid_list($v_oid$v_version=null){
        
$param = array(
            
'v_mid' => $this->v_mid,
            
'v_oid' => $v_oid,
            
'v_mac' => $this->_msg_sign("{$this->v_mid}{$v_oid}"),
        );
        return 
self::_excute($this->order_ack_oid_list_endpoint$param);
    }

    public function 
ref_ack_day_list($v_ymd$v_version=null){
        
$param = array(
            
'v_mid' => $this->v_mid,
            
'v_ymd' => $v_ymd,
            
'v_version' => $v_version ?: $this->ref_version,
            
'v_mac' => $this->_msg_sign("{$this->v_mid}{$v_ymd}"),
        );
        return 
self::_excute($this->ref_ack_day_list_endpoint$param);
    }

    public function 
ref_ack_oid_list($v_oid$v_version=null){
        
$param = array(
            
'v_mid' => $this->v_mid,
            
'v_oid' => $v_oid,
            
'v_version' => $v_version ?: $this->ref_version,
            
'v_mac' => $this->_msg_sign("{$this->v_mid}{$v_oid}"),
        );
        return 
self::_excute($this->ref_ack_oid_list_endpoint$param);
    }

    public function 
ref_ack_submit($v_oid$v_refamount$v_refreason$v_refoprt){
        
$param = array(
            
'v_mid' => $this->v_mid,
            
'v_oid' => $v_oid,
            
'v_refamount' => $v_refamount,
            
'v_refreason' => $v_refreason,
            
'v_refoprt' => $v_refoprt,
            
'v_version' => $v_version ?: $this->ref_version,
            
'v_mac' => $this->_msg_sign("{$this->v_mid}{$v_oid}{$v_refamount}{$v_refoprt}"),
        );
        return 
self::_excute($this->ref_ack_submit_endpoint$param);
    }

    protected function 
_msg_sign($content){
        
// vdump(__FUNCTION__, $content, $this->key);
        
return hash_hmac('md5'$content$this->key);
    }

    protected function 
_msg_validate($content$signature){
        
// vdump(__FUNCTION__, $content, $this->_msg_sign($content, $signature));
        
return $signature == $this->_msg_sign($content$signature);
    }

    public function 
mer_payment_submit_utf8($v_data$v_version=null){
        
$param = array(
            
'v_mid' => $this->v_mid,
            
'v_data' => $v_data,
            
'v_mac' => $this->_msg_sign(_("{$this->v_mid}{$v_data}")),
            
'v_version' => $v_version ?: $this->ref_version,
        );
        
// vdump($this->v_mid, $v_data, $this->_msg_sign("{$this->v_mid}{$v_data}"), $this->_msg_sign(_("{$this->v_mid}{$v_data}")));
        
return self::_excute($this->mer_payment_submit_utf8_endpoint$param);
    }

    protected static function 
_excute($endpoint$param){
        
$ch curl_init();
        
curl_setopt($chCURLOPT_URL$endpoint);
        
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
        
curl_setopt($chCURLOPT_POSTtrue);
        
curl_setopt($chCURLOPT_POSTFIELDShttp_build_query($param));
        
$output curl_exec($ch);
        
curl_close($ch);

        
$output self::_xml_pre_process($output);
        
$output_obj simplexml_load_string($output);

        
ApiLog::create([
            
'type' => get_class($this),
            
'endpoint' => $endpoint,
            
'request' => $param,
            
'response' => $output,
            
'status' => $output_obj->status ?: $output_obj->pstatus,
        ]);

        return 
$output_obj;
    }

    
/**
     * @param  gb2312 xml
     * @return utf8 xml
     */
    
protected static function _xml_pre_process($xml){
        
$xml str_replace("&""&amp;"$xml);
        return 
mb_convert_encoding($xml"HTML-ENTITIES""gb2312");
    }

    public static function 
resolve_pstatus($v_pstatus$translation_fn=false){
        switch (
$v_pstatus) {
            case 
'':
            case 
'0':
                
$description "Not paid";
                break;
            case 
'1':
            case 
'11'// 预授权成功
            
case '20':
                
$description "Paid";
                break;
            case 
'2':
                
$description "Not confirmed Payment";
                break;
            case 
'3':
            case 
'30':
                
$description "Rejected Payment";
                break;
            case 
'4':
                
$description "Refund in progress";
                break;
            case 
'5':
                
$description "Refund is completed";
                break;
            case 
'6':
                
$description "Fail to refund";
                break;
            case 
'7':
                
$description "Card holder rejected";
                break;
            case 
'8':
                
$description "Abnormal refund";
                break;
            default:
                
$description "Invalid";
                break;
        }
        return 
is_callable($translation_fn) ? call_user_func($translation_fn$description) : $description;
    }

    public static 
$money_types = [
        
'CNY' => '0',
        
'USD' => '1',
        
'EUR' => '2',
        
'GBP' => '3',
        
'JPY' => '4',
        
'KRW' => '5',
        
'AUD' => '6',
        
'RUB' => '7',
        
'CHF' => '8',
        
'HKD' => '9',
        
'SGD' => '10',
        
'MOP' => '11',
        
'IDR' => '16',
    ];

    public static 
$idcountry_codes = [
        
'AUS' => '036',
        
'KHM' => '116',
        
'CHN' => '156',
        
'HKG' => '344',
        
'IDN' => '360',
        
'KOR' => '410',
    ];

    public static function 
getMoneytype($currency_code)
    {
        if (
array_key_exists($currency_codeself::$money_types)) {
            return 
self::$money_types[$currency_code];
        }
        throw new 
Exception("Currency {$currency_code} not found"1);
    }

    public static function 
getIdcountry($country_code)
    {
        if (
array_key_exists($country_codeself::$idcountry_codes)) {
            return 
self::$idcountry_codes[$country_code];
        }
        return 
false;
        
// throw new Exception("Country {$currency_code} not found", 1);
    
}

    public static function 
getCurrencyCode($find_money_type)
    {
        foreach(
self::$money_types as $currency_code => $money_type) {
            if(
$find_money_type==$money_type) {
                return 
$currency_code;
            }
        }
        throw new 
Exception("MoneyType {$find_money_type} not found"1);
    }

    public static function 
trimData($data$maxlength=100)
    {
        if (
strlen($data) > 100) {
            return 
substr($data0$maxlength-3) . "...";
        }
        return 
$data;
    }

}