code
stringlengths
15
9.96M
docstring
stringlengths
1
10.1k
func_name
stringlengths
1
124
language
stringclasses
1 value
repo
stringlengths
7
63
path
stringlengths
6
186
url
stringlengths
50
236
license
stringclasses
4 values
public function getCouponCost($base_product_total, $coupon_code) { $dc_discount = Yii::$service->cart->coupon->getDiscount($coupon_code, $base_product_total); return $dc_discount; }
得到优惠券的折扣金额. @return array , example: [ 'baseCost' => $base_discount_cost, # 基础货币的优惠金额 'currCost' => $curr_discount_cost # 当前货币的优惠金额 ]
getCouponCost
php
fecshop/yii2_fecshop
services/cart/Quote.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cart/Quote.php
BSD-3-Clause
public function setCartCoupon($coupon_code) { $cart = $this->getCart(); $cart->coupon_code = $coupon_code; $cart->save(); return true; }
@param $coupon_code | String 设置购物车的优惠券
setCartCoupon
php
fecshop/yii2_fecshop
services/cart/Quote.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cart/Quote.php
BSD-3-Clause
public function cancelCartCoupon($coupon_code) { $cart = $this->getCart(); $cart->coupon_code = null; $cart->save(); return true; }
@param $coupon_code | String 取消购物车的优惠券
cancelCartCoupon
php
fecshop/yii2_fecshop
services/cart/Quote.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cart/Quote.php
BSD-3-Clause
public function mergeCartAfterUserLogin() { if (!Yii::$app->user->isGuest) { $identity = Yii::$app->user->identity; $customer_id = $identity['id']; $email = $identity->email; $customer_firstname = $identity->firstname; $customer_lastname = $identity->lastname; $customer_cart = $this->getCartByCustomerId($customer_id); $cart_id = $this->getCartId(); if (!$customer_cart) { if ($cart_id) { $cart = $this->getCart(); if ($cart) { $cart['customer_email'] = $email; $cart['customer_id'] = $customer_id; $cart['customer_firstname'] = $customer_firstname; $cart['customer_lastname'] = $customer_lastname; $cart['customer_is_guest'] = 2; $cart->save(); } } } else { $cart = $this->getCart(); if (!$cart || !$cart_id) { $cart_id = $customer_cart['cart_id']; $this->setCartId($cart_id); } else { // 将无用户产品(当前)和 购物车中的产品(登录用户对应的购物车)进行合并。 $new_cart_id = $customer_cart['cart_id']; if ($cart['coupon_code']) { // 如果有优惠券则取消,以登录用户的购物车的优惠券为准。 Yii::$service->cart->coupon->cancelCoupon($cart['coupon_code']); } // 将当前购物车产品表的cart_id 改成 登录用户对应的cart_id if ($new_cart_id && $cart_id && ($new_cart_id != $cart_id)) { Yii::$service->cart->quoteItem->updateCartId($new_cart_id, $cart_id); // 当前的购物车删除掉 $cart->delete(); // 设置当前的cart_id $this->setCartId($new_cart_id); // 设置当前的cart $this->setCart($customer_cart); // 重新计算购物车中产品的个数 $this->computeCartInfo(); } } } } }
当用户登录账号后,将用户未登录时的购物车和用户账号中保存 的购物车信息进行合并。
mergeCartAfterUserLogin
php
fecshop/yii2_fecshop
services/cart/Quote.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cart/Quote.php
BSD-3-Clause
public function getCartByCustomerId($customer_id) { if ($customer_id) { $one = $this->_cartModel->findOne(['customer_id' => $customer_id]); if ($one['cart_id']) { return $one; } } }
@param $customer_id | int @return $this->_cartModel Object。 通过用户的customer_id,在cart表中找到对应的购物车
getCartByCustomerId
php
fecshop/yii2_fecshop
services/cart/Quote.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cart/Quote.php
BSD-3-Clause
public function getByPrimaryKey($primaryKey) { $one = $this->_couponModel->findOne($primaryKey); $primaryKey = $this->getPrimaryKey(); if ($one[$primaryKey]) { return $one; } else { return new $this->_couponModelName; } }
@param $primaryKey | Int @return Object($this->_couponModel) 通过id找到cupon的对象
getByPrimaryKey
php
fecshop/yii2_fecshop
services/cart/Coupon.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cart/Coupon.php
BSD-3-Clause
public function getCouponUsageModel($customer_id = '', $coupon_id = '') { if (!$this->_coupon_usage_model) { if (!$customer_id) { $customer_id = $this->_customer_id; } if (!$coupon_id) { $couponModel = $this->getCouponModel(); $coupon_id = isset($couponModel['coupon_id']) ? $couponModel['coupon_id'] : ''; } if ($customer_id && $coupon_id) { $one = $this->_couponUsageModel->findOne([ 'customer_id' => $customer_id, 'coupon_id' => $coupon_id, ]); if ($one['customer_id']) { $this->_coupon_usage_model = $one; } } } if ($this->_coupon_usage_model) { return $this->_coupon_usage_model; } }
@param $customer_id | Int @param $coupon_id | Int 通过customer_id 和 coupon_id得到 Coupon Usage Model.
getCouponUsageModel
php
fecshop/yii2_fecshop
services/cart/Coupon.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cart/Coupon.php
BSD-3-Clause
public function getCouponModel($coupon_code = '') { if (!$this->_coupon_model) { if (!$coupon_code) { $coupon_code = $this->_coupon_code; } if ($coupon_code) { $one = $this->_couponModel->findOne(['coupon_code' => $coupon_code]); if ($one['coupon_code']) { $this->_coupon_model = $one; } } } if ($this->_coupon_model) { return $this->_coupon_model; } }
@param $coupon_code | String 根据 coupon_code 得到 coupon model
getCouponModel
php
fecshop/yii2_fecshop
services/cart/Coupon.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cart/Coupon.php
BSD-3-Clause
public function save($one) { $time = time(); $primaryKey = $this->getPrimaryKey(); $primaryVal = isset($one[$primaryKey]) ? $one[$primaryKey] : ''; if ($primaryVal) { $model = $this->_couponModel->findOne($primaryVal); if (!$model) { Yii::$service->helper->errors->add('coupon {primaryKey} is not exist' , ['primaryKey' => $this->getPrimaryKey()] ); return; } } else { $o_one = $this->_couponModel->find() ->where(['coupon_code' =>$one['coupon_code']]) ->one(); if ($o_one[$primaryKey]) { Yii::$service->helper->errors->add('coupon_code must be unique'); return; } $model = new $this->_couponModelName; $model->created_at = time(); if (isset(Yii::$app->user)) { $user = Yii::$app->user; if (isset($user->identity)) { $identity = $user->identity; $person_id = $identity['id']; $model->created_person = $person_id; } } } $model->attributes = $one; if ($model->validate()) { $model->updated_at = time(); $model = Yii::$service->helper->ar->save($model, $one); $primaryVal = $model[$primaryKey]; return $primaryVal; } else { $errors = $model->errors; Yii::$service->helper->errors->addByModelErrors($errors); return false; } }
@param $one|array , save one data . @return int 保存coupon成功后,返回保存的id。
save
php
fecshop/yii2_fecshop
services/cart/Coupon.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cart/Coupon.php
BSD-3-Clause
protected function useCouponInit($coupon_code) { if (!$this->_useCouponInit) { // $this->_customer_id if (Yii::$app->user->isGuest) { $this->_customer_id = ''; } else { if (Yii::$app->user->identity->id) { $this->_customer_id = Yii::$app->user->identity->id; } } $this->_coupon_code = $coupon_code; $this->_useCouponInit = 1; } }
@param $coupon_code | String 优惠卷码 初始化对象变量,这个函数是在使用优惠券 和 取消优惠券的时候, 调用相应方法前,通过这个函数初始化类变量 $_useCouponInit # 是否初始化过,如果初始化过了,则不会执行 $_customer_id # 用户id $_coupon_code # 优惠卷码 $_coupon_model # 优惠券model $_coupon_usage_model # 优惠券使用次数记录model 这是一个内部函数,不对外开放。
useCouponInit
php
fecshop/yii2_fecshop
services/cart/Coupon.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cart/Coupon.php
BSD-3-Clause
protected function couponIsActive($isGetDiscount = false) { if ($this->_customer_id) { if ($couponModel = $this->getCouponModel()) { $expiration_date = $couponModel['expiration_date']; // 未过期 if ($expiration_date > time()) { if ($isGetDiscount) { return true; } $couponUsageModel = $this->getCouponUsageModel(); $times_used = 0; if ($couponUsageModel['times_used']) { $times_used = $couponUsageModel['times_used']; } $users_per_customer = $couponModel['users_per_customer']; // 次数限制 if ($times_used < $users_per_customer) { return true; } else { Yii::$service->helper->errors->add('The coupon has exceeded the maximum number of uses'); } } else { Yii::$service->helper->errors->add('coupon is expired'); } } } return false; }
@param $isGetDiscount | boolean, 是否是获取折扣信息, 1.如果值为true,说明该操作是获取cart 中的coupon的折扣操作步骤中的active判断,则只进行优惠券存在和是否过期判断,不对使用次数判断 2.如果值为false,则是add coupon操作,除了优惠券是否存在, 是否过期判断,还需要对使用次数进行判断。 查看coupon是否是可用的,如果可用,返回true,如果不可用,返回false
couponIsActive
php
fecshop/yii2_fecshop
services/cart/Coupon.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cart/Coupon.php
BSD-3-Clause
public function getDiscount($coupon_code, $dc_price) { $discount_cost = 0; $this->useCouponInit($coupon_code); if ($this->couponIsActive(true)) { $couponModel = $this->getCouponModel(); $type = $couponModel['type']; $conditions = $couponModel['conditions']; $discount = $couponModel['discount']; //echo $conditions.'##'.$dc_price;;exit; if ($conditions <= $dc_price) { if ($type == $this->coupon_type_percent) { // 百分比 $base_discount_cost = (1-$discount / 100) * $dc_price; } elseif ($type == $this->coupon_type_direct) { // 直接折扣 $base_discount_cost = $discount; } $curr_discount_cost = Yii::$service->page->currency->getCurrentCurrencyPrice($base_discount_cost); } } return [ 'baseCost' => $base_discount_cost, 'currCost' => $curr_discount_cost, ]; }
@param $coupon_code | String , coupon_code字符串 @param $dc_price | Float 总价格 根据优惠券和总价格,计算出来打折后的价格。譬如原来10元,打八折后,是8元。
getDiscount
php
fecshop/yii2_fecshop
services/cart/Coupon.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cart/Coupon.php
BSD-3-Clause
public function addCoupon($coupon_code) { $this->useCouponInit($coupon_code); if ($this->couponIsActive()) { $couponModel = $this->getCouponModel(); $type = $couponModel['type']; $conditions = $couponModel['conditions']; $discount = $couponModel['discount']; // 判断购物车金额是否满足条件 $cartProduct = Yii::$service->cart->quoteItem->getCartProductInfo(); $product_total = isset($cartProduct['product_total']) ? $cartProduct['product_total'] : 0; if ($product_total) { //var_dump($product_total); $dc_price = Yii::$service->page->currency->getBaseCurrencyPrice($product_total); if ($dc_price > $conditions) { // 更新购物侧的coupon 和优惠券的使用情况。 // 在service中不要出现事务等操作。在调用层使用。 $set_status = Yii::$service->cart->quote->setCartCoupon($coupon_code); $up_status = $this->updateCouponUse('add'); if ($set_status && $up_status) { return true; } else { Yii::$service->helper->errors->add('add coupon fail'); } } else { Yii::$service->helper->errors->add('The coupon can not be used if the product amount in the shopping cart is less than {conditions} dollars', ['conditions' => $conditions]); } } } else { Yii::$service->helper->errors->add('Coupon is not available or has expired'); } }
@param $coupon_code | String 优惠卷码 检查当前购物车中是否存在优惠券,如果存在,则覆盖当前的优惠券 如果当前购物车没有使用优惠券,则检查优惠券是否可以使用 如果优惠券可以使用,则使用优惠券进行打折。更新购物车信息。
addCoupon
php
fecshop/yii2_fecshop
services/cart/Coupon.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cart/Coupon.php
BSD-3-Clause
public function cancelCoupon($coupon_code) { $this->useCouponInit($coupon_code); if ($this->_customer_id) { $couponModel = $this->getCouponModel($coupon_code); if ($couponModel) { $up_status = $this->updateCouponUse('cancel'); $cancel_status = Yii::$service->cart->quote->cancelCartCoupon($coupon_code); if ($up_status && $cancel_status) { return true; } } } }
@param $coupon_code | String 取消优惠券
cancelCoupon
php
fecshop/yii2_fecshop
services/cart/Coupon.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cart/Coupon.php
BSD-3-Clause
public function getCustomOptionSku($item, $product) { $custom_option_arr = $item['custom_option_sku']; if ($custom_option_arr) { $product_custom_option = $product['custom_option']; $co_sku = Yii::$service->product->info->getProductCOSku($custom_option_arr, $product_custom_option); if ($co_sku) { return $co_sku; } } return ''; }
@param $item | Array , 数据格式为: [ 'product_id' => xxxxx 'qty' => 55, 'custom_option_sku' => [ 'color' => 'red', 'size' => 'L', ] ] @param $product | Product Model , 产品的model对象 $product['custom_option'] 的数据格式如下: [ "black-s-s2-s3": [ "my_color": "black", "my_size": "S", "my_size2": "S2", "my_size3": "S3", "sku": "black-s-s2-s3", "qty": NumberInt(99999), "price": 0, "image": "/2/01/20161024170457_10036.jpg" ], ] @return string 得到 custom option 部分对应的sku 当用户在产品加入购物车的时候选择了颜色尺码等属性,通过这个函数,可以得到这些属性对应的custom_option_sku的值。 如果不存在,则返回为空。
getCustomOptionSku
php
fecshop/yii2_fecshop
services/cart/Info.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cart/Info.php
BSD-3-Clause
protected function getProductSpuOptions($productOb) { $custom_option_info_arr = []; $productPrimaryKey = Yii::$service->product->getPrimaryKey(); $productAttrGroup = $productOb['attr_group']; if (isset($productOb['attr_group']) && !empty($productOb['attr_group'])) { $spuArr = Yii::$service->product->getSpuAttr($productAttrGroup); //var_dump($productOb['attr_group_info']); // mysql存储 if (isset($productOb['attr_group_info']) && is_array($productOb['attr_group_info'])) { $attr_group_info = $productOb['attr_group_info']; if (is_array($spuArr) && !empty($spuArr)) { foreach ($spuArr as $spu_attr) { if (isset($attr_group_info[$spu_attr]) && !empty($attr_group_info[$spu_attr])) { // 进行翻译。 $spu_attr_label = Yii::$service->page->translate->__($spu_attr); $spu_attr_val = Yii::$service->page->translate->__($attr_group_info[$spu_attr]); $custom_option_info_arr[$spu_attr_label] = $spu_attr_val; } } } } else { // mongodb类型 Yii::$service->product->addGroupAttrs($productAttrGroup); $productOb = Yii::$service->product->getByPrimaryKey((string) $productOb[$productPrimaryKey ]); if (is_array($spuArr) && !empty($spuArr)) { foreach ($spuArr as $spu_attr) { if (isset($productOb[$spu_attr]) && !empty($productOb[$spu_attr])) { // 进行翻译。 $spu_attr_label = Yii::$service->page->translate->__($spu_attr); $spu_attr_val = Yii::$service->page->translate->__($productOb[$spu_attr]); $custom_option_info_arr[$spu_attr_label] = $spu_attr_val; } } } } } return $custom_option_info_arr; }
@param $productOb | Object,类型:\fecshop\models\mongodb\Product 得到产品的spu对应的属性以及值。 概念 - spu options:当多个产品是同一个spu,但是不同的sku的时候,他们的产品表里面的 spu attr 的值是不同的,譬如对应鞋子,size 和 color 就是spu attr,对于同一款鞋子,他们 是同一个spu,对于尺码,颜色不同的鞋子,是不同的sku,他们的spu attr 就是 color 和 size。
getProductSpuOptions
php
fecshop/yii2_fecshop
services/cart/QuoteItem.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cart/QuoteItem.php
BSD-3-Clause
public function addOneItem($item_id) { $cart_id = Yii::$service->cart->quote->getCartId(); if ($cart_id) { $one = $this->_itemModel->find()->where([ 'cart_id' => $cart_id, 'item_id' => $item_id, ])->one(); $product_id = $one['product_id']; if ($one['item_id'] && $product_id) { $product = Yii::$service->product->getByPrimaryKey($product_id); // 检查产品满足加入购物车的条件 $checkItem = [ 'product_id' => $one['product_id'], 'custom_option_sku' => $one['custom_option_sku'], 'qty' => $one['qty'] + 1, ]; $productValidate = Yii::$service->cart->info->checkProductBeforeAdd($checkItem, $product); if (!$productValidate) { return false; } $changeQty = Yii::$service->cart->getCartQty($product['package_number'], 1); $one['qty'] = $one['qty'] + $changeQty; $one->save(); // 重新计算购物车的数量 Yii::$service->cart->quote->computeCartInfo(); $item = [ 'product_id' => $product_id, 'custom_option_sku' => $one['custom_option_sku'], 'qty' => $changeQty, 'sku' => $product['sku'], 'afterAddQty' => $one['qty'], ]; // 购物车数据加1 $this->sendTraceAddToCartInfoByApi($item); return true; } } return false; }
@param $item_id | Int , quoteItem表的id @return bool 将这个item_id对应的产品个数+1.
addOneItem
php
fecshop/yii2_fecshop
services/cart/QuoteItem.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cart/QuoteItem.php
BSD-3-Clause
public function lessOneItem($item_id) { $cart_id = Yii::$service->cart->quote->getCartId(); if ($cart_id) { $one = $this->_itemModel->find()->where([ 'cart_id' => $cart_id, 'item_id' => $item_id, ])->one(); $product_id = $one['product_id']; $product = Yii::$service->product->getByPrimaryKey($one['product_id']); $changeQty = Yii::$service->cart->getCartQty($product['package_number'], 1); $lessedQty = $one['qty'] - $changeQty; $min_sales_qty = 1; if ($product['min_sales_qty'] && $product['min_sales_qty'] >= 2) { $min_sales_qty = $product['min_sales_qty']; } if ($lessedQty < $min_sales_qty) { Yii::$service->helper->errors->add('product less buy qty is {min_sales_qty}', ['min_sales_qty' => $product['min_sales_qty']]); return false; } if ($one['item_id']) { if ($one['qty'] > 1) { $one['qty'] = $lessedQty; $one->save(); // 重新计算购物车的数量 Yii::$service->cart->quote->computeCartInfo(); return true; } } } return false; }
@param $item_id | Int , quoteItem表的id @return bool 将这个item_id对应的产品个数-1.
lessOneItem
php
fecshop/yii2_fecshop
services/cart/QuoteItem.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cart/QuoteItem.php
BSD-3-Clause
public function removeItem($item_id) { $cart_id = Yii::$service->cart->quote->getCartId(); if ($cart_id) { $one = $this->_itemModel->find()->where([ 'cart_id' => $cart_id, 'item_id' => $item_id, ])->one(); if ($one['item_id']) { $one->delete(); // 重新计算购物车的数量 Yii::$service->cart->quote->computeCartInfo(); return true; } } return false; }
@param $item_id | Int , quoteItem表的id @return bool 将这个item_id对应的产品删除
removeItem
php
fecshop/yii2_fecshop
services/cart/QuoteItem.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cart/QuoteItem.php
BSD-3-Clause
public function selectOneItem($item_id, $checked) { $cart_id = Yii::$service->cart->quote->getCartId(); if ($cart_id) { $one = $this->_itemModel->find()->where([ 'cart_id' => $cart_id, 'item_id' => $item_id, ])->one(); $product_id = $one['product_id']; if ($one['item_id'] && $product_id) { //$product = Yii::$service->product->getByPrimaryKey($product_id); //$changeQty = Yii::$service->cart->getCartQty($product['package_number'], 1); //$one['qty'] = $one['qty'] + $changeQty; if ($checked == true) { $one->active = $this->activeStatus; } else { $one->active = $this->noActiveStatus; } $one->save(); // 重新计算购物车的数量 Yii::$service->cart->quote->computeCartInfo(); return true; } } return false; }
@param $item_id | Int , quoteItem表的id @return bool 将这个item_id对应的产品个数+1.
selectOneItem
php
fecshop/yii2_fecshop
services/cart/QuoteItem.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cart/QuoteItem.php
BSD-3-Clause
public function selectAllItem($checked) { $cart_id = Yii::$service->cart->quote->getCartId(); if ($cart_id) { $active = $this->noActiveStatus; if ($checked == true) { $active = $this->activeStatus; } $updateCount = $this->_itemModel->updateAll( ['active' => $active], ['cart_id' => $cart_id] ); if ($updateCount > 0) { Yii::$service->cart->quote->computeCartInfo(); } } return true; }
@param $item_id | Int , quoteItem表的id @return bool 将这个item_id对应的产品个数+1.
selectAllItem
php
fecshop/yii2_fecshop
services/cart/QuoteItem.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cart/QuoteItem.php
BSD-3-Clause
public function removeNoActiveItemsByCartId($cart_id = '') { if (!$cart_id) { $cart_id = Yii::$service->cart->quote->getCartId(); } if ($cart_id) { $columns = $this->_itemModel->deleteAll([ 'cart_id' => $cart_id, 'active' => $this->activeStatus, ]); if ($columns > 0) { // 重新计算购物车的数量 Yii::$service->cart->quote->computeCartInfo(); return true; } } }
@param $cart_id | int 购物车id 删除购物车中的所有的active产品。对于noActive产品保留 注意:清空购物车并不是清空所有信息,仅仅是清空用户购物车中的产品。 另外,购物车的数目更改后,需要更新cart中产品个数的信息。
removeNoActiveItemsByCartId
php
fecshop/yii2_fecshop
services/cart/QuoteItem.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cart/QuoteItem.php
BSD-3-Clause
public function removeItemByCartId($cart_id = '') { if (!$cart_id) { $cart_id = Yii::$service->cart->quote->getCartId(); } if ($cart_id) { $items = $this->_itemModel->deleteAll([ 'cart_id' => $cart_id, ]); // 重新计算购物车的数量 Yii::$service->cart->quote->computeCartInfo(0); } return true; }
废弃,改为 removeNoActiveItemsByCartId(),因为购物车改为勾选下单方式。 @param $cart_id | int 购物车id 删除购物车中的所有产品。 注意:清空购物车并不是清空所有信息,仅仅是清空用户购物车中的产品。 另外,购物车的数目更改后,需要更新cart中产品个数的信息。
removeItemByCartId
php
fecshop/yii2_fecshop
services/cart/QuoteItem.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cart/QuoteItem.php
BSD-3-Clause
public function updateCartId($new_cart_id, $cart_id) { if ($cart_id && $new_cart_id) { $this->_itemModel->updateAll( ['cart_id' => $new_cart_id], // $attributes ['cart_id' => $cart_id] // $condition ); return true; } return false; }
@param $new_cart_id | int 更新后的cart_id @param $cart_id | int 更新前的cart_id 删除购物车中的所有产品。 这里仅仅更改cart表的cart_id, 而不会做其他任何事情。
updateCartId
php
fecshop/yii2_fecshop
services/cart/QuoteItem.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cart/QuoteItem.php
BSD-3-Clause
public function getPrimaryKey() { return $this->_article->getPrimaryKey(); }
get artile's primary key.
getPrimaryKey
php
fecshop/yii2_fecshop
services/cms/Article.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cms/Article.php
BSD-3-Clause
public function getByPrimaryKey($primaryKey) { return $this->_article->getByPrimaryKey($primaryKey); }
get artile model by primary key.
getByPrimaryKey
php
fecshop/yii2_fecshop
services/cms/Article.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cms/Article.php
BSD-3-Clause
public function getActivePageByPrimaryKey($primaryKey) { return $this->_article->getActivePageByPrimaryKey($primaryKey); }
get active artile model by primary key.
getActivePageByPrimaryKey
php
fecshop/yii2_fecshop
services/cms/Article.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cms/Article.php
BSD-3-Clause
public function getByUrlKey($urlKey) { return $this->_article->getByUrlKey($urlKey); }
@param $urlKey | String , 对应表的url_key字段 根据url_key 查询得到article model
getByUrlKey
php
fecshop/yii2_fecshop
services/cms/Article.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cms/Article.php
BSD-3-Clause
public function getModelName() { return get_class($this->_article); }
得到category model的全名.
getModelName
php
fecshop/yii2_fecshop
services/cms/Article.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cms/Article.php
BSD-3-Clause
public function coll($filter = '') { return $this->_article->coll($filter); }
@param $filter|array get artile collection by $filter example filter: [ 'numPerPage' => 20, 'pageNum' => 1, 'orderBy' => ['_id' => SORT_DESC, 'sku' => SORT_ASC ], 'where' => [ ['>','price',1], ['<=','price',10] ['sku' => 'uk10001'], ], 'asArray' => true, ]
coll
php
fecshop/yii2_fecshop
services/cms/Article.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cms/Article.php
BSD-3-Clause
public function save($one, $originUrlKey) { return $this->_article->save($one, $originUrlKey); }
@param $one|array , save one data . @param $originUrlKey|string , article origin url key. save $data to cms model,then,add url rewrite info to system service urlrewrite.
save
php
fecshop/yii2_fecshop
services/cms/Article.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cms/Article.php
BSD-3-Clause
public function init() { parent::init(); // 从数据库配置中得到值, 设置成当前service存储,是Mysqldb 还是 Mongodb $config = Yii::$app->store->get('service_db', 'article_and_staticblock'); $this->storage = 'StaticBlockMysqldb'; if ($config == Yii::$app->store->serviceMongodbName) { $this->storage = 'StaticBlockMongodb'; } $currentService = $this->getStorageService($this); $this->_static_block = new $currentService(); }
init static block db.
init
php
fecshop/yii2_fecshop
services/cms/StaticBlock.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cms/StaticBlock.php
BSD-3-Clause
public function getByUrlKey($urlKey) { if ($urlKey) { $model = $this->_articleModel->findOne([ 'url_key' => '/'.$urlKey, 'status' =>$this->getEnableStatus(), ]); if (isset($model['url_key'])) { $model['content'] = unserialize($model['content']); $model['title'] = unserialize($model['title']); $model['meta_keywords'] = unserialize($model['meta_keywords']); $model['meta_description'] = unserialize($model['meta_description']); return $model; } } return false; }
@param $urlKey | String , 对应表的url_key字段 根据url_key 查询得到article model
getByUrlKey
php
fecshop/yii2_fecshop
services/cms/article/ArticleMysqldb.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cms/article/ArticleMysqldb.php
BSD-3-Clause
public function save($one, $originUrlKey) { $currentDateTime = \fec\helpers\CDate::getCurrentDateTime(); $primaryVal = isset($one[$this->getPrimaryKey()]) ? $one[$this->getPrimaryKey()] : ''; if ($primaryVal) { $model = $this->_articleModel->findOne($primaryVal); if (!$model) { Yii::$service->helper->errors->add('article {primaryKey} is not exist' , ['primaryKey' => $this->getPrimaryKey()]); return; } } else { $model = new $this->_articleModelName(); $model->created_at = time(); $model->created_user_id = \fec\helpers\CUser::getCurrentUserId(); } $defaultLangTitle = Yii::$service->fecshoplang->getDefaultLangAttrVal($one['title'], 'title'); $model->updated_at = time(); foreach ($this->_lang_attr as $attrName) { if (is_array($one[$attrName]) && !empty($one[$attrName])) { $one[$attrName] = serialize($one[$attrName]); } } unset($one['id']); $primaryKey = $this->getPrimaryKey(); $saveStatus = Yii::$service->helper->ar->save($model, $one); $primaryVal = $model[$primaryKey]; $originUrl = $originUrlKey.'?'.$this->getPrimaryKey() .'='. $primaryVal; $originUrlKey = isset($one['url_key']) ? $one['url_key'] : ''; $urlKey = Yii::$service->url->saveRewriteUrlKeyByStr($defaultLangTitle, $originUrl, $originUrlKey); $model->url_key = $urlKey; $this->initStatus($model); $model->save(); // 保存的数据格式返回 $model['content'] = unserialize($model['content']); $model['title'] = unserialize($model['title']); $model['meta_keywords'] = unserialize($model['meta_keywords']); $model['meta_description'] = unserialize($model['meta_description']); return $model->attributes; }
@param $one|array save $data to cms model,then,add url rewrite info to system service urlrewrite.
save
php
fecshop/yii2_fecshop
services/cms/article/ArticleMysqldb.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cms/article/ArticleMysqldb.php
BSD-3-Clause
public function getByUrlKey($urlKey) { if ($urlKey) { $model = $this->_articleModel->findOne([ 'url_key' => '/'.$urlKey, 'status' =>$this->getEnableStatus(), ]); if (isset($model['url_key'])) { return $model; } } return false; }
@param $urlKey | String , 对应表的url_key字段 根据url_key 查询得到article model
getByUrlKey
php
fecshop/yii2_fecshop
services/cms/article/ArticleMongodb.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cms/article/ArticleMongodb.php
BSD-3-Clause
public function save($one) { $currentDateTime = \fec\helpers\CDate::getCurrentDateTime(); $primaryVal = isset($one[$this->getPrimaryKey()]) ? $one[$this->getPrimaryKey()] : ''; if (!($this->validateIdentify($one))) { Yii::$service->helper->errors->add('Static block: identify exit, You must define a unique identify'); return; } if ($primaryVal) { $model = $this->_staticBlockModel->findOne($primaryVal); if (!$model) { Yii::$service->helper->errors->add('Static block {primaryKey} is not exist', ['primaryKey' => $this->getPrimaryKey()]); return; } } else { $model = new $this->_staticBlockModelName(); $model->created_at = time(); $model->created_user_id = \fec\helpers\CUser::getCurrentUserId(); } $model->updated_at = time(); foreach ($this->_lang_attr as $attrName) { if (is_array($one[$attrName]) && !empty($one[$attrName])) { $one[$attrName] = serialize($one[$attrName]); } } $primaryKey = $this->getPrimaryKey(); $model = Yii::$service->helper->ar->save($model, $one); $primaryVal = $model[$primaryKey]; return true; }
@param $one|array save $data to cms model,then,add url rewrite info to system service urlrewrite.
save
php
fecshop/yii2_fecshop
services/cms/staticblock/StaticBlockMysqldb.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/cms/staticblock/StaticBlockMysqldb.php
BSD-3-Clause
public function ipn() { $notifyFile = Yii::getAlias('@fecshop/services/payment/wxpay/notify.php'); require_once($notifyFile); \Yii::info('begin ipn', 'fecshop_debug'); $notify = new \PayNotifyCallBack(); $notify->Handle(false); }
接收IPN消息的url,接收微信支付的异步消息,进而更改订单状态。
ipn
php
fecshop/yii2_fecshop
services/payment/WxpayJsApi.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/WxpayJsApi.php
BSD-3-Clause
public function getScanCodeStart($code = "") { // 根据订单得到json格式的微信支付参数。 $trade_info = $this->getStartBizContentAndSetPaymentMethod(); if (!$trade_info) { Yii::$service->helper->errors->add('generate wxpay bizContent error'); return false; } //①、获取用户openid $tools = new \JsApiPay(); if (!$code) { $openId = $tools->GetOpenid(); } else { $openId = $tools->GetOpenidByCode($code); } //②、统一下单 $input = new \WxPayUnifiedOrder(); //$notify_url = Yii::$service->url->getUrl("payment/wxpayjsapi/ipn"); ////获取支付配置中的返回ipn url $notify_url = Yii::$service->payment->getStandardIpnUrl(); //$notify = new \NativePay(); //$input = new \WxPayUnifiedOrder(); $input->SetBody($this->scanCodeBody); //$input->SetAttach("商店的额外的自定义数据"); $input->SetAttach($trade_info['subject']); $input->SetDevice_info($this->deviceInfo); // 设置设备号 if ($trade_info['coupon_code']) { $input->SetGoods_tag($trade_info['coupon_code']); //设置商品标记,代金券或立减优惠功能的参数 } $input->SetOut_trade_no($trade_info['increment_id']); // Fecshop 订单号 $orderTotal = $trade_info['total_amount'] * 100; //微信支付的单位为分,所以要乘以100 $input->SetTotal_fee($orderTotal); $input->SetTime_start(date("YmdHis")); $input->SetTime_expire($this->getShangHaiExpireTime($this->expireTime)); $input->SetNotify_url($notify_url); //通知地址 改成自己接口通知的接口,要有公网域名,测试时直接行动此接口会产生日志 $input->SetTrade_type($this->tradeType); $input->SetProduct_id($trade_info['product_ids']); //此为二维码中包含的商品ID $input->SetOpenid($openId); //var_dump($input); $order = \WxPayApi::unifiedOrder($input); //echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>'; //$this->printf_info($order); $isJsonFormat = true; if ($code) { $isJsonFormat = false; } $jsApiParameters = $tools->GetJsApiParameters($order, $isJsonFormat); //获取共享收货地址js函数参数 $editAddress = $tools->GetEditAddressParameters($isJsonFormat); return [ 'jsApiParameters' => $jsApiParameters, 'editAddress' => $editAddress, 'total_amount' => $trade_info['total_amount'], 'increment_id' => $trade_info['increment_id'], ]; }
@param $code | string 传递的微信code
getScanCodeStart
php
fecshop/yii2_fecshop
services/payment/WxpayJsApi.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/WxpayJsApi.php
BSD-3-Clause
function printf_info($data) { foreach($data as $key=>$value){ echo "<font color='#00ff55;'>$key</font> : $value <br/>"; } }
打印输出数组信息
printf_info
php
fecshop/yii2_fecshop
services/payment/WxpayJsApi.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/WxpayJsApi.php
BSD-3-Clause
public function queryOrderByOut($out_trade_no) { $input = new \WxPayOrderQuery(); $input->SetOut_trade_no($out_trade_no); $result = \WxPayApi::orderQuery($input); return $result; }
通过微信接口查询交易信息 @param unknown $out_trade_no
queryOrderByOut
php
fecshop/yii2_fecshop
services/payment/WxpayJsApi.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/WxpayJsApi.php
BSD-3-Clause
protected function getStartBizContentAndSetPaymentMethod() { $currentOrderInfo = Yii::$service->order->getCurrentOrderInfo(); if (isset($currentOrderInfo['products']) && is_array($currentOrderInfo['products'])) { $subject_arr = []; foreach ($currentOrderInfo['products'] as $product) { $subject_arr[] = $product['name']; } if (!empty($subject_arr)) { $subject = implode(',', $subject_arr); // 字符串太长会出问题,这里将产品的name链接起来,在截图一下 if (strlen($subject) > $this->subjectMaxLength) { $subject = mb_substr($subject, 0, $this->subjectMaxLength); } $increment_id = $currentOrderInfo['increment_id']; $base_grand_total = $currentOrderInfo['base_grand_total']; $total_amount = Yii::$service->page->currency->getCurrencyPrice($base_grand_total, 'CNY'); Yii::$service->payment->setPaymentMethod($currentOrderInfo['payment_method']); $products = $currentOrderInfo['products']; $productIds = ''; if (is_array($products)) { foreach ($products as $product) { $productIds = $product['product_id']; break; } } return [ 'increment_id' => $increment_id, 'total_amount' => $total_amount, 'subject' => $subject, 'coupon_code' => $currentOrderInfo['coupon_code'], 'product_ids' => $productIds, ]; } } }
把返回的支付参数方式改成数组以适应微信的api 生成二维码图片会用到这个函数
getStartBizContentAndSetPaymentMethod
php
fecshop/yii2_fecshop
services/payment/WxpayJsApi.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/WxpayJsApi.php
BSD-3-Clause
protected function updateOrderInfo($out_trade_no, $trade_no, $isClearCart=true) { if (!empty($out_trade_no) && !empty($trade_no)) { if ($this->paymentSuccess($out_trade_no, $trade_no)) { // 清空购物车 if ($isClearCart) { Yii::$service->cart->clearCartProductAndCoupon(); } return true; } } else { Yii::$service->helper->errors->add('wxpay payment fail,resultCode: {result_code}', ['result_code' => $resultCode]); return false; } }
微信 支付成功后,对订单的状态进行修改 如果支付成功,则修改订单状态为支付成功状态。 @param $out_trade_no | string , fecshop的订单编号 increment_id @param $trade_no | 微信支付交易号 @param isClearCart | boolean 是否清空购物车
updateOrderInfo
php
fecshop/yii2_fecshop
services/payment/WxpayJsApi.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/WxpayJsApi.php
BSD-3-Clause
protected function paymentSuccess($increment_id, $trade_no, $sendEmail = true) { if (!$this->_order) { $this->_order = Yii::$service->order->getByIncrementId($increment_id); Yii::$service->payment->setPaymentMethod($this->_order['payment_method']); } $orderstatus = Yii::$service->order->payment_status_confirmed; $updateArr['order_status'] = $orderstatus; $updateArr['txn_id'] = $trade_no; // 微信的交易号 $updateColumn = $this->_order->updateAll( $updateArr, [ 'and', ['order_id' => $this->_order['order_id']], ['in','order_status',$this->_allowChangOrderStatus] ] ); if (!empty($updateColumn)) { // 发送邮件,以及其他的一些操作(订单支付成功后的操作) Yii::$service->order->orderPaymentCompleteEvent($this->_order['increment_id']); } return true; }
@param $increment_id | String 订单号 @param $sendEmail | boolean 是否发送邮件 订单支付成功后,需要更改订单支付状态等一系列的处理。
paymentSuccess
php
fecshop/yii2_fecshop
services/payment/WxpayJsApi.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/WxpayJsApi.php
BSD-3-Clause
public function ipn() { $notifyFile = Yii::getAlias('@fecshop/services/payment/wxpay/notify.php'); require_once($notifyFile); \Yii::info('begin ipn', 'fecshop_debug'); $notify = new \PayNotifyCallBack(); $notify->Handle(false); }
接收IPN消息的url,接收微信支付的异步消息,进而更改订单状态。
ipn
php
fecshop/yii2_fecshop
services/payment/Wxpay.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/Wxpay.php
BSD-3-Clause
public function queryOrderByOut($out_trade_no) { $input = new \WxPayOrderQuery(); $input->SetOut_trade_no($out_trade_no); $result = \WxPayApi::orderQuery($input); return $result; }
通过微信接口查询交易信息 @param unknown $out_trade_no
queryOrderByOut
php
fecshop/yii2_fecshop
services/payment/Wxpay.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/Wxpay.php
BSD-3-Clause
protected function getStartBizContentAndSetPaymentMethod() { $currentOrderInfo = Yii::$service->order->getCurrentOrderInfo(); if (isset($currentOrderInfo['products']) && is_array($currentOrderInfo['products'])) { $subject_arr = []; foreach ($currentOrderInfo['products'] as $product) { $subject_arr[] = $product['name']; } if (!empty($subject_arr)) { $subject = implode(',', $subject_arr); // 字符串太长会出问题,这里将产品的name链接起来,在截图一下 if (strlen($subject) > $this->subjectMaxLength) { $subject = mb_substr($subject, 0, $this->subjectMaxLength); } //echo $subject; $increment_id = $currentOrderInfo['increment_id']; $base_grand_total = $currentOrderInfo['base_grand_total']; $total_amount = Yii::$service->page->currency->getCurrencyPrice($base_grand_total, 'CNY'); Yii::$service->payment->setPaymentMethod($currentOrderInfo['payment_method']); $products = $currentOrderInfo['products']; $productIds = ''; if (is_array($products)) { foreach ($products as $product) { $productIds = $product['product_id']; break; } } return [ 'increment_id' => $increment_id, 'total_amount' => $total_amount, 'subject' => $subject, 'coupon_code' => $currentOrderInfo['coupon_code'], 'product_ids' => $productIds, ]; } } }
把返回的支付参数方式改成数组以适应微信的api 生成二维码图片会用到这个函数
getStartBizContentAndSetPaymentMethod
php
fecshop/yii2_fecshop
services/payment/Wxpay.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/Wxpay.php
BSD-3-Clause
protected function updateOrderInfo($out_trade_no, $trade_no, $isClearCart=true) { if (!empty($out_trade_no) && !empty($trade_no)) { if ($this->paymentSuccess($out_trade_no, $trade_no)) { // 清空购物车 if ($isClearCart) { Yii::$service->cart->clearCartProductAndCoupon(); } return true; } } else { Yii::$service->helper->errors->add('wxpay payment fail,resultCode: {result_code}', ['result_code' => $resultCode]); return false; } }
微信 支付成功后,对订单的状态进行修改 如果支付成功,则修改订单状态为支付成功状态。 @param $out_trade_no | string , fecshop的订单编号 increment_id @param $trade_no | 微信支付交易号 @param isClearCart | boolean 是否清空购物车
updateOrderInfo
php
fecshop/yii2_fecshop
services/payment/Wxpay.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/Wxpay.php
BSD-3-Clause
protected function paymentSuccess($increment_id, $trade_no, $sendEmail = true) { if (!$this->_order) { $this->_order = Yii::$service->order->getByIncrementId($increment_id); Yii::$service->payment->setPaymentMethod($this->_order['payment_method']); } $orderstatus = Yii::$service->order->payment_status_confirmed; $updateArr['order_status'] = $orderstatus; $updateArr['txn_id'] = $trade_no; // 微信的交易号 $updateColumn = $this->_order->updateAll( $updateArr, [ 'and', ['order_id' => $this->_order['order_id']], ['in','order_status',$this->_allowChangOrderStatus] ] ); if (!empty($updateColumn)) { // 发送邮件,以及其他的一些操作(订单支付成功后的操作) Yii::$service->order->orderPaymentCompleteEvent($this->_order['increment_id']); } return true; }
@param $increment_id | String 订单号 @param $sendEmail | boolean 是否发送邮件 订单支付成功后,需要更改订单支付状态等一系列的处理。
paymentSuccess
php
fecshop/yii2_fecshop
services/payment/Wxpay.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/Wxpay.php
BSD-3-Clause
public function getWxpayHandle() { return 'wxpay_standard'; }
支付宝的 标示
getWxpayHandle
php
fecshop/yii2_fecshop
services/payment/Wxpay.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/Wxpay.php
BSD-3-Clause
public function ipn() { $notifyFile = Yii::getAlias('@fecshop/services/payment/wxpay/notify.php'); require_once($notifyFile); \Yii::info('begin ipn', 'fecshop_debug'); $notify = new \PayNotifyCallBack(); $notify->Handle(false); }
接收IPN消息的url,接收微信支付的异步消息,进而更改订单状态。
ipn
php
fecshop/yii2_fecshop
services/payment/WxpayMicro.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/WxpayMicro.php
BSD-3-Clause
public function getScanCodeStart() { // 根据订单得到json格式的微信支付参数。 $trade_info = $this->getStartBizContentAndSetPaymentMethod(); if (!$trade_info) { Yii::$service->helper->errors->add('generate wxpay bizContent error'); return false; } //①、获取用户openid $tools = new \JsApiPay(); $identity = Yii::$app->user->identity; $openId = $identity->wx_micro_openid; //②、统一下单 $input = new \WxPayUnifiedOrder(); $notify_url = Yii::$service->url->getUrl("payment/wxpayjsapi/ipn"); ////获取支付配置中的返回ipn url $input->SetBody($this->scanCodeBody); $input->SetAttach($trade_info['subject']); $input->SetDevice_info('1000'); // 设置设备号 if ($trade_info['coupon_code']) { $input->SetGoods_tag($trade_info['coupon_code']); //设置商品标记,代金券或立减优惠功能的参数 } $input->SetOut_trade_no($trade_info['increment_id']); // Fecshop 订单号 $orderTotal = $trade_info['total_amount'] * 100; //微信支付的单位为分,所以要乘以100 $input->SetTotal_fee($orderTotal); $input->SetTime_start(date("YmdHis")); $input->SetTime_expire($this->getShangHaiExpireTime($this->expireTime)); $input->SetNotify_url($notify_url); //通知地址 改成自己接口通知的接口,要有公网域名,测试时直接行动此接口会产生日志 $input->SetTrade_type($this->tradeType); $input->SetProduct_id($trade_info['product_ids']); //此为二维码中包含的商品ID $input->SetOpenid($openId); $order = \WxPayApi::unifiedOrder($input); $isJsonFormat = false; $jsApiParameters = $tools->GetJsApiParameters($order, $isJsonFormat); //获取共享收货地址js函数参数 $editAddress = $tools->GetEditAddressParameters($isJsonFormat); return [ 'jsApiParameters' => $jsApiParameters, 'editAddress' => $editAddress, 'total_amount' => $trade_info['total_amount'], 'increment_id' => $trade_info['increment_id'], ]; }
@param $code | string 传递的微信code
getScanCodeStart
php
fecshop/yii2_fecshop
services/payment/WxpayMicro.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/WxpayMicro.php
BSD-3-Clause
function printf_info($data) { foreach($data as $key=>$value){ echo "<font color='#00ff55;'>$key</font> : $value <br/>"; } }
打印输出数组信息
printf_info
php
fecshop/yii2_fecshop
services/payment/WxpayMicro.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/WxpayMicro.php
BSD-3-Clause
public function queryOrderByOut($out_trade_no) { $input = new \WxPayOrderQuery(); $input->SetOut_trade_no($out_trade_no); $result = \WxPayApi::orderQuery($input); return $result; }
通过微信接口查询交易信息 @param unknown $out_trade_no
queryOrderByOut
php
fecshop/yii2_fecshop
services/payment/WxpayMicro.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/WxpayMicro.php
BSD-3-Clause
protected function getStartBizContentAndSetPaymentMethod() { $currentOrderInfo = Yii::$service->order->getCurrentOrderInfo(); if (isset($currentOrderInfo['products']) && is_array($currentOrderInfo['products'])) { $subject_arr = []; foreach ($currentOrderInfo['products'] as $product) { $subject_arr[] = $product['name']; } if (!empty($subject_arr)) { $subject = implode(',', $subject_arr); // 字符串太长会出问题,这里将产品的name链接起来,在截图一下 if (strlen($subject) > $this->subjectMaxLength) { $subject = mb_substr($subject, 0, $this->subjectMaxLength); } $increment_id = $currentOrderInfo['increment_id']; $base_grand_total = $currentOrderInfo['base_grand_total']; $total_amount = Yii::$service->page->currency->getCurrencyPrice($base_grand_total, 'CNY'); Yii::$service->payment->setPaymentMethod($currentOrderInfo['payment_method']); $products = $currentOrderInfo['products']; $productIds = ''; if (is_array($products)) { foreach ($products as $product) { $productIds = $product['product_id']; break; } } return [ 'increment_id' => $increment_id, 'total_amount' => $total_amount, 'subject' => $subject, 'coupon_code' => $currentOrderInfo['coupon_code'], 'product_ids' => $productIds, ]; } } }
把返回的支付参数方式改成数组以适应微信的api 生成二维码图片会用到这个函数
getStartBizContentAndSetPaymentMethod
php
fecshop/yii2_fecshop
services/payment/WxpayMicro.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/WxpayMicro.php
BSD-3-Clause
protected function updateOrderInfo($out_trade_no, $trade_no, $isClearCart=true) { if (!empty($out_trade_no) && !empty($trade_no)) { if ($this->paymentSuccess($out_trade_no, $trade_no)) { // 清空购物车 if ($isClearCart) { Yii::$service->cart->clearCartProductAndCoupon(); } return true; } } else { Yii::$service->helper->errors->add('wxpay payment fail,resultCode: {result_code}', ['result_code' => $resultCode]); return false; } }
微信 支付成功后,对订单的状态进行修改 如果支付成功,则修改订单状态为支付成功状态。 @param $out_trade_no | string , fecshop的订单编号 increment_id @param $trade_no | 微信支付交易号 @param isClearCart | boolean 是否清空购物车
updateOrderInfo
php
fecshop/yii2_fecshop
services/payment/WxpayMicro.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/WxpayMicro.php
BSD-3-Clause
protected function paymentSuccess($increment_id, $trade_no, $sendEmail = true) { if (!$this->_order) { $this->_order = Yii::$service->order->getByIncrementId($increment_id); Yii::$service->payment->setPaymentMethod($this->_order['payment_method']); } $orderstatus = Yii::$service->order->payment_status_confirmed; $updateArr['order_status'] = $orderstatus; $updateArr['txn_id'] = $trade_no; // 微信的交易号 $updateColumn = $this->_order->updateAll( $updateArr, [ 'and', ['order_id' => $this->_order['order_id']], ['in','order_status',$this->_allowChangOrderStatus] ] ); if (!empty($updateColumn)) { // 发送邮件,以及其他的一些操作(订单支付成功后的操作) Yii::$service->order->orderPaymentCompleteEvent($this->_order['increment_id']); } return true; }
@param $increment_id | String 订单号 @param $sendEmail | boolean 是否发送邮件 订单支付成功后,需要更改订单支付状态等一系列的处理。
paymentSuccess
php
fecshop/yii2_fecshop
services/payment/WxpayMicro.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/WxpayMicro.php
BSD-3-Clause
public function getWxpayHandle() { return 'wxpay_standard'; }
支付宝的 标示
getWxpayHandle
php
fecshop/yii2_fecshop
services/payment/WxpayMicro.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/WxpayMicro.php
BSD-3-Clause
protected function initParam() { /** * 引入 支付宝支付的SDK文件。 */ if (!$this->_initAlipayLib) { define("AOP_SDK_WORK_DIR", $this->alipay_aop_sdk_work_dir); define("AOP_SDK_DEV_MODE", $this->alipay_aop_sdk_dev_mode); $AopSdkFile = Yii::getAlias('@fecshop/lib/alipay/AopSdk.php'); require($AopSdkFile); $this->_initAlipayLib = 1; } if (!$this->_AopClient) { $this->_AopClient = new \AopClient; $this->_AopClient->gatewayUrl = $this->gatewayUrl; $this->_AopClient->appId = $this->appId; $this->_AopClient->rsaPrivateKey = $this->rsaPrivateKey; $this->_AopClient->apiVersion = $this->apiVersion; //'1.0'; $this->_AopClient->format = $this->format; $this->_AopClient->charset = $this->charset; $this->_AopClient->signType = $this->signType; $this->_AopClient->alipayrsaPublicKey= $this->alipayrsaPublicKey; } }
初始化 $this->_AopClient
initParam
php
fecshop/yii2_fecshop
services/payment/Alipay.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/Alipay.php
BSD-3-Clause
public function review() { $this->initParam(); $trade_no = Yii::$app->request->get('trade_no'); $out_trade_no = Yii::$app->request->get('out_trade_no'); $total_amount = Yii::$app->request->get('total_amount'); $seller_id = Yii::$app->request->get('seller_id'); $auth_app_id = Yii::$app->request->get('auth_app_id'); //验证订单的合法性 if (!$this->validateReviewOrder($out_trade_no, $total_amount, $seller_id, $auth_app_id)) { return false; } $this->_AopClient->postCharset = $this->charset; $this->_alipayRequest = new \AlipayTradeQueryRequest(); $bizContent = json_encode([ 'out_trade_no' => $out_trade_no, 'trade_no' => $trade_no, ]); //echo $bizContent; $this->_alipayRequest->setBizContent($bizContent); $result = $this->_AopClient->execute($this->_alipayRequest); $responseNode = str_replace(".", "_", $this->_alipayRequest->getApiMethodName()) . "_response"; $resultCode = $result->$responseNode->code; if (!empty($resultCode)&&$resultCode == 10000) { $this->paymentSuccess($out_trade_no, $trade_no); // 清空购物车 Yii::$service->cart->clearCartProductAndCoupon(); return true; } else { Yii::$service->helper->errors->add('Alipay payment fail,resultCode: {result_code}', ['result_code' => $resultCode]); return false; } }
支付宝 支付成功后,返回网站,调用该函数进行支付宝订单支付状态查询 如果支付成功,则修改订单状态为支付成功状态。
review
php
fecshop/yii2_fecshop
services/payment/Alipay.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/Alipay.php
BSD-3-Clause
public function receiveIpn() { Yii::info('alipay service receiveIpn():begin init param', 'fecshop_debug'); $this->initParam(); Yii::info('alipay service receiveIpn():begin rsaCheck', 'fecshop_debug'); // 验签 $checkV2Status = $this->_AopClient->rsaCheckV1($_POST, '', $this->signType); Yii::info('alipay service receiveIpn():rsacheck end', 'fecshop_debug'); if ($checkV2Status) { Yii::info('alipay service receiveIpn():rsacheck success', 'fecshop_debug'); $trade_no = Yii::$app->request->post('trade_no'); $out_trade_no = Yii::$app->request->post('out_trade_no'); $total_amount = Yii::$app->request->post('total_amount'); $seller_id = Yii::$app->request->post('seller_id'); $auth_app_id = Yii::$app->request->post('app_id'); $trade_status = Yii::$app->request->post('trade_status'); Yii::info('alipay service receiveIpn(): [ trade_no: ]'.$trade_no, 'fecshop_debug'); Yii::info('alipay service receiveIpn(): [ out_trade_no: ]'.$out_trade_no, 'fecshop_debug'); Yii::info('alipay service receiveIpn(): [ total_amount: ]'.$total_amount, 'fecshop_debug'); Yii::info('alipay service receiveIpn(): [ seller_id: ]'.$seller_id, 'fecshop_debug'); Yii::info('alipay service receiveIpn(): [ auth_app_id: ]'.$auth_app_id, 'fecshop_debug'); Yii::info('alipay service receiveIpn(): [ trade_status: ]'.$trade_status, 'fecshop_debug'); //验证订单的合法性 if (!$this->validateReviewOrder($out_trade_no, $total_amount, $seller_id, $auth_app_id)) { Yii::info('alipay service receiveIpn(): validate order fail', 'fecshop_debug'); return false; } Yii::info('alipay service receiveIpn():validate order success', 'fecshop_debug'); if (self::TRADE_SUCCESS == $trade_status) { Yii::info('alipay service receiveIpn():alipay trade success ', 'fecshop_debug'); if ($this->paymentSuccess($out_trade_no, $trade_no)) { Yii::info('alipay service receiveIpn():update order status success', 'fecshop_debug'); return true; } } } else { return false; } }
支付宝的消息接收IPN,执行的函数,接收的消息用来更改订单状态。 您开启log后,可以在@app/runtime/fecshop_logs 文件夹下执行:tail -f fecshop_debug.log , 来查看log输出。
receiveIpn
php
fecshop/yii2_fecshop
services/payment/Alipay.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/Alipay.php
BSD-3-Clause
protected function paymentSuccess($increment_id, $trade_no, $sendEmail = true) { Yii::$service->store->currentLangCode = 'zh'; if (!$this->_order) { $this->_order = Yii::$service->order->getByIncrementId($increment_id); Yii::$service->payment->setPaymentMethod($this->_order['payment_method']); } // 【优化后的代码 ##】 $orderstatus = Yii::$service->order->payment_status_confirmed; $updateArr['order_status'] = $orderstatus; $updateArr['txn_id'] = $trade_no; // 支付宝的交易号 $updateColumn = $this->_order->updateAll( $updateArr, [ 'and', ['order_id' => $this->_order['order_id']], ['in','order_status',$this->_allowChangOrderStatus] ] ); if (!empty($updateColumn)) { // 发送邮件,以及其他的一些操作(订单支付成功后的操作) Yii::$service->order->orderPaymentCompleteEvent($this->_order['increment_id']); } return true; }
@param $increment_id | String 订单号 @param $sendEmail | boolean 是否发送邮件 订单支付成功后,需要更改订单支付状态等一系列的处理。
paymentSuccess
php
fecshop/yii2_fecshop
services/payment/Alipay.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/Alipay.php
BSD-3-Clause
protected function getStartBizContentAndSetPaymentMethod() { $currentOrderInfo = Yii::$service->order->getCurrentOrderInfo(); if (isset($currentOrderInfo['products']) && is_array($currentOrderInfo['products'])) { $subject_arr = []; foreach ($currentOrderInfo['products'] as $product) { $subject_arr[] = $product['name']; } if (!empty($subject_arr)) { $subject = implode(',', $subject_arr); $increment_id = $currentOrderInfo['increment_id']; $total_amount = $currentOrderInfo['grand_total']; Yii::$service->payment->setPaymentMethod($currentOrderInfo['payment_method']); return json_encode([ // param 参看:https://docs.open.alipay.com/common/105901 'out_trade_no' => $increment_id, 'product_code' => $this->_productCode, 'total_amount' => $total_amount, 'subject' => $subject, //'body' => '', ]); } } }
通过订单信息,得到支付宝支付传递的参数数据 也就是一个json格式的数组。
getStartBizContentAndSetPaymentMethod
php
fecshop/yii2_fecshop
services/payment/Alipay.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/Alipay.php
BSD-3-Clause
public function getAlipayHandle() { return 'alipay_standard'; }
支付宝的 标示
getAlipayHandle
php
fecshop/yii2_fecshop
services/payment/Alipay.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/Alipay.php
BSD-3-Clause
public function ipn() { $notifyFile = Yii::getAlias('@fecshop/services/payment/wxpay/notify.php'); require_once($notifyFile); \Yii::info('begin ipn', 'fecshop_debug'); $notify = new \PayNotifyCallBack(); $notify->Handle(false); }
接收IPN消息的url,接收微信支付的异步消息,进而更改订单状态。
ipn
php
fecshop/yii2_fecshop
services/payment/WxpayH5.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/WxpayH5.php
BSD-3-Clause
public function getScanCodeStart($code = "") { // 根据订单得到json格式的微信支付参数。 $trade_info = $this->getStartBizContentAndSetPaymentMethod(); if (!$trade_info) { Yii::$service->helper->errors->add('generate wxpay bizContent error'); return false; } $money= $trade_info['total_amount'] * 100; //微信支付的单位为分,所以要乘以100; //充值金额 微信支付单位为分 $userip = Yii::$service->helper->getCustomerIp();; //获得用户设备 IP $appid = \WxPayConfig::APPID ; //应用 APPID $mch_id = \WxPayConfig::MCHID; //微信支付商户号 $key = \WxPayConfig::KEY; //微信商户 API 密钥 $out_trade_no = $trade_info['increment_id'];//平台内部订单号 $nonce_str = Yii::$service->helper->createNoncestr();//随机字符串 $body = $this->scanCodeBody;//内容 $total_fee = $money; //金额 $spbill_create_ip = $userip; //IP $notify_url = Yii::$service->payment->getStandardIpnUrl(); //回调地址 $trade_type = $this->tradeType;//交易类型 具体看 API 里面有详细介绍 $wap_url = Yii::$service->url->homeUrl(); $scene_info ='{"h5_info":{"type":"Wap","wap_url":"'.$wap_url.'","wap_name":"'.$this->scanCodeBody.'"}}';//场景信息 必要参数 $signA ="appid=$appid&attach=$out_trade_no&body=$body&mch_id=$mch_id&nonce_str=$nonce_str&notify_url=$notify_url&out_trade_no=$out_trade_no&scene_info=$scene_info&spbill_create_ip=$spbill_create_ip&total_fee=$total_fee&trade_type=$trade_type"; $strSignTmp = $signA."&key=$key"; //拼接字符串 注意顺序微信有个测试网址 顺序按照他的来 直接点下面的校正测试 包括下面 XML 是否正确 $sign = strtoupper(MD5($strSignTmp)); // MD5 后转换成大写 $post_data = "<xml> <appid>$appid</appid> <mch_id>$mch_id</mch_id> <body>$body</body> <out_trade_no>$out_trade_no</out_trade_no> <total_fee>$total_fee</total_fee> <spbill_create_ip>$spbill_create_ip</spbill_create_ip> <notify_url>$notify_url</notify_url> <trade_type>$trade_type</trade_type> <scene_info>$scene_info</scene_info> <attach>$out_trade_no</attach> <nonce_str>$nonce_str</nonce_str> <sign>$sign</sign> </xml>";//拼接成 XML 格式 $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";//微信传参地址 $dataxml = $this->postXmlCurl($post_data,$url); //后台 POST 微信传参地址 同时取得微信返回的参数 $objectxml = (array)simplexml_load_string($dataxml, 'SimpleXMLElement', LIBXML_NOCDATA); //将微信返回的 XML 转换成数组 return $objectxml; }
@param $code | string 传递的微信code
getScanCodeStart
php
fecshop/yii2_fecshop
services/payment/WxpayH5.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/WxpayH5.php
BSD-3-Clause
public function printf_info($data) { foreach($data as $key=>$value){ echo "<font color='#00ff55;'>$key</font> : $value <br/>"; } }
打印输出数组信息
printf_info
php
fecshop/yii2_fecshop
services/payment/WxpayH5.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/WxpayH5.php
BSD-3-Clause
public function queryOrderByOut($out_trade_no) { $input = new \WxPayOrderQuery(); $input->SetOut_trade_no($out_trade_no); $result = \WxPayApi::orderQuery($input); return $result; }
通过微信接口查询交易信息 @param unknown $out_trade_no
queryOrderByOut
php
fecshop/yii2_fecshop
services/payment/WxpayH5.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/WxpayH5.php
BSD-3-Clause
protected function getStartBizContentAndSetPaymentMethod() { $currentOrderInfo = Yii::$service->order->getCurrentOrderInfo(); if (isset($currentOrderInfo['products']) && is_array($currentOrderInfo['products'])) { $subject_arr = []; foreach ($currentOrderInfo['products'] as $product) { $subject_arr[] = $product['name']; } if (!empty($subject_arr)) { $subject = implode(',', $subject_arr); // 字符串太长会出问题,这里将产品的name链接起来,在截图一下 if (strlen($subject) > $this->subjectMaxLength) { $subject = mb_substr($subject, 0, $this->subjectMaxLength); } $increment_id = $currentOrderInfo['increment_id']; $base_grand_total = $currentOrderInfo['base_grand_total']; $total_amount = Yii::$service->page->currency->getCurrencyPrice($base_grand_total, 'CNY'); Yii::$service->payment->setPaymentMethod($currentOrderInfo['payment_method']); $products = $currentOrderInfo['products']; $productIds = ''; if (is_array($products)) { foreach ($products as $product) { $productIds = $product['product_id']; break; } } return [ 'increment_id' => $increment_id, 'total_amount' => $total_amount, 'subject' => $subject, 'coupon_code' => $currentOrderInfo['coupon_code'], 'product_ids' => $productIds, ]; } } }
把返回的支付参数方式改成数组以适应微信的api 生成二维码图片会用到这个函数
getStartBizContentAndSetPaymentMethod
php
fecshop/yii2_fecshop
services/payment/WxpayH5.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/WxpayH5.php
BSD-3-Clause
protected function updateOrderInfo($out_trade_no, $trade_no, $isClearCart=true) { if (!empty($out_trade_no) && !empty($trade_no)) { if ($this->paymentSuccess($out_trade_no, $trade_no)) { // 清空购物车 if ($isClearCart) { Yii::$service->cart->clearCartProductAndCoupon(); } return true; } } else { Yii::$service->helper->errors->add('wxpay payment fail,resultCode: {result_code}', ['result_code' => $resultCode]); return false; } }
微信 支付成功后,对订单的状态进行修改 如果支付成功,则修改订单状态为支付成功状态。 @param $out_trade_no | string , fecshop的订单编号 increment_id @param $trade_no | 微信支付交易号 @param isClearCart | boolean 是否清空购物车
updateOrderInfo
php
fecshop/yii2_fecshop
services/payment/WxpayH5.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/WxpayH5.php
BSD-3-Clause
protected function paymentSuccess($increment_id, $trade_no, $sendEmail = true) { if (!$this->_order) { $this->_order = Yii::$service->order->getByIncrementId($increment_id); Yii::$service->payment->setPaymentMethod($this->_order['payment_method']); } $orderstatus = Yii::$service->order->payment_status_confirmed; $updateArr['order_status'] = $orderstatus; $updateArr['txn_id'] = $trade_no; // 微信的交易号 $updateColumn = $this->_order->updateAll( $updateArr, [ 'and', ['order_id' => $this->_order['order_id']], ['in','order_status',$this->_allowChangOrderStatus] ] ); if (!empty($updateColumn)) { // 发送邮件,以及其他的一些操作(订单支付成功后的操作) Yii::$service->order->orderPaymentCompleteEvent($this->_order['increment_id']); } return true; }
@param $increment_id | String 订单号 @param $sendEmail | boolean 是否发送邮件 订单支付成功后,需要更改订单支付状态等一系列的处理。
paymentSuccess
php
fecshop/yii2_fecshop
services/payment/WxpayH5.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/WxpayH5.php
BSD-3-Clause
public function getWxpayHandle() { return 'wxpay_standard'; }
支付宝的 标示
getWxpayHandle
php
fecshop/yii2_fecshop
services/payment/WxpayH5.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/WxpayH5.php
BSD-3-Clause
public function getRequestUrl( $orderInfo, $return_url='', $cancel_url='', $ipn_url='' ) { $express_payment_method = Yii::$service->payment->paypal->express_payment_method; if (!$return_url) { $return_url = Yii::$service->url->getUrl('payment/success'); } if (!$cancel_url) { $cancel_url = Yii::$service->payment->getExpressCancelUrl($express_payment_method); } if (!$ipn_url) { $ipn_url = Yii::$service->payment->getExpressIpnUrl($express_payment_method); } $paypal_args = $this->get_paypal_args( $orderInfo, $return_url, $cancel_url, $ipn_url); $paypal_args['bn'] = 'FecThemes_Cart'; // Append PayPal Partner Attribution ID. This should not be overridden for this gateway. return $this->endpoint . http_build_query( $paypal_args, '', '&' ); }
@param $orderInfo | array , 订单信息 @param $return_url | string, 支付完成后,返回商城的url地址 @param $cancel_url | string,支付取消后,返回商城的url地址 @param $ipn_url | string,paypal发送异步支付消息IPN的地址。 得到跳转到paypal的url,url中带有订单等信息
getRequestUrl
php
fecshop/yii2_fecshop
services/payment/PaypalCart.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/PaypalCart.php
BSD-3-Clause
protected function get_paypal_args( $orderInfo, $return_url, $cancel_url, $ipn_url ) { return array_merge( array( 'cmd' => '_cart', 'business' => $this->businessAccount, 'no_note' => 1, 'currency_code' => Yii::$service->page->currency->getCurrentCurrency(), 'charset' => 'utf-8', 'rm' => Yii::$app->getRequest()->getIsSecureConnection() ? 2 : 1, 'upload' => 1, 'order' => $orderInfo['increment_id'], 'order_id' => $orderInfo['order_id'], 'notify_url' => $ipn_url, 'return' => $return_url, 'cancel_return' => $cancel_url , 'page_style' => '', 'image_url' => '', 'paymentaction' => 'sale', 'invoice' => $this->limit_length( $orderInfo['increment_id'], 127 ), 'custom' => json_encode( [ 'order_id' => $orderInfo['order_id'], 'order_key' => $orderInfo['increment_id'], ] ), 'first_name' => $this->limit_length( $orderInfo['customer_firstname'], 32 ), 'last_name' => $this->limit_length( $orderInfo['customer_lastname'], 64 ), 'address1' => $this->limit_length( $orderInfo['customer_address_street1'], 100 ), 'address2' => $this->limit_length( $orderInfo['customer_address_street2'], 100 ), 'city' => $this->limit_length( $orderInfo['customer_address_city'], 40 ), 'state' => $orderInfo['customer_address_state_name'], 'zip' => $this->limit_length( $orderInfo['customer_address_zip'], 32 ), 'country' => $this->limit_length( $orderInfo['customer_address_country'], 2 ), 'email' => $this->limit_length( $orderInfo['customer_email'] ), ), $this->get_phone_number_args( $orderInfo ), $this->get_shipping_args( $orderInfo ), $this->get_line_item_args( $orderInfo ) ); }
@param $orderInfo | array , 订单信息 @param $return_url | string, 支付完成后,返回商城的url地址 @param $cancel_url | string,支付取消后,返回商城的url地址 @param $ipn_url | string,paypal发送异步支付消息IPN的地址。 得到跳转到paypal的url,url中带有订单等信息
get_paypal_args
php
fecshop/yii2_fecshop
services/payment/PaypalCart.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/PaypalCart.php
BSD-3-Clause
protected function get_shipping_args( $orderInfo ) { $shipping_args = array(); $shipping_args['address_override'] = 1; $shipping_args['no_shipping'] = 0; // If we are sending shipping, send shipping address instead of billing. $shipping_args['first_name'] = $this->limit_length( $orderInfo['customer_firstname'], 32 ); $shipping_args['last_name'] = $this->limit_length( $orderInfo['customer_lastname'], 64 ); $shipping_args['address1'] = $this->limit_length( $orderInfo['customer_address_street1'], 100 ); $shipping_args['address2'] = $this->limit_length( $orderInfo['customer_address_street2'], 100 ); $shipping_args['city'] = $this->limit_length( $orderInfo['customer_address_city'], 40 ); $shipping_args['state'] = $orderInfo['customer_address_state_name']; $shipping_args['country'] = $this->limit_length( $orderInfo['customer_address_country'], 2 ); $shipping_args['zip'] = $this->limit_length( $orderInfo['customer_address_zip'], 32 ); return $shipping_args; }
Get shipping args for paypal request. @param WC_Order $order Order object. @return array
get_shipping_args
php
fecshop/yii2_fecshop
services/payment/PaypalCart.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/PaypalCart.php
BSD-3-Clause
protected function limit_length( $string, $limit = 127 ) { $str_limit = $limit - 3; if ( function_exists( 'mb_strimwidth' ) ) { if ( mb_strlen( $string ) > $limit ) { $string = mb_strimwidth( $string, 0, $str_limit ) . '...'; } } else { if ( strlen( $string ) > $limit ) { $string = substr( $string, 0, $str_limit ) . '...'; } } return $string; }
Limit length of an arg. @param string $string Argument to limit. @param integer $limit Limit size in characters. @return string
limit_length
php
fecshop/yii2_fecshop
services/payment/PaypalCart.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/PaypalCart.php
BSD-3-Clause
public function isSandoxEnv() { if ($this->_env == Yii::$service->payment->env_sanbox) { return true; } return false; }
是否沙盒账户环境
isSandoxEnv
php
fecshop/yii2_fecshop
services/payment/Paypal.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/Paypal.php
BSD-3-Clause
public function accountIsBusinessMode() { if ($this->_account && $this->_password && $this->_signature) { //var_dump($this->_account , $this->_password , $this->_signature);exit; return true; } return false; }
是否,商业账户模式 如果没有填写api信息,则为个人账户,否则为商业账户
accountIsBusinessMode
php
fecshop/yii2_fecshop
services/payment/Paypal.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/Paypal.php
BSD-3-Clause
public function getCrtFile($domain) { if (isset($this->crt_file[$domain]) && !empty($this->crt_file[$domain])) { return Yii::getAlias($this->crt_file[$domain]); } }
@param $domain | string @return 得到证书crt文件的绝对路径
getCrtFile
php
fecshop/yii2_fecshop
services/payment/Paypal.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/Paypal.php
BSD-3-Clause
public function receiveIpn($post) { \Yii::info('receiveIpn', 'fecshop_debug'); if ($this->verifySecurity($post)) { \Yii::info('verifySecurity', 'fecshop_debug'); // 验证数据是否已经发送 // 验证数据是否被篡改。 if ($this->isNotDistort()) { \Yii::info('updateOrderStatusByIpn', 'fecshop_debug'); $this->updateOrderStatusByIpn(); } else { // 如果数据和订单数据不一致,而且,支付状态为成功,则此订单 // 标记为可疑的。 $suspected_fraud = Yii::$service->order->payment_status_suspected_fraud; $this->updateOrderStatusByIpn($suspected_fraud); } } }
在paypal 标准支付中,paypal会向网站发送IPN消息,告知fecshop订单支付状态, 进而fecshop更改订单状态。 fecshop一方面验证消息是否由paypal发出,另一方面要验证订单是否和后台的一致。
receiveIpn
php
fecshop/yii2_fecshop
services/payment/Paypal.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/Paypal.php
BSD-3-Clause
protected function verifySecurity($post) { $this->_postData = $post; $verifyUrl = $this->getVerifyUrl(); \Yii::info('verifyUrl:'.$verifyUrl, 'fecshop_debug'); $verifyReturn = $this->curlGet($verifyUrl); \Yii::info('verifyReturn:'.$verifyReturn, 'fecshop_debug'); if ($verifyReturn == 'VERIFIED') { return true; } }
该函数是为了验证IPN是否是由paypal发出, 当paypal发送IPN消息给fecshop,fecshop不知道是否是伪造的支付消息, 因此,fecshop将接收到的参数传递给paypal,询问paypal是否是paypal 发送的IPN消息,如果是,则返回VERIFIED。
verifySecurity
php
fecshop/yii2_fecshop
services/payment/Paypal.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/Paypal.php
BSD-3-Clause
protected function curlGet($url, $i = 0) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_VERBOSE, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $req); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_SSLVERSION, 6); if ($this->use_local_certs) { $crtFile = $this->getCrtFile('www.paypal.com'); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_CAINFO, $crtFile); } else { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); } curl_setopt($ch, CURLOPT_FORBID_REUSE, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Connection: Close']); $httpResponse = curl_exec($ch); if (!$httpResponse) { $i++; if ($i <= 5) { return $this->curlGet($url, $i); } else { return $httpResponse; } } return $httpResponse; }
@param $url | string, 请求的url @param $i | 请求的次数,因为curl可能存在失败的可能,当 失败后,就会通过递归的方式进行多次请求,这里设置的最大请求5次。 @return 返回请求url的return信息。
curlGet
php
fecshop/yii2_fecshop
services/payment/Paypal.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/Paypal.php
BSD-3-Clause
protected function isNotDistort() { $increment_id = $this->_postData['invoice']; $mc_gross = $this->_postData['mc_gross']; $mc_currency = $this->_postData['mc_currency']; if ($increment_id && $mc_gross && $mc_currency) { $this->_order = Yii::$service->order->getByIncrementId($increment_id); if ($this->_order) { $order_currency_code = $this->_order['order_currency_code']; if ($order_currency_code == $mc_currency) { // 核对订单总额 $currentCurrencyGrandTotal = $this->_order['grand_total']; // if (round($currentCurrencyGrandTotal, 2) == round($mc_gross, 2)) { // 因为float精度问题,使用高精度函数进行比较,精度到2位小数 if(bccomp($currentCurrencyGrandTotal, $mc_gross, 2) == 0){ return true; } } } } return false; }
验证订单数据是否被篡改。 通过订单号找到订单,查看是否存在 验证邮件地址,订单金额是否准确。
isNotDistort
php
fecshop/yii2_fecshop
services/payment/Paypal.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/Paypal.php
BSD-3-Clause
public function getExpressCheckoutUrl($token) { if ($token) { //$webscrUrl = Yii::$service->payment->getExpressWebscrUrl($this->express_payment_method); if ($this->_env == Yii::$service->payment->env_sanbox) { $webscrUrl = 'https://www.sandbox.paypal.com/cgi-bin/webscr'; } else { $webscrUrl = 'https://www.paypal.com/cgi-bin/webscr'; } return $webscrUrl.'?cmd=_express-checkout&token='.urlencode($token); } }
@param $token | String , 通过 下面的 PPHttpPost5 方法返回的paypal express的token @return String,通过token得到跳转的 paypal url,通过这个url跳转到paypal登录页面,进行支付的开始
getExpressCheckoutUrl
php
fecshop/yii2_fecshop
services/payment/Paypal.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/Paypal.php
BSD-3-Clause
public function getStandardCheckoutUrl($token) { if ($token) { if ($this->_env == Yii::$service->payment->env_sanbox) { $webscrUrl = 'https://www.sandbox.paypal.com/cgi-bin/webscr'; } else { $webscrUrl = 'https://www.paypal.com/cgi-bin/webscr'; } return $webscrUrl.'?useraction=commit&cmd=_express-checkout&token='.urlencode($token); } }
@param $token | String , 通过 下面的 PPHttpPost5 方法返回的paypal standard的token @return String,通过token得到跳转的 paypal url,通过这个url跳转到paypal登录页面,进行支付的开始
getStandardCheckoutUrl
php
fecshop/yii2_fecshop
services/payment/Paypal.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/Paypal.php
BSD-3-Clause
public function getExpressAddressNvpStr() { $nvp_array = []; $nvp_array['VERSION'] = Yii::$service->payment->paypal->version; $nvp_array['token'] = Yii::$service->payment->paypal->getToken(); return $this->getRequestUrlStrByArray($nvp_array); }
【paypal快捷支付部分】将参数组合成字符串。 通过api token,从paypal获取用户在paypal保存的货运地址。
getExpressAddressNvpStr
php
fecshop/yii2_fecshop
services/payment/Paypal.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/Paypal.php
BSD-3-Clause
public function getToken() { if (!$this->token) { $token = Yii::$app->request->get('token'); if (!$token) { $token = Yii::$app->request->post('token'); } $token = \Yii::$service->helper->htmlEncode($token); if ($token) { $this->token = $token; } } return $this->token; }
从get参数里得到paypal支付的token
getToken
php
fecshop/yii2_fecshop
services/payment/Paypal.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/Paypal.php
BSD-3-Clause
public function getPayerID() { if (!$this->payerID) { $payerID = Yii::$app->request->get('PayerID'); if (!$payerID) { $payerID = Yii::$app->request->post('PayerID'); } $payerID = \Yii::$service->helper->htmlEncode($payerID); if ($payerID) { $this->payerID = $payerID; } } return $this->payerID; }
从get参数里得到paypal支付的PayerID
getPayerID
php
fecshop/yii2_fecshop
services/payment/Paypal.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/Paypal.php
BSD-3-Clause
public function updateOrderPayment($doCheckoutReturn, $token) { if ($doCheckoutReturn) { $order = Yii::$service->order->getByPaymentToken($token); $order_cancel_status = Yii::$service->order->payment_status_canceled; // 如果订单状态被取消,那么不能进行支付。 if ($order['order_status'] == $order_cancel_status) { Yii::$service->helper->errors->add('The order status has been canceled and you can not pay for item ,you can create a new order to pay'); return false; } $updateArr = []; if ($order['increment_id']) { $updateArr['txn_id'] = $doCheckoutReturn['PAYMENTINFO_0_TRANSACTIONID']; $updateArr['txn_type'] = $doCheckoutReturn['PAYMENTINFO_0_TRANSACTIONTYPE']; $PAYMENTINFO_0_AMT = $doCheckoutReturn['PAYMENTINFO_0_AMT']; $updateArr['payment_fee'] = $doCheckoutReturn['PAYMENTINFO_0_FEEAMT']; $currency = $doCheckoutReturn['PAYMENTINFO_0_CURRENCYCODE']; $updateArr['base_payment_fee'] = Yii::$service->page->currency->getBaseCurrencyPrice($updateArr['payment_fee'], $currency); $updateArr['payer_id'] = $this->getPayerID(); $updateArr['correlation_id'] = $doCheckoutReturn['CORRELATIONID']; $updateArr['protection_eligibility'] = $doCheckoutReturn['PAYMENTINFO_0_PROTECTIONELIGIBILITY']; $updateArr['protection_eligibility_type'] = $doCheckoutReturn['PAYMENTINFO_0_PROTECTIONELIGIBILITYTYPE']; $updateArr['secure_merchant_account_id'] = $doCheckoutReturn['PAYMENTINFO_0_SECUREMERCHANTACCOUNTID']; $updateArr['build'] = $doCheckoutReturn['BUILD']; $updateArr['payment_type'] = $doCheckoutReturn['PAYMENTINFO_0_PAYMENTTYPE']; $updateArr['paypal_order_datetime'] = date('Y-m-d H:i:s', $doCheckoutReturn['PAYMENTINFO_0_ORDERTIME']); $PAYMENTINFO_0_PAYMENTSTATUS = $doCheckoutReturn['PAYMENTINFO_0_PAYMENTSTATUS']; $updateArr['updated_at'] = time(); if ( strtolower($PAYMENTINFO_0_PAYMENTSTATUS) == $this->payment_status_completed || strtolower($PAYMENTINFO_0_PAYMENTSTATUS) == $this->payment_status_processed ) { $order_status = Yii::$service->order->payment_status_confirmed; if ($currency == $order['order_currency_code'] && $PAYMENTINFO_0_AMT == $order['grand_total']) { $updateArr['order_status'] = $order_status; $updateColumn = $order->updateAll( $updateArr, [ 'and', ['order_id' => $order['order_id']], ['in','order_status',$this->_allowChangOrderStatus] ] ); // 因为IPN消息可能不止发送一次,但是这里只允许一次, // 如果重复发送,$updateColumn 的更新返回值将为0 if (!empty($updateColumn)) { // 执行订单支付成功后的事情。 Yii::$service->order->orderPaymentCompleteEvent($order['increment_id']); } return true; } else { // 金额不一致,判定为欺诈 Yii::$service->helper->errors->add('The amount of payment is inconsistent with the amount of the order'); $order_status = Yii::$service->order->payment_status_suspected_fraud; $updateArr['order_status'] = $order_status; $updateColumn = $order->updateAll( $updateArr, [ 'and', ['order_id' => $order['order_id']], ['in','order_status',$this->_allowChangOrderStatus] ] ); } } elseif (strtolower($PAYMENTINFO_0_PAYMENTSTATUS) == $this->payment_status_pending) { // 这种情况代表paypal 信用卡预售,需要等待一段时间才知道是否收到钱 $order_status = Yii::$service->order->payment_status_processing; if ($currency == $order['order_currency_code'] && $PAYMENTINFO_0_AMT == $order['grand_total']) { $updateArr['order_status'] = $order_status; $updateColumn = $order->updateAll( $updateArr, [ 'and', ['order_id' => $order['order_id']], ['order_status' => Yii::$service->order->payment_status_pending] ] ); // 这种情况并没有接收到paypal的钱,只是一种支付等待状态, // 因此,对于这种支付状态,视为正常订单,但是没有支付成功,需要延迟等待,如果支付成功,paypal会继续发送IPN消息。 return true; } else { // 金额不一致,判定为欺诈 Yii::$service->helper->errors->add('The amount of payment is inconsistent with the amount of the order'); $order_status = Yii::$service->order->payment_status_suspected_fraud; $updateArr['order_status'] = $order_status; $updateColumn = $order->updateAll( $updateArr, [ 'and', ['order_id' => $order['order_id']], ['in','order_status',$this->_allowChangOrderStatus] ] ); } } else { Yii::$service->helper->errors->add('paypal payment is not complete , current payment status is {payment_status}', ['payment_status' => $PAYMENTINFO_0_PAYMENTSTATUS]); } } else { Yii::$service->helper->errors->add('current order is not exist'); } } else { Yii::$service->helper->errors->add('CheckoutReturn is empty'); } return false; }
@param $doCheckoutReturn | Array , paypal付款状态提交后,更新订单的支付部分的信息。
updateOrderPayment
php
fecshop/yii2_fecshop
services/payment/Paypal.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/Paypal.php
BSD-3-Clause
public function Queryorder($transaction_id) { $input = new WxPayOrderQuery(); $input->SetTransaction_id($transaction_id); $result = WxPayApi::orderQuery($input); \Yii::info("query:" . json_encode($result), 'fecshop_debug'); if (array_key_exists("return_code", $result) && array_key_exists("result_code", $result) && $result["return_code"] == "SUCCESS" && $result["result_code"] == "SUCCESS") { return true; } return false; }
查询订单
Queryorder
php
fecshop/yii2_fecshop
services/payment/wxpay/notify.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/wxpay/notify.php
BSD-3-Clause
public function NotifyProcess($data, &$msg) { \Yii::info("call back:" . json_encode($data), 'fecshop_debug'); $notfiyOutput = []; if (!array_key_exists("transaction_id", $data)) { $msg = "输入参数不正确"; return false; } //查询订单,判断订单真实性 if (!$this->Queryorder($data["transaction_id"])) { $msg = "订单查询失败"; return false; } $arr = $this->getDataArray($data); return \Yii::$service->payment->wxpay->ipnUpdateOrder($arr); }
重写回调处理函数
NotifyProcess
php
fecshop/yii2_fecshop
services/payment/wxpay/notify.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/payment/wxpay/notify.php
BSD-3-Clause
protected function checkPostDataRequireAndInt($post) { $model = $this->_productModel; if (empty($post) || !is_array($post)) { $this->_error[] = 'post data is empty or is not array'; return ; } // 产品名字:【必填】 【多语言属性】 $name = $post['name']; if (!$name) { $this->_error[] = '[name] can not empty'; } else { $this->_param['name'] = $name; } if (!Yii::$service->fecshoplang->getDefaultLangAttrVal($name, 'name')) { $defaultLangAttrName = Yii::$service->fecshoplang->getDefaultLangAttrName('name'); $this->_error[] = '[name.'.$defaultLangAttrName.'] can not empty'; } // 产品描述:【必填】 【多语言】 $description = $post['description']; if (!$description) { $this->_error[] = '[description] can not empty'; } else { $this->_param['description'] = $description; } if (!Yii::$service->fecshoplang->getDefaultLangAttrVal($description, 'description')) { $defaultLangAttrName = Yii::$service->fecshoplang->getDefaultLangAttrName('description'); $this->_error[] = '[description.'.$defaultLangAttrName.'] can not empty'; } // 产品spu:【必填】 $spu = $post['spu']; if (!$spu) { $this->_error[] = '[spu] can not empty'; } else { $this->_param['spu'] = $spu; } // 产品sku:【必填】 $sku = $post['sku']; if (!$sku) { $this->_error[] = '[sku] can not empty'; } else { $this->_param['sku'] = $sku; } // 产品重量Kg:【必填】强制转换成float类型 $weight = (float)$post['weight']; if (!$weight && $weight !== 0) { $this->_error[] = '[weight] can not empty'; } else { $this->_param['weight'] = $weight; } // 产品价格:【必填】 强制转换成float类型 $price = (float)$post['price']; if (!$price) { $this->_error[] = '[price] can not empty'; } else { $this->_param['price'] = $price; } // 产品库存:【选填】,如果不在合法范围内则强制为0 $qty = (int)$post['qty']; if (!$qty || $qty <0) { $qty = 0; } $this->_param['qty'] = $qty; // 选填 数组 $category = $post['category']; if ($category && !is_array($category)) { $this->_error[] = '[category] must be array'; } if ($category) { $this->_param['category'] = $category; } // 选填, 是否下架, 如果不存在,或者不合法,则会被设置成有库存状态 $is_in_stock = $post['is_in_stock']; $allow_stock_arr = [$model::IS_IN_STOCK,$model::OUT_STOCK]; if (!$is_in_stock || !in_array($is_in_stock, $allow_stock_arr)) { $is_in_stock = $model::IS_IN_STOCK; } $this->_param['is_in_stock'] = $is_in_stock; // 选填 特价 $special_price = (float)$post['special_price']; if ($special_price) { $this->_param['special_price'] = $special_price; } // 选填 特价开始时间 开始时间只要“年-月-日”部分,其他部分去除,然后取00:00:00的数据 $special_from = $post['special_from']; if ($special_from) { $special_from = substr($special_from, 0, 10).' 00:00:00'; $special_from = strtotime($special_from); if ($special_from) { $this->_param['special_from'] = $special_from; } } // 选填 特价结束时间 开始时间只要“年-月-日”部分,其他部分去除,然后取23:59:59的数据 $special_to = $post['special_to']; if ($special_to) { $special_to = substr($special_to, 0, 10).' 23:59:59'; $special_to = strtotime($special_to); if ($special_to) { $this->_param['special_to'] = $special_to; } } // 选填 $tier_price = $post['tier_price']; if ($tier_price) { /** 检查数据个数是否如下 * "tier_price": [ * { * "qty": NumberLong(2), * "price": 17 * }, * { * "qty": NumberLong(4), * "price": 16 * } * ], */ if (is_array($tier_price)) { $correct = 1; foreach ($tier_price as $one) { if ( !isset($one['qty']) || !$one['qty'] || !isset($one['price']) || !$one['price'] ) { $correct = 0; break; } } if (!$correct) { $this->_error[] = '[tier_price] data format is error , you can see doc example data'; } $this->_param['tier_price'] = $tier_price; } else { $this->_error[] = '[tier_price] data must be array'; } } // 选填 开始时间只要“年-月-日”部分,其他部分去除,然后取00:00:00的数据 $new_product_from = $post['new_product_from']; if ($new_product_from) { $new_product_from = substr($new_product_from, 0, 10).' 00:00:00'; $new_product_from = strtotime($new_product_from); if ($new_product_from) { $this->_param['new_product_from'] = $new_product_from; } } // 选填 结束时间只要“年-月-日”部分,其他部分去除,然后取23:59:59的数据 $new_product_to = $post['new_product_to']; if ($new_product_to) { $new_product_to = substr($new_product_to, 0, 10).' 23:59:59'; $new_product_to = strtotime($new_product_to); if ($new_product_to) { $this->_param['new_product_to'] = $new_product_to; } } // 选填 产品的成本价 $cost_price = (float)$post['cost_price']; if ($cost_price) { $this->_param['cost_price'] = $cost_price; } // 选填 【多语言类型】产品的简单描述 $short_description = $post['short_description']; if (!empty($short_description) && is_array($short_description)) { $this->_param['short_description'] = $short_description; } // 必填 $attr_group = $post['attr_group']; $customAttrGroup = Yii::$service->product->customAttrGroup; if (!$attr_group) { $this->_error[] = '[attr_group] can not empty'; } elseif (!isset($customAttrGroup[$attr_group])) { $this->_error[] = '[attr_group:'.$attr_group.'] is not config is Product Service Config File'; } else { $this->_param['attr_group'] = $attr_group; } // 选填 $remark = $post['remark']; if ($remark) { $this->_param['remark'] = $remark; } // 选填 $relation_sku = $post['relation_sku']; if ($relation_sku) { $this->_param['relation_sku'] = $relation_sku; } // 选填 $buy_also_buy_sku = $post['buy_also_buy_sku']; if ($buy_also_buy_sku) { $this->_param['buy_also_buy_sku'] = $buy_also_buy_sku; } // 选填 $see_also_see_sku = $post['see_also_see_sku']; if ($see_also_see_sku) { $this->_param['see_also_see_sku'] = $see_also_see_sku; } // 选填 产品状态 $status = $post['status']; $allowStatus = [$model::STATUS_ENABLE,$model::STATUS_DISABLE]; if (!$status || !in_array($status, $allowStatus)) { $status = $model::STATUS_ENABLE; } $this->_param['status'] = $status; // 选填 产品的url key $url_key = $post['url_key']; if ($url_key) { $this->_param['url_key'] = $url_key; } /** * 选填 产品的图片 * 图片的格式如下: * "image": { * "gallery": [ * { * "image": "/2/01/20161024170457_13851.jpg", * "label": "", * "sort_order": "" * }, * { * "image": "/2/01/20161024170457_21098.jpg", * "label": "", * "sort_order": "" * }, * { * "image": "/2/01/20161101155240_26690.jpg", * "label": "", * "sort_order": "" * }, * { * "image": "/2/01/20161101155240_56328.jpg", * "label": "", * "sort_order": "" * }, * { * "image": "/2/01/20161101155240_94256.jpg", * "label": "", * "sort_order": "" * } * ], * "main": { * "image": "/2/01/20161024170457_10036.jpg", * "label": "", * "sort_order": "" * } * }, */ $image = $post['image']; if ($image) { if (isset($image['main'])) { if (isset($image['main']['image']) && $image['main']['image']) { // 正确 $image['main']['is_thumbnails'] = 1; $image['main']['is_detail'] = 1; } else { $this->_error[] = 'image[\'main\'][\'image\'] must exist '; } } if (isset($image['gallery'])) { if (is_array($image['gallery']) && !empty($image['gallery'])) { foreach ($image['gallery'] as $one) { if (!isset($one['image']) || !$one['image']) { $this->_error[] = 'image[\'gallery\'][][\'image\'] must exist '; } } } else { $this->_error[] = 'image[\'gallery\'] must be array '; } } $this->_param['image'] = $image; } // 选填 多语言 $title = $post['title']; if (!empty($title) && is_array($title)) { $this->_param['title'] = $title; } // 选填 多语言 $meta_keywords = $post['meta_keywords']; if (!empty($meta_keywords) && is_array($meta_keywords)) { $this->_param['meta_keywords'] = $meta_keywords; } // 选填 多语言 $meta_description = $post['meta_description']; if (!empty($meta_description) && is_array($meta_description)) { $this->_param['meta_description'] = $meta_description; } // 属性组属性,这里没有做强制的必填判断,有值就会加入 $this->_param 中。 $attrInfo = Yii::$service->product->getGroupAttrInfo($attr_group); if (is_array($attrInfo) && !empty($attrInfo)) { foreach ($attrInfo as $attrName => $info) { if (isset($post[$attrName]) && $post[$attrName]) { $attrVal = $post[$attrName]; if (isset($info['display']['type']) && $info['display']['type'] === 'select') { $selectArr = $info['display']['data']; if (!is_array($selectArr) || empty($selectArr)) { $this->_error[] = 'GroutAttr:'.$attrName.' config is empty ,you must reConfig it'; } $allowValArr = array_keys($selectArr); if (is_array($allowValArr) && in_array($attrVal, $allowValArr)) { $this->_param[$attrName] = $attrVal; } else { $this->_error[] = '['.$attrName.':'.$attrVal.'] must be in '.implode(',', $allowValArr); } } else { $this->_param[$attrName] = $attrVal; } } } } }
@param $post | Array , 数组 检查产品数据的必填以及数据的初始化 1. 产品必填数据是否填写,不填写就报错 2. 产品选填信息如果没有填写,如果可以初始化,那么就初始化 3. 对了列举类型,譬如产品状态,只能填写1和2,填写其他的是不允许的,对于这种情况,会忽略掉填写的值, 如果可以初始化,给初始化一个默认的正确的值,如果不可以初始化,譬如颜色尺码之类的属性,则报错。 4. 类型的强制转换,譬如价格,强制转换成float 5. 数据结构的检查,譬如图片 custom option ,是一个大数组,需要进行严格的检查。
checkPostDataRequireAndInt
php
fecshop/yii2_fecshop
services/product/ProductApi.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/product/ProductApi.php
BSD-3-Clause
protected function checkShopfwPostDataRequireAndInt($post) { $model = $this->_productModel; if (empty($post) || !is_array($post)) { $this->_error[] = 'post data is empty or is not array'; return ; } // 产品名字:【必填】 【多语言属性】 $name = $post['name']; if (!$name) { $this->_error[] = '[name] can not empty'; } else { $this->_param['name'] = $name; } if (!Yii::$service->fecshoplang->getDefaultLangAttrVal($name, 'name')) { $defaultLangAttrName = Yii::$service->fecshoplang->getDefaultLangAttrName('name'); $this->_error[] = '[name.'.$defaultLangAttrName.'] can not empty'; } // 产品描述:【必填】 【多语言】 $description = $post['description']; if (!$description) { $this->_error[] = '[description] can not empty'; } else { $this->_param['description'] = $description; } if (!Yii::$service->fecshoplang->getDefaultLangAttrVal($description, 'description')) { $defaultLangAttrName = Yii::$service->fecshoplang->getDefaultLangAttrName('description'); $this->_error[] = '[description.'.$defaultLangAttrName.'] can not empty'; } // 产品重量Kg:【必填】强制转换成float类型 $weight = (float)$post['weight']; if (!$weight && $weight !== 0) { $this->_error[] = '[weight] can not empty'; } else { $this->_param['weight'] = $weight; } $third_refer_url = $post['third_refer_url']; if (!$third_refer_url) { $this->_error[] = '[third_refer_url] can not empty'; } else { $this->_param['third_refer_url'] = $third_refer_url; } $third_refer_code = $post['third_refer_code']; if (!$third_refer_code) { $this->_error[] = '[third_refer_code] can not empty'; } else { $this->_param['third_refer_code'] = $third_refer_code; } $third_product_code = $post['third_product_code']; if ($third_product_code) { $this->_param['third_product_code'] = $third_product_code; } // 产品价格:【必填】 强制转换成float类型 $price = (float)$post['price']; if (!$price) { $this->_error[] = '[price] can not empty'; } else { $this->_param['price'] = $price; } // 产品库存:【选填】,如果不在合法范围内则强制为0 $qty = (int)$post['qty']; if (!$qty || $qty <0) { $qty = 0; } $this->_param['qty'] = $qty; // 选填 数组 $category = $post['category']; if ($category && !is_array($category)) { $this->_error[] = '[category] must be array'; } if ($category) { $this->_param['category'] = $category; } // 选填, 是否下架, 如果不存在,或者不合法,则会被设置成有库存状态 $is_in_stock = $post['is_in_stock']; $allow_stock_arr = [$model::IS_IN_STOCK,$model::OUT_STOCK]; if (!$is_in_stock || !in_array($is_in_stock, $allow_stock_arr)) { $is_in_stock = $model::IS_IN_STOCK; } $this->_param['is_in_stock'] = $is_in_stock; // 选填 特价 $special_price = (float)$post['special_price']; if ($special_price) { $this->_param['special_price'] = $special_price; } // 选填 特价开始时间 开始时间只要“年-月-日”部分,其他部分去除,然后取00:00:00的数据 $special_from = $post['special_from']; if ($special_from) { $special_from = substr($special_from, 0, 10).' 00:00:00'; $special_from = strtotime($special_from); if ($special_from) { $this->_param['special_from'] = $special_from; } } // 选填 特价结束时间 开始时间只要“年-月-日”部分,其他部分去除,然后取23:59:59的数据 $special_to = $post['special_to']; if ($special_to) { $special_to = substr($special_to, 0, 10).' 23:59:59'; $special_to = strtotime($special_to); if ($special_to) { $this->_param['special_to'] = $special_to; } } // 选填 $tier_price = $post['tier_price']; if ($tier_price) { /** 检查数据个数是否如下 * "tier_price": [ * { * "qty": NumberLong(2), * "price": 17 * }, * { * "qty": NumberLong(4), * "price": 16 * } * ], */ if (is_array($tier_price)) { $correct = 1; foreach ($tier_price as $one) { if ( !isset($one['qty']) || !$one['qty'] || !isset($one['price']) || !$one['price'] ) { $correct = 0; break; } } if (!$correct) { $this->_error[] = '[tier_price] data format is error , you can see doc example data'; } $this->_param['tier_price'] = $tier_price; } else { $this->_error[] = '[tier_price] data must be array'; } } // 选填 开始时间只要“年-月-日”部分,其他部分去除,然后取00:00:00的数据 $new_product_from = $post['new_product_from']; if ($new_product_from) { $new_product_from = substr($new_product_from, 0, 10).' 00:00:00'; $new_product_from = strtotime($new_product_from); if ($new_product_from) { $this->_param['new_product_from'] = $new_product_from; } } // 选填 结束时间只要“年-月-日”部分,其他部分去除,然后取23:59:59的数据 $new_product_to = $post['new_product_to']; if ($new_product_to) { $new_product_to = substr($new_product_to, 0, 10).' 23:59:59'; $new_product_to = strtotime($new_product_to); if ($new_product_to) { $this->_param['new_product_to'] = $new_product_to; } } // 选填 产品的成本价 $cost_price = (float)$post['cost_price']; if ($cost_price) { $this->_param['cost_price'] = $cost_price; } // 选填 【多语言类型】产品的简单描述 $short_description = $post['short_description']; if (!empty($short_description) && is_array($short_description)) { $this->_param['short_description'] = $short_description; } // 必填 $attr_group = $post['attr_group']; $customAttrGroup = Yii::$service->product->customAttrGroup; if (!$attr_group) { $this->_error[] = '[attr_group] can not empty'; } elseif (!isset($customAttrGroup[$attr_group])) { $this->_error[] = '[attr_group:'.$attr_group.'] is not config is Product Service Config File'; } else { $this->_param['attr_group'] = $attr_group; } // 选填 $remark = $post['remark']; if ($remark) { $this->_param['remark'] = $remark; } // 选填 产品状态 $status = $post['status']; $allowStatus = [$model::STATUS_ENABLE,$model::STATUS_DISABLE]; if (!$status || !in_array($status, $allowStatus)) { $status = $model::STATUS_ENABLE; } $this->_param['status'] = $status; // 选填 产品的url key $url_key = $post['url_key']; if ($url_key) { $this->_param['url_key'] = $url_key; } $image = $post['image']; if ($image) { if (isset($image['main'])) { if (isset($image['main']['image']) && $image['main']['image']) { // 正确 $image['main']['is_thumbnails'] = 1; $image['main']['is_detail'] = 1; } else { $this->_error[] = 'image[\'main\'][\'image\'] must exist '; } } if (isset($image['gallery']) && $image['gallery']) { if (is_array($image['gallery']) && !empty($image['gallery'])) { foreach ($image['gallery'] as $one) { if (!isset($one['image']) || !$one['image']) { $this->_error[] = 'image[\'gallery\'][][\'image\'] must exist '; } } } else { $this->_error[] = 'image[\'gallery\'] must be array '; } } $this->_param['image'] = $image; } // 选填 多语言 $title = $post['title']; if (!empty($title) && is_array($title)) { $this->_param['title'] = $title; } if (isset($post['brand_id']) && $post['brand_id']) { $this->_param['brand_id'] = $post['brand_id']; } // 选填 多语言 $meta_keywords = $post['meta_keywords']; if (!empty($meta_keywords) && is_array($meta_keywords)) { $this->_param['meta_keywords'] = $meta_keywords; } // 选填 多语言 $meta_description = $post['meta_description']; if (!empty($meta_description) && is_array($meta_description)) { $this->_param['meta_description'] = $meta_description; } // 属性组属性,这里没有做强制的必填判断,有值就会加入 $this->_param 中。 $attrInfo = Yii::$service->product->getGroupAttrInfo($attr_group); $attr_group_normal = []; if (isset($post['attr_group_normal']) && is_array($post['attr_group_normal']) && !empty($post['attr_group_normal'])) { $attr_group_normal = $post['attr_group_normal']; } $attr_group_custom = []; if (isset($post['attr_group_custom']) && is_array($post['attr_group_custom']) && !empty($post['attr_group_custom'])) { $attr_group_custom = $post['attr_group_custom']; } if (is_array($attrInfo) && !empty($attrInfo)) { foreach ($attrInfo as $attrName => $info) { if ($info['attr_type'] == 'general_attr') { $attrVal = $attr_group_normal[$attrName]; } else if ($info['attr_type'] == 'spu_attr') { $attrVal = $attr_group_custom[$attrName]; } $this->_param[$attrName] = $attrVal; //if (isset($post[$attrName]) && $post[$attrName]) { //$attrVal = $post[$attrName]; /* if (isset($info['display']['type']) && $info['display']['type'] === 'select') { $selectArr = $info['display']['data']; if (!is_array($selectArr) || empty($selectArr)) { $this->_error[] = 'GroutAttr:'.$attrName.' config is empty ,you must reConfig it'; } $allowValArr = array_keys($selectArr); if (is_array($allowValArr) && in_array($attrVal, $allowValArr)) { $this->_param[$attrName] = $attrVal; } else { $this->_error[] = '['.$attrName.':'.$attrVal.'] must be in '.implode(',', $allowValArr); } } else { $this->_param[$attrName] = $attrVal; } */ //} } } //var_dump($this->_param);exit; }
@param $post | Array , 数组 检查产品数据的必填以及数据的初始化 1. 产品必填数据是否填写,不填写就报错 2. 产品选填信息如果没有填写,如果可以初始化,那么就初始化 3. 对了列举类型,譬如产品状态,只能填写1和2,填写其他的是不允许的,对于这种情况,会忽略掉填写的值, 如果可以初始化,给初始化一个默认的正确的值,如果不可以初始化,譬如颜色尺码之类的属性,则报错。 4. 类型的强制转换,譬如价格,强制转换成float 5. 数据结构的检查,譬如图片 custom option ,是一个大数组,需要进行严格的检查。
checkShopfwPostDataRequireAndInt
php
fecshop/yii2_fecshop
services/product/ProductApi.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/product/ProductApi.php
BSD-3-Clause
public function changeToMongoStorage() { $this->storage = 'FavoriteMongodb'; $currentService = $this->getStorageService($this); $this->_favorite = new $currentService(); }
动态更改为mongodb model
changeToMongoStorage
php
fecshop/yii2_fecshop
services/product/Favorite.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/product/Favorite.php
BSD-3-Clause
public function changeToMysqlStorage() { $this->storage = 'FavoriteMysqldb'; $currentService = $this->getStorageService($this); $this->_favorite = new $currentService(); }
动态更改为mongodb model
changeToMysqlStorage
php
fecshop/yii2_fecshop
services/product/Favorite.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/product/Favorite.php
BSD-3-Clause
public function getByProductIdAndUserId($product_id, $user_id = '') { return $this->_favorite->getByProductIdAndUserId($product_id, $user_id); }
@param $product_id | String , 产品id @param $user_id | Int ,用户id @return $this->_favoriteModel ,如果用户在该产品收藏,则返回相应model。
getByProductIdAndUserId
php
fecshop/yii2_fecshop
services/product/Favorite.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/product/Favorite.php
BSD-3-Clause
public function add($product_id, $user_id) { return $this->_favorite->add($product_id, $user_id); }
@param $product_id | String , 产品id @param $user_id | Int ,用户id @return boolean,用户收藏该产品时,执行的操作。
add
php
fecshop/yii2_fecshop
services/product/Favorite.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/product/Favorite.php
BSD-3-Clause
public function updateProductFavoriteCount($product_id) { return $this->_favorite->updateProductFavoriteCount($product_id); }
@param $product_id | String 更新该产品被收藏的总次数。
updateProductFavoriteCount
php
fecshop/yii2_fecshop
services/product/Favorite.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/product/Favorite.php
BSD-3-Clause
public function updateUserFavoriteCount($user_id = '') { return $this->_favorite->updateUserFavoriteCount($user_id); }
@param $user_id | Int 更新该用户总的收藏产品个数到用户表
updateUserFavoriteCount
php
fecshop/yii2_fecshop
services/product/Favorite.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/product/Favorite.php
BSD-3-Clause
public function removeByProductIdAndUserId($product_id, $user_id) { return $this->_favorite->removeByProductIdAndUserId($product_id, $user_id); }
@param $favorite_id | string 通过id删除favorite
removeByProductIdAndUserId
php
fecshop/yii2_fecshop
services/product/Favorite.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/product/Favorite.php
BSD-3-Clause
public function currentUserRemove($favorite_id) { return $this->_favorite->currentUserRemove($favorite_id); }
@param $favorite_id | string 通过id删除favorite
currentUserRemove
php
fecshop/yii2_fecshop
services/product/Favorite.php
https://github.com/fecshop/yii2_fecshop/blob/master/services/product/Favorite.php
BSD-3-Clause