Javascript操作iframe框架经典案例

 更新时间:2016年11月25日 15:35  点击:1595
操作iframe对于许多的前段来讲觉得是一个不可靠的方式了,其实操作iframe是非常的不错并且兼容性也好,下面我们来看一个经典的关于操作iframe的例子。

虽然我们在web开发中使用iframe比较少,但是iframe还是有它值得使用的场景,比如嵌入外部广告等。在使用iframe过程中我们可能会遇到很多问题,例如iframe父子窗口传值,iframe自适应高度,iframe跨域通信等等。


实际应用中,我们常常要在父窗口中直接获取子窗口页面的元素,并对其进行操作。今天我来使用实例给大家介绍如何使用Javascript来进行iframe父子窗口之间相互操作dom对象,开始动手。
HTML

为了更好的讲解和演示,我们准备3个页面,父级页面index.html的html结构如下。另外两个子页面分别为iframeA.html和iframeB.html。我们需要演示通过父页面获取和设置子页面iframeA.html中元素的值,以及演示通过子页面iframeB.html设置子页面iframeA.html相关元素的值以及操作父页面index.html元素。
 
<div class="opt_btn">
    <button onclick="getValiframeA();">父窗口获取iframeA中的值</button>
    <button onclick="setValiframeA();">父窗口设置iframeA中的值</button>
    <button onclick="setBgiframeA();">父窗口设置iframeA的h1标签背景色</button>
</div>

<div id="result">--操作结果--</div>
 
<div class="frames">
    <iframe id="wIframeA" name="myiframeA" src="iframeA.html" scrolling="no" frameborder="1"></iframe> 
    <iframe id="wIframeB" name="myiframeB" src="iframeB.html" scrolling="no" frameborder="1"></iframe>
</div>
iframeA.html布置一个h1标题,以及一个输入框和一个p段落,结构如下:
 
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>helloweba.com</title>
</head>
 
<body>
<h1 id="title">iframe A</h1> 
<input type="text" id="iframeA_ipt" name="iframeA_ipt" value="123">
<p id="hello">helloweba.com欢迎您!</p> 
</body>
</html>

iframeB.html同样布置h1标题和段落以及输入框。iframe有两个按钮,调用了javascript,相关代码等下在js部分会描述。
 
<html>
<head>
<meta charset="utf-8">
<title>helloweba.com</title>
</head>
 
<body>
<h1>iframe B</h1> 
<p id="hello">Helloweb.com</p> 
<input type="text" id="iframeB_ipt" name="iframeB_ipt" value="1,2,3,4">
<button onclick="child4parent();">iframeB子窗口操作父窗口</button> 
<button onclick="child4child();">iframeB操作子窗口iframeA</button> 
 
</body>
</html>

Javascript

页面html都布置好了,现在我们来看Javascript部分。
首先我们来看index.html父级页面的操作。JS操作iframe里的dom可是使用contentWindow属性,contentWindow属性是指指定的frame或者iframe所在的window对象,在IE中iframe或者frame的contentWindow属性可以省略,但在Firefox中如果要对iframe对象进行编辑则,必须指定contentWindow属性,contentWindow属性支持所有主流浏览器。
我们自定义了函数getIFrameDOM(),传入参数iID即可获取iframe,之后就跟在当前页面获取元素的操作一样了。
 
function getIFrameDOM(iID){
    return document.getElementById(iID).contentWindow.document;
}
index.html的三个按钮操作代码如下:
 
function getValiframeA(){
    var valA = getIFrameDOM("wIframeA").getElementById('iframeA_ipt').value;
    document.getElementById("result").innerHTML = "获取了子窗口iframeA中输入框里的值:<span style='color:#f30'>"+valA+"</span>";
}
 
function setValiframeA(){
    getIFrameDOM("wIframeA").getElementById('iframeA_ipt').value = 'Helloweba';
    document.getElementById("result").innerHTML = "设置了了子窗口iframeA中输入框里的值:<span style='color:#f30'>Helloweba</span>";
}
 
function setBgiframeA(){
    getIFrameDOM("wIframeA").getElementById('title').style.background = "#ffc";
}

保存后,打开index.html看下效果,是不是操作很简单了。
好,iframeB.html的两个按钮操作调用了js,代码如下:
 
