微信支付和分享功能插件

通过微信分享和支付插件可以轻松的通过js调用微信的分享,支付和认证功能

微信后台参数说明

如果需要使用微信分享,需要上微信开放平台(https://open.weixin.qq.com/)申请微信分享功能,如果需要支付和登录认证还要单独申请权限。

申请审批后得到app_id参数(样式AppID:wx21fb4d35f5eba46b),这个参数填到LBuilder后台插件设置处。微信对参数要求严格,所以注意检查包名称,app_id,签名证书指纹确保准确无误,否则会出现闪一下失败之类的现象

使用微信分享功能

Wechat.share({
    text: "This is just a plain string",
    scene: Wechat.Scene.TIMELINE   // share to Timeline
}, function (data) {
    alert("Success"+JSON.stringify(data));
}, function (reason) {
    alert("Failed: " + JSON.stringify(reason));
});

分享的第一个参数是被分享的文本内容和分享场景的json,第二个参数和第三参数是分享完成和分享失败的回调函数,后面的其他功能也基本类似,只是具体参数有出入

对于分享文本,则第一个参数包含text和scene参数,text是要被分享的文字,scene是分享到的场景包括朋友圈,联系人,收藏夹等

分享图片的代码如下,与分享文字的区别是text参数换成了一个json描述的对象

Wechat.share({
    message: {
        title: "Hi, there",
        description: "This is description.",
        thumb: "www/zhifubao.jpg",
        mediaTagName: "TEST-TAG-001",
        messageExt: "这是第三方带的测试字段",
        messageAction: "<action>dotalist</action>",
        media:{
            type:  Wechat.Type.IMAGE,
            image: "https://www.baidu.com/img/bd_logo1.png"
        } 
    },
    scene: Wechat.Scene.TIMELINE   // share to Timeline
}, function (data) {
    alert("Success"+JSON.stringify(data));
}, function (reason) {
    alert("Failed: " + JSON.stringify(reason));
});

再看一个分享链接的,和上面分享图片的更像,只要把media类型修改下就行

Wechat.share({
    message: {
	title: "Hi, here",
        description: "That is description.",
        thumb: "www/img/thumbnail.png",
        mediaTagName: "TEST-TAG-002",
        messageExt: "这是第三方带的测试字段ddd",
        messageAction: "<action>dotalist</action>",
        media: {
            type: Wechat.Type.WEBPAGE,
            webpageUrl: "http://www.appuploader.net/"
        }
    },
    scene: Wechat.Scene.TIMELINE   // share to Timeline
}, function (data) {
    alert("Success"+JSON.stringify(data));
}, function (reason) {
    alert("Failed: " + JSON.stringify(reason));
});


使用微信支付功能

var params = {
    partnerid: '10000100', // merchant id
    prepayid: 'wx201411101639507cbf6ffd8b0779950874', // prepay id
    noncestr: '1add1a30ac87aa2db72f57a2375d8fec', // nonce
    timestamp: '1439531364', // timestamp
    sign: '0CB01533B8C1EF103065174F50BCA001', // signed string
};

Wechat.sendPaymentRequest(params, function (data) {
    alert("Success"+JSON.stringify(data));
}, function (reason) {
    alert("Failed: " + JSON.stringify(reason));
});

微信支付需要单独申请支付权限,否则支付无法完成。支付参数请参考微信支付接入指南

php类型的支付服务器端代码示例

<?php 
// APPID (开户邮件中可查看)
define("APP_ID",  "YOUR_APP_ID");

// 商户号 (开户邮件中可查看)
define("MCH_ID",  "YOUR_MCH_ID");

// 商户支付密钥 (https://pay.weixin.qq.com/index.php/account/api_cert)
define("APP_KEY", "YOUR_APP_KEY");

// get prepay id
$prepay_id = generatePrepayId(APP_ID, MCH_ID);

// re-sign it
$response = array(
    'appid'     => APP_ID,
    'partnerid' => MCH_ID,
    'prepayid'  => $prepay_id,
    'package'   => 'Sign=WXPay',
    'noncestr'  => generateNonce(),
    'timestamp' => time(),
);
$response['sign'] = calculateSign($response, APP_KEY);

// send it to APP
echo json_encode($response);

/**
 * Generate a nonce string
 *
 * @link https://pay.weixin.qq.com/wiki/doc/api/app.php?chapter=4_3
 */
function generateNonce()
{
    return md5(uniqid('', true));
}

/**
 * Get a sign string from array using app key
 *
 * @link https://pay.weixin.qq.com/wiki/doc/api/app.php?chapter=4_3
 */
function calculateSign($arr, $key)
{
    ksort($arr);

    $buff = "";
    foreach ($arr as $k => $v) {
        if ($k != "sign" && $k != "key" && $v != "" && !is_array($v)){
            $buff .= $k . "=" . $v . "&";
        }
    }

    $buff = trim($buff, "&");

    return strtoupper(md5($buff . "&key=" . $key));
}

/**
 * Get xml from array
 */
function getXMLFromArray($arr)
{
    $xml = "<xml>";
    foreach ($arr as $key => $val) {
        if (is_numeric($val)) {
            $xml .= sprintf("<%s>%s</%s>", $key, $val, $key);
        } else {
            $xml .= sprintf("<%s><![CDATA[%s]]></%s>", $key, $val, $key);
        }
    }

    $xml .= "</xml>";

    return $xml;
}

/**
 * Generate a prepay id
 *
 * @link https://pay.weixin.qq.com/wiki/doc/api/app.php?chapter=9_1
 */
function generatePrepayId($app_id, $mch_id)
{
    $params = array(
        'appid'            => $app_id,
        'mch_id'           => $mch_id,
        'nonce_str'        => generateNonce(),
        'body'             => 'Test product name',
        'out_trade_no'     => time(),
        'total_fee'        => 1,
        'spbill_create_ip' => '8.8.8.8',
        'notify_url'       => 'http://localhost',
        'trade_type'       => 'APP',
    );

    // add sign
    $params['sign'] = calculateSign($params, APP_KEY);

    // create xml
    $xml = getXMLFromArray($params);

    // send request
    $ch = curl_init();

    curl_setopt_array($ch, array(
        CURLOPT_URL            => "https://api.mch.weixin.qq.com/pay/unifiedorder",
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => array('Content-Type: text/xml'),
        CURLOPT_POSTFIELDS     => $xml,
    ));

    $result = curl_exec($ch);
    curl_close($ch);

    // get the prepay id from response
    $xml = simplexml_load_string($result);
    return (string)$xml->prepay_id;
}

微信登录认证功能

微信提供用户app直接使用微信功能登录,但是要求app单独申请权限,当权限开通后方可使用

var scope = "snsapi_userinfo";
var state = "_" + (+new Date());
Wechat.auth(scope, state, function (data) {
    // you may use response.code to get the access token.
    alert(JSON.stringify(data));
}, function (reason) {
    alert("Failed: " + JSON.stringify(reason));
});

scope是申请的读取用户资料范围,state是请求状态码,其他是认证成功和失败的回调函数,更多的请求参数和返回数据结构可以参考微信登录认证

下面是一个完整的使用微信功能的例子代码

<!DOCTYPE>
<html>
	<head>
		<title>lbuilder demo</title>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"/>
		<meta http-equiv="Cache-Control" content="no-siteapp"/>
		<script type="text/javascript">
			function isInstall(){
			
			  Wechat.isInstalled(function (installed) {
				    alert("Wechat installed: " + (installed ? "Yes" : "No"));
				}, function (reason) {
				    alert("Failed: " + JSON.stringify(reason));
				});
			}
			function auth(){
				var scope = "snsapi_userinfo";
				var state = "_" + (+new Date());
				Wechat.auth(scope, state, function (data) {
				    // you may use response.code to get the access token.
				    alert(JSON.stringify(data));
				}, function (reason) {
				    alert("Failed: " + JSON.stringify(reason));
				});
			}
			function shareText(){
				Wechat.share({
				    text: "This is just a plain string",
				    scene: Wechat.Scene.TIMELINE   // share to Timeline
				}, function (data) {
				    alert("Success"+JSON.stringify(data));
				}, function (reason) {
				    alert("Failed: " + JSON.stringify(reason));
				});
			}
			function shareImage(){
				Wechat.share({
				    message: {
				        title: "Hi, there",
				        description: "This is description.",
				        thumb: "www/zhifubao.jpg",
				        mediaTagName: "TEST-TAG-001",
				        messageExt: "这是第三方带的测试字段",
				        messageAction: "<action>dotalist</action>",
				        media:{
				            type:  Wechat.Type.IMAGE,
				            image: "https://www.baidu.com/img/bd_logo1.png"
				        } 
				    },
				    scene: Wechat.Scene.TIMELINE   // share to Timeline
				}, function (data) {
				    alert("Success"+JSON.stringify(data));
				}, function (reason) {
				    alert("Failed: " + JSON.stringify(reason));
				});
			}
			function shareLink(){
				Wechat.share({
				    message: {
						title: "Hi, here",
				        description: "That is description.",
				        thumb: "www/img/thumbnail.png",
				        mediaTagName: "TEST-TAG-002",
				        messageExt: "这是第三方带的测试字段ddd",
				        messageAction: "<action>dotalist</action>",
				        media: {
				            type: Wechat.Type.WEBPAGE,
				            webpageUrl: "http://www.appuploader.net/"
				        }
				    },
				    scene: Wechat.Scene.TIMELINE   // share to Timeline
				}, function (data) {
				    alert("Success"+JSON.stringify(data));
				}, function (reason) {
				    alert("Failed: " + JSON.stringify(reason));
				});
			}
			function startPay(){
				var params = {
				    partnerid: '10000100', // merchant id
				    prepayid: 'wx201411101639507cbf6ffd8b0779950874', // prepay id
				    noncestr: '1add1a30ac87aa2db72f57a2375d8fec', // nonce
				    timestamp: '1439531364', // timestamp
				    sign: '0CB01533B8C1EF103065174F50BCA001', // signed string
				};

				Wechat.sendPaymentRequest(params, function (data) {
				    alert("Success"+JSON.stringify(data));
				}, function (reason) {
				    alert("Failed: " + JSON.stringify(reason));
				});
			}
			function invoices(){
				var params = {
				    timeStamp: '1510198391', // timeStamp
				    signType: 'SHA1', // sign type
				    cardSign: 'dff450eeeed08120159d285e79737173aec3df94', // cardSign
				    nonceStr: '5598190f-5fb3-4bff-8314-fd189ab4e4b8', // nonce
				};

				Wechat.chooseInvoiceFromWX(params,function(data){
				    console.log(data);
				   alert("Success"+JSON.stringify(data));
				},function(reason){
				     alert("Failed: " + JSON.stringify(reason));
				});
			}
		
		</script>
	</head>
	<body>
	<h3>Lbuilder demo line</h3>
	
	<a href="javascript:isInstall();">isInstall</a><br/><br/>
	<a href="javascript:auth();">auth</a><br/><br/>
	<a href="javascript:shareText();">shareText</a><br/><br/>
	<a href="javascript:shareImage();">shareImage</a><br/><br/>
	<a href="javascript:startPay();">startPay</a><br/><br/>
	<a href="javascript:invoices();">invoices</a><br/><br/>
	</body>
</html>