function child4child(){
    var parentDOM=parent.getIFrameDOM("wIframeA");
    parentDOM.getElementById('hello').innerHTML="<span style='color:blue;font-size:18px;background:yellow;'>看到输入框里的值变化了吗?</span>";
    parentDOM.getElementById('iframeA_ipt').value = document.getElementById("iframeB_ipt").value;
    parent.document.getElementById("result").innerHTML="子窗口iframeB操作了子窗口iframeA";
}
function child4parent(){
    var iframeB_ipt = document.getElementById("iframeB_ipt").value;
    parent.document.getElementById("result").innerHTML="<p style='background:#000;color:#fff;font-size:15px;'>子窗口传来输入框值:<span style='color:#f30'>"+iframeB_ipt+"</span></p>";
}
子页面iframeB.html可以通过使用parent.getIFrameDOM()调用了负页面的自定义函数getIFrameDOM(),从而就可以对平级的子页面iframeA.html进行操作,子页面还可以通过使用parent.document操作父级页面元素。
本文结合实例讲解了Javascript对iframe的基本操作,接下来我们会介绍iframe的应用:自适应高度以及iframe跨域问题,敬请关注。

微信开发已经是现在程序员必须要掌握的一项基本的技术了,其实做过微信开发的都知道微信接口非常的强大做起来也非常的简单,这里我们一起来看一个微信自动登陆注册的例子。


php 微信扫码 pc端自动登陆注册 用的接口scope 是snsapi_userinfo,微信登陆一个是网页授权登陆,另一个是微信联合登陆

网页授权登陆:http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html

微信联合登陆:https://open.weixin.qq.com/cgi-bin/frame?t=home/web_tmpl&lang=zh_CN

一:首先把微信链接带个标识生成二维码

比如链接为 https://open.weixin.qq.com/connect/oauth2/authorize?appid=’.$appid.’&redirect_uri=’.$url.’&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect’  我们可以在state上做文章,因为state你传入什么微信那边返回什么

可以作为服务器与微信段的一个标识

public function creatqrAction(){
 
if($_GET['app']){
$wtoken=$_COOKIE['wtoken'];
$postdata=$_SESSION['w_state'];
if($wtoken){
$postdata=$wtoken;
}
include CONFIG_PATH . 'phpqrcode/'.'phpqrcode.php'
$sh=$this->shar1();
$value="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx138697ef383a9167&redirect_uri=http://www.xxx.net/login/wcallback&response_type=code&scope=snsapi_userinfo&state=".$postdata."&connect_redirect=1#wechat_redirect";
 
$errorCorrectionLevel = "L";
 
$matrixPointSize = "5";
 
QRcode::png($value, false, $errorCorrectionLevel, $matrixPointSize);
}
 
}

此时生成了二维码 state是标识,phpqrcode可以在文章末尾下载,这样我们设置了回调地址http://www.xxx.net/login/wcallback

就可以在wcallback方法里面处理数据 插入用户 生成session,跳转登陆,pc端可以设置几秒钟ajax请求服务器,一旦获取到了

state,即实现调整,微信浏览器里处理完后可以关闭窗口,微信js可实现

document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {
WeixinJSBridge.call('closeWindow');
 
}, false);

也可以授权登陆成功后跳转到微信服务号关注页面

header("Location: weixin://profile/gh_a5e1959f9a4e");

wcallback方法做处理登陆

$code = $_GET['code'];
$state = $_GET['state'];
$setting = include CONFIG_PATH . 'setting.php'
$appid=$setting['weixin']['appid'];
$appsecret=$setting['weixin']['appsecret'];
 
if (empty($code)) $this->showMessage('授权失败');
try{
 
$token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code'
 
$token = json_decode($this->https_request($token_url));
 
}catch(Exception $e)
{
print_r($e);
}
 
if (isset($token->errcode)) {
echo '

错误:

'.$token->errcode;
echo '

错误信息:

'.$token->errmsg;
exit;
}
 
$access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;
//转成对象
$access_token = json_decode($this->https_request($access_token_url));
if (isset($access_token->errcode)) {
echo '

错误:

'.$access_token->errcode;
echo '

错误信息:

'.$access_token->errmsg;
exit;
}
$user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN'
//转成对象
$user_info = json_decode($this->https_request($user_info_url));
if (isset($user_info->errcode)) {
echo '

错误:

'.$user_info->errcode;
echo '

错误信息:

'.$user_info->errmsg;
exit;
}
//打印用户信息
// echo '

'
// print_r($user_info);
// echo '

'

phpqrcode类库下载在此不提供各位可以百度搜索下载

magento微信扫码网站自动登录的例子

https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&lang=zh_CN

查看授权后接口调用(UnionID),不难发现填写回调地址,用户确认登陆pc端即可跳转

获取UnionID方法


public function wcallbackAction(){
 
$code = $_GET['code'];
$state = $_GET['state'];
$setting = include CONFIG_PATH . 'setting.php';
$appid=$setting['weixin']['appid'];
$appsecret=$setting['weixin']['appsecret'];
 
if (empty($code)) $this->showMessage('授权失败');
try{
 
$token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
 
$token = json_decode($this->https_request($token_url));
 
}catch(Exception $e)
{
print_r($e);
}
 
if (isset($token->errcode)) {
echo '<h1>错误:</h1>'.$token->errcode;
echo '<br/><h2>错误信息:</h2>'.$token->errmsg;
exit;
}
 
$access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;
//转成对象
$access_token = json_decode($this->https_request($access_token_url));
if (isset($access_token->errcode)) {
echo '<h1>错误:</h1>'.$access_token->errcode;
echo '<br/><h2>错误信息:</h2>'.$access_token->errmsg;
exit;
}
$user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN';
//转成对象
$user_info = json_decode($this->https_request($user_info_url));
if (isset($user_info->errcode)) {
echo '<h1>错误:</h1>'.$user_info->errcode;
echo '<br/><h2>错误信息:</h2>'.$user_info->errmsg;
exit;
}
//打印用户信息
// echo '<pre>';
// print_r($user_info);
// echo '</pre>';
 
//获取unionid
 
$uid=$user_info->unionid;
 
}
 
//用户操作处理 分为再次登录和第一次登陆
 
$sql="select h_user_id from dtb_user_binded as t1 left join dtb_user_weixin as t2 on t1.u_id=t2.id where t1.u_type='".
User::$arrUtype['weixin_num_t']."' and t2.openid='$user_info->unionid'";
$h_user_id = Core_Db::getOne($sql);
if(!empty($h_user_id)){//该weixin号再次登录
 
}{//该weixin号第一次登录
 
}

获取ip地址信息的接口在网上可以找到一堆了,我们现在主要使用的是淘宝,百度,ip138及新浪的了,下面我们来看一个调用ip138的ip地址例子吧。

通过php获取ip所属地的接口,要是自己弄一个ip库的话,会比较麻烦,而且需要经常更新,所以不现实。网上找了一些接口,发现好多都不能用了,于是自己写了一个,通过抓ip138页面来提取信息。只要它不改版,这个就能永久有效。

响应比较快,小网站用此接口完全没有问题,代码如下:

<?php
 header("Content-type:text/html;charset=utf-8");
 $ip = checkip(@$_GET['ip']);
 if(!$ip)
 {
  exit( json_encode( array('error'=>1, 'msg'=>'参数ip不正确') ) );
 }
 $url = 'http://www.ip138.com/ips1388.asp?ip='.$ip.'&action=2';
 $ipInfo = file_get_contents($url);
 $ipInfo = iconv('gb2312', 'utf-8', $ipInfo);
 preg_match('/<li>本站主数据:(.*)<\/li><li>/i', $ipInfo, $info);
 if($info[1])
 {
  exit( json_encode( array('error'=>0, 'pos'=>$info[1]) ) );
 }
 else
 {
  exit( json_encode( array('error'=>1, 'msg'=>'解析失败') ) );
 }

 /**
  * 验证ip格式是否正确
  */
 function checkip($ip)
 {
  $ip = substr($ip, 0, 15); //ipv4最多只有这么长
  if( !preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $ip) )
  {
   return false;
  }
  else
  {
   return $ip;
  }
 }
?>

访问形式为:localhost/ip.php?ip=xxx.xxx.xxx.xxx。带一个参数就行了,返回为json格式的数据

一聚教程小编为各位介绍一篇php 部分缓存数据库返回数据的例子,这个例子其实是非常的实用了,希望能够帮助到大家。

$cache = new FileCache();
$new_arr = $cache->get('gsmcache');//yourkey是你为每一个要缓存的数据定义的缓存名字
if ($new_arr===false) {
 
$new_arr="数据库返回的数据";
 
$cache->set('gsmcache',$new_arr,3600);//缓存3600秒
 
}
 

<?php
/**
* 文件缓存类
*
* @copyright blog.itiwin.cn
* @author  More
* @package cache
* @version v0.1
*/
class FileCache {
/**
* @var string $cachePath 缓存文件目录
* @access public
*/
public $cachePath = './';
 
/**
* 构造函数
* @param string $path 缓存文件目录
*/
function __construct($path = NULL) {
if ($path) {
$this->cachePath = $path;
}
}
 
/**
* 析构函数
*/
function __destruct() {
//nothing
}
 
/**
* 在cache中设置键为$key的项的值,如果该项不存在,则新建一个项
* @param string $key 键值
* @param mix $var 值
* @param int $expire 到期秒数
* @param int $flag 标志位
* @return bool 如果成功则返回 TRUE,失败则返回 FALSE。
* @access public
*/
public function set($key, $var, $expire = 36000, $flag = 0) {
$value = serialize($var);
$timeout = time() + $expire;
$result = safe_file_put_contents($this->cachePath . urlencode($key) .'.cache',
$timeout . '<<%-==-%>>' . $value);
return $result;
}
 
/**
* 在cache中获取键为$key的项的值
* @param string $key 键值
* @return string 如果该项不存在,则返回false
* @access public
*/
public function get($key) {
$file = $this->cachePath . urlencode($key) .'.cache';
if (file_exists($file)) {
$content = safe_file_get_contents($file);
if ($content===false) {
return false;
}
$tmp = explode('<<%-==-%>>', $content);
$timeout = $tmp[0];
$value = $tmp[1];
if (time()>$timeout) {
 
$this->delete($key) ;//删除文件过期的
$result = false;
} else {
$result = unserialize($value);
}
} else {
$result = false;
}
return $result;
}
 
/**
* 清空cache中所有项
* @return 如果成功则返回 TRUE,失败则返回 FALSE。
* @access public
*/
public function flush() {
$fileList = FileSystem::ls($this->cachePath,array(),'asc',true);
return FileSystem::rm($fileList);
}
 
/**
* 删除在cache中键为$key的项的值
* @param string $key 键值
* @return 如果成功则返回 TRUE,失败则返回 FALSE。
* @access public
*/
public function delete($key) {
return FileSystem::rm($this->cachePath . $key .'.cache');
}
}
 
if (!function_exists('safe_file_put_contents')) {
function safe_file_put_contents($filename, $content)
{
$fp = fopen($filename, 'wb');
if ($fp) {
flock($fp, LOCK_EX);
fwrite($fp, $content);
flock($fp, LOCK_UN);
fclose($fp);
return true;
} else {
return false;
}
}
}
 
if (!function_exists('safe_file_get_contents')) {
function safe_file_get_contents($filename)
{
$fp = fopen($filename, 'rb');
if ($fp) {
flock($fp, LOCK_SH);
clearstatcache();
$filesize = filesize($filename);
if ($filesize > 0) {
$data = fread($fp, $filesize);
}
flock($fp, LOCK_UN);
fclose($fp);
return $data;
} else {
return false;
}
}
}
 

下面我们一直来看看magento2 添加支付方式payment method,有兴趣的可以和111cn小编一起来看看吧,希望例子对各位用。

一:启动文件 \app\code\Inchoo\Stripe\etc\module.xml

<?xml version="1.0"?>

<config xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance
" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">

<module name="More_Payment" schema_version="1.0.0.0" active="true">

<sequence>

<module name="Magento_Sales"/>

<module name="Magento_Payment"/>

</sequence>

<depends>

<module name="Magento_Sales"/>

<module name="Magento_Payment"/>

</depends>

</module>

</config>

二:配置文件config.xml \app\code\Inchoo\Stripe\etc\config.xml

<?xml version="1.0"?>

<config xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance
" xsi:noNamespaceSchemaLocation="../../../Magento/Core/etc/config.xsd">

<default>

<payment>

<more_payment>

<active>1</active>

<model>More\Payment\Model\Payment</model>

<payment_action>authorize_capture</payment_action>

<title>Payment</title>

<api_key backend_model="Magento\Backend\Model\Config\Backend\Encrypted" />

<cctypes>AE,VI,MC,DI,JCB</cctypes>

<allowspecific>1</allowspecific>

<min_order_total>0.50</min_order_total>

</more_payment>

</payment>

</default>

</config>


三:后台配置文件 app\code\Inchoo\Stripe\etc\adminhtml\system2.xml

<?xml version="1.0"?>

<config xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance
" xsi:noNamespaceSchemaLocation="../../../../Magento/Backend/etc/system_file.xsd">

<system>

<section id="payment" translate="label" type="text" sortOrder="400" showInDefault="1" showInWebsite="1" showInStore="1">

<group id="more_payment" translate="label" type="text" sortOrder="50" showInDefault="1" showInWebsite="1" showInStore="1">

<label>Payment</label>

 

<field id="active" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="0">

<label>Enabled</label>

<source_model>Magento\Backend\Model\Config\Source\Yesno</source_model>

</field>

<field id="title" translate="label" type="text" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1">

<label>Title</label>

</field>

<field id="api_key" translate="label" type="obscure" sortOrder="3" showInDefault="1" showInWebsite="1" showInStore="0">

<label>Api Key</label>

<backend_model>Magento\Backend\Model\Config\Backend\Encrypted</backend_model>

</field>

<field id="debug" translate="label" type="select" sortOrder="4" showInDefault="1" showInWebsite="1" showInStore="0">

<label>Debug</label>

<source_model>Magento\Backend\Model\Config\Source\Yesno</source_model>

</field>

<field id="cctypes" translate="label" type="multiselect" sortOrder="5" showInDefault="1" showInWebsite="1" showInStore="0">

<label>Credit Card Types</label>

<source_model>More\Payment\Model\Source\Cctype</source_model>

</field>

<field id="sort_order" translate="label" type="text" sortOrder="100" showInDefault="1" showInWebsite="1" showInStore="0">

<label>Sort Order</label>

</field>

<field id="allowspecific" translate="label" type="allowspecific" sortOrder="50" showInDefault="1" showInWebsite="1" showInStore="0">

<label>Payment from Applicable Countries</label>

<source_model>Magento\Payment\Model\Config\Source\Allspecificcountries</source_model>

</field>

<field id="specificcountry" translate="label" type="multiselect" sortOrder="51" showInDefault="1" showInWebsite="1" showInStore="0">

<label>Payment from Specific Countries</label>

<source_model>Magento\Directory\Model\Config\Source\Country</source_model>

</field>

<field id="min_order_total" translate="label" type="text" sortOrder="98" showInDefault="1" showInWebsite="1" showInStore="0">

<label>Minimum Order Total</label>

</field>

<field id="max_order_total" translate="label" type="text" sortOrder="99" showInDefault="1" showInWebsite="1" showInStore="0">

<label>Maximum Order Total</label>

<comment>Leave empty to disable limit</comment>

</field>

</group>

</section>

</system>

</config>


四:model类 因为我们在config.xml配置了model,所以前台点击保存支付方式的时候 触发

<?php

 

namespace More\Payment\Model;

 

class Payment extends \Magento\Payment\Model\Method\Cc

{

const CODE = 'more_payment';

 

protected $_code = self::CODE;

 

protected $_isGateway = true;

protected $_canCapture = true;

protected $_canCapturePartial = true;

protected $_canRefund = true;

protected $_canRefundInvoicePartial = true;

 

protected $_stripeApi = false;

 

protected $_minAmount = null;

protected $_maxAmount = null;

protected $_supportedCurrencyCodes = array('USD');

 

public function __construct(

\Magento\Framework\Event\ManagerInterface $eventManager,

\Magento\Payment\Helper\Data $paymentData,

\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,

\Magento\Framework\Logger\AdapterFactory $logAdapterFactory,

\Magento\Framework\Logger $logger,

\Magento\Framework\Module\ModuleListInterface $moduleList,

\Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,

\Magento\Centinel\Model\Service $centinelService,

\Stripe\Api $stripe,

array $data = array()

) {

parent::__construct($eventManager, $paymentData, $scopeConfig, $logAdapterFactory, $logger, $moduleList, $localeDate, $centinelService, $data);

 

$this->_stripeApi = $stripe;

// $this->_stripeApi->setApiKey(

// $this->getConfigData('api_key')

// );

 

$this->_minAmount = $this->getConfigData('min_order_total');

$this->_maxAmount = $this->getConfigData('max_order_total');

}

 

/**

* 支付捕获方法

* *

* @param \Magento\Framework\Object $payment

* @param float $amount

* @return $this

* @throws \Magento\Framework\Model\Exception

*/

public function capture(\Magento\Framework\Object $payment, $amount)

{

/** @var Magento\Sales\Model\Order $order */

$order = $payment->getOrder();

 

/** @var Magento\Sales\Model\Order\Address $billing */

$billing = $order->getBillingAddress();

 

try {

$charge = \Stripe_Charge::create(array(

'amount' => $amount * 100,

'currency' => strtolower($order->getBaseCurrencyCode()),

'description' => sprintf('#%s, %s', $order->getIncrementId(), $order->getCustomerEmail()),

'card' => array(

'number' => $payment->getCcNumber(),

'number' => $payment->getCcNumber(),

'exp_month' => sprintf('%02d',$payment->getCcExpMonth()),

'exp_year' => $payment->getCcExpYear(),

'cvc' => $payment->getCcCid(),

'name' => $billing->getName(),

'address_line1' => $billing->getStreet(1),

'address_line2' => $billing->getStreet(2),

'address_zip' => $billing->getPostcode(),

'address_state' => $billing->getRegion(),

'address_country' => $billing->getCountry(),

),

));

 

$payment

->setTransactionId($charge->id)

->setIsTransactionClosed(0);

} catch (\Exception $e) {

$this->debugData($e->getMessage());

$this->_logger->logException(__('Payment capturing error.'));

throw new \Magento\Framework\Model\Exception(__('Payment capturing error.'));

}

 

return $this;

}

 

/**

* Payment refund

*

* @param \Magento\Framework\Object $payment

* @param float $amount

* @return $this

* @throws \Magento\Framework\Model\Exception

*/

public function refund(\Magento\Framework\Object $payment, $amount)

{

$transactionId = $payment->getParentTransactionId();

 

try {

\Stripe_Charge::retrieve($transactionId)->refund();

} catch (\Exception $e) {

$this->debugData($e->getMessage());

$this->_logger->logException(__('Payment refunding error.'));

throw new \Magento\Framework\Model\Exception(__('Payment refunding error.'));

}

 

$payment

->setTransactionId($transactionId . '-' . \Magento\Sales\Model\Order\Payment\Transaction::TYPE_REFUND)

->setParentTransactionId($transactionId)

->setIsTransactionClosed(1)

->setShouldCloseParentTransaction(1);

 

return $this;

}

 

/**

* Determine method availability based on quote amount and config data

*

* @param null $quote

* @return bool

*/

public function isAvailable($quote = null)

{

if ($quote && (

$quote->getBaseGrandTotal() < $this->_minAmount

|| ($this->_maxAmount && $quote->getBaseGrandTotal() > $this->_maxAmount))

) {

return false;

}

 

// if (!$this->getConfigData('api_key')) {

// return false;

// }

 

return parent::isAvailable($quote);

}

 

/**

* Availability for currency

*

* @param string $currencyCode

* @return bool

*/

public function canUseForCurrency($currencyCode)

{

if (!in_array($currencyCode, $this->_supportedCurrencyCodes)) {

return false;

}

return true;

}

}

 

[!--infotagslink--]

相关文章

  • 使用PHP+JavaScript将HTML页面转换为图片的实例分享

    这篇文章主要介绍了使用PHP+JavaScript将HTML元素转换为图片的实例分享,文后结果的截图只能体现出替换的字体,也不能说将静态页面转为图片可以加快加载,只是这种做法比较interesting XD需要的朋友可以参考下...2016-04-19
  • 关于JavaScript中name的意义冲突示例介绍

    在昨天的《Javascript权威指南》学习笔记之十:ECMAScript 5 增强的对象模型一文中,对于一段代码的调试出现了一个奇怪现象,现将源代码贴在下面: 复制代码 代码如下: <script type="text/javascript"> function Person(){}...2014-05-31
  • C#和JavaScript实现交互的方法

    最近做一个小项目不可避免的需要前端脚本与后台进行交互。由于是在asp.net中实现,故问题演化成asp.net中jiavascript与后台c#如何进行交互。...2020-06-25
  • javascript自定义的addClass()方法

    复制代码 代码如下: //element:需要添加新样式的元素,value:新的样式 function addClass(element, value ){ if (!element.className){ element.className = value; }else { newClassName = element.className; newClas...2014-05-31
  • JavaScript中的this关键字使用方法总结

    在javascritp中,不一定只有对象方法的上下文中才有this, 全局函数调用和其他的几种不同的上下文中也有this指代。 它可以是全局对象、当前对象或者任意对象,这完全取决于函数的调用方式。JavaScript 中函数的调用有以下...2015-03-15
  • 详解javascript数组去重问题

    首先,我想到的是另建一个结果数组,用来存储原始数组中不重复的数据。遍历原始数组依次跟结果数组中的元素进行比较,检测是否重复。于是乎,我写出了如下代码A: Array.prototype.clearRepetitionA = function(){ var resul...2015-11-08
  • javascript的事件触发器介绍的实现

    事件触发器从字面意思上可以很好的理解,就是用来触发事件的,但是有些没有用过的朋友可能就会迷惑了,事件不是通常都由用户在页面上的实际操作来触发的吗?这个观点不完全正确,因为有些事件必须由程序来实现,如自定义事件,jQue...2014-06-07
  • JavaScript中逗号运算符介绍及使用示例

    有一道js面试题,题目是这样的:下列代码的执行结果是什么,为什么? 复制代码 代码如下: var i, j, k; for (i=0, j=0; i<10, j<6; i++, j++) { k = i+j; } document.write(k); 答案是显示10,这道题主要考察JavaScript的逗...2015-03-15
  • JavaScript预解析,对象详解

    这篇文章主要介绍了JavaScript预解析,对象的的相关资料,小编觉得这篇文章写的还不错,需要的朋友可以参考下,希望能够给你带来帮助...2021-11-10
  • JavaScript学习笔记整理_setTimeout的应用

    下面小编就为大家带来一篇JavaScript学习笔记整理_setTimeout的应用。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2016-10-03
  • Javascript类型转换的规则实例解析

    这篇文章主要介绍了Javascript类型转换的规则实例解析,涉及到javascript类型转换相关知识,对本文感兴趣的朋友一起学习吧...2016-02-27
  • 详解JavaScript操作HTML DOM的基本方式

    通过 HTML DOM,可访问 JavaScript HTML 文档的所有元素。 HTML DOM (文档对象模型) 当网页被加载时,浏览器会创建页面的文档对象模型(Document Object Model)。 HTML DOM 模型被构造为对象的树: 通过可编程的对象模型,Java...2015-10-23
  • ActiveX控件与Javascript之间的交互示例

    1、ActiveX向Javascript传参 复制代码 代码如下: <script language="javascript" for="objectname" event="fun1(arg)"> fun2(arg); </script> objectname为ActiveX控件名,通过<object>标签里的id属性设定,如下; 复制...2014-06-07
  • JavaScript获取浏览器信息的方法

    Window有navigator对象让我们得知浏览器的全部信息.我们可以利用一系列的API函数得知浏览器的信息.JavaScript代码如下:function message(){ txt = "<p>浏览器代码名: " + navigator.appCodeName + "</p>";txt+= "<p>...2015-11-24
  • 学习JavaScript设计模式之装饰者模式

    这篇文章主要为大家介绍了JavaScript设计模式中的装饰者模式,对JavaScript设计模式感兴趣的小伙伴们可以参考一下...2016-01-21
  • JavaScript中的数组遍历forEach()与map()方法以及兼容写法介绍

    下面小编就为大家带来一篇JavaScript中的数组遍历forEach()与map()方法以及兼容写法介绍。小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2016-05-20
  • javascript设计模式之解释器模式详解

    神马是“解释器模式”?先翻开《GOF》看看Definition:给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。在开篇之前还是要科普几个概念: 抽象语法树: 解释器模式并未解释如...2014-06-07
  • 跟我学习javascript的最新标准ES6

    虽然ES6都还没真正发布,但已经有用ES6重写的程序了,各种关于ES789的提议已经开始了,这你敢信。潮流不是我等大众所能追赶的。潮流虽然太快,但我们不停下学习的步伐,就不会被潮流丢下的,下面来领略下ES6中新特性,一堵新生代JS...2015-11-24
  • JavaScript操作URL的相关内容集锦

    ---恢复内容开始---1.location.href.....(1)self.loction.href="http://www.cnblogs.com/url" window.location.href="http://www.cnblogs.com/url" 以上两个用法相同均为在当前页面打开URL页面 (2)this.locati...2015-10-30
  • 基于JavaScript如何实现私有成员的语法特征及私有成员的实现方式

    前言在面向对象的编程范式中,封装都是必不可少的一个概念,而在诸如 Java,C++等传统的面向对象的语言中, 私有成员是实现封装的一个重要途径。但在 JavaScript 中,确没有在语法特性上对私有成员提供支持, 这也使得开发人员使...2015-10-